text
stringlengths
54
60.6k
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: toolbar.cpp // Purpose: Implementation of wxExToolBar class // Author: Anton van Wezenbeek // Created: 2010-03-26 // RCS-ID: $Id$ // Copyright: (c) 2010 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/extension/toolbar.h> #include <wx/extension/art.h> #include <wx/extension/filedlg.h> #include <wx/extension/frame.h> #include <wx/extension/frd.h> #include <wx/extension/stcfile.h> #include <wx/extension/util.h> #if wxUSE_GUI #if wxUSE_AUI // Cannot use wxNewId here, as these are used in a switch statement. enum { ID_MATCH_WHOLE_WORD = 100, ID_MATCH_CASE, ID_REGULAR_EXPRESSION, ID_EDIT_HEX_MODE, ID_SYNC_MODE, }; BEGIN_EVENT_TABLE(wxExToolBar, wxAuiToolBar) EVT_CHECKBOX(ID_EDIT_HEX_MODE, wxExToolBar::OnCommand) EVT_CHECKBOX(ID_SYNC_MODE, wxExToolBar::OnCommand) END_EVENT_TABLE() wxExToolBar::wxExToolBar(wxExFrame* frame, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) : wxAuiToolBar(frame, id, pos, size, style | wxAUI_TB_HORZ_TEXT) , m_Frame(frame) , m_HexModeCheckBox(NULL) , m_SyncCheckBox(NULL) { } wxExToolBar::~wxExToolBar() { if (m_HexModeCheckBox != NULL) { wxConfigBase::Get()->Write("HexMode", m_HexModeCheckBox->GetValue()); } } void wxExToolBar::AddControls() { AddTool(wxID_OPEN); AddTool(wxID_SAVE); AddTool(wxID_PRINT); AddSeparator(); AddTool(wxID_FIND); #ifdef __WXGTK__ // wxID_EXECUTE is not part of art provider, but GTK directly, // so the following does not present a bitmap. AddSeparator(); AddTool(wxID_EXECUTE); #endif AddSeparator(); AddControl( m_HexModeCheckBox = new wxCheckBox( this, ID_EDIT_HEX_MODE, "Hex")); // m_HexModeCheckBox->SetBackgroundColour(m_Frame->GetBackgroundColour()); // AddTool(ID_SYNC_MODE, "Sync", wxNullBitmap, wxEmptyString, wxITEM_CHECK); AddControl( m_SyncCheckBox = new wxCheckBox( this, ID_SYNC_MODE, "Sync")); #if wxUSE_TOOLTIPS m_HexModeCheckBox->SetToolTip(_("View in hex mode")); m_SyncCheckBox->SetToolTip(_("Synchronize modified files")); #endif m_HexModeCheckBox->SetValue(wxConfigBase::Get()->ReadBool("HexMode", false)); // default no hex m_SyncCheckBox->SetValue(wxConfigBase::Get()->ReadBool("AllowSync", true)); Realize(); } wxAuiToolBarItem* wxExToolBar::AddTool( int toolId, const wxString& label, const wxBitmap& bitmap, const wxString& shortHelp, wxItemKind kind) { const wxExStockArt art(toolId); if (art.GetBitmap().IsOk()) { return wxAuiToolBar::AddTool( toolId, wxEmptyString, art.GetBitmap(wxART_TOOLBAR, GetToolBitmapSize()), wxGetStockLabel(toolId, wxSTOCK_NOFLAGS), kind); } else { return wxAuiToolBar::AddTool( toolId, label, bitmap, shortHelp, kind); } } void wxExToolBar::OnCommand(wxCommandEvent& event) { switch (event.GetId()) { case ID_EDIT_HEX_MODE: wxConfigBase::Get()->Write("HexMode", m_HexModeCheckBox->GetValue()); { wxExSTCFile* stc = m_Frame->GetSTC(); if (stc != NULL) { long flags = 0; if (m_HexModeCheckBox->GetValue()) flags |= wxExSTCFile::STC_WIN_HEX; wxExFileDialog dlg(m_Frame, stc); if (dlg.ShowModalIfChanged() == wxID_CANCEL) return; stc->Open(stc->GetFileName(), 0, wxEmptyString, flags); } } break; case ID_SYNC_MODE: wxConfigBase::Get()->Write("AllowSync", m_SyncCheckBox->GetValue()); break; default: wxFAIL; break; } } /// Offers a find combobox that allows you to find text /// on a current STC on an wxExFrame. class ComboBox : public wxComboBox { public: /// Constructor. Fills the combobox box with values from FindReplace from config. ComboBox( wxWindow* parent, wxExFrame* frame, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize); private: void OnCommand(wxCommandEvent& event); void OnKey(wxKeyEvent& event); wxExFrame* m_Frame; DECLARE_EVENT_TABLE() }; BEGIN_EVENT_TABLE(ComboBox, wxComboBox) EVT_CHAR(ComboBox::OnKey) EVT_MENU(wxID_DELETE, ComboBox::OnCommand) END_EVENT_TABLE() ComboBox::ComboBox( wxWindow* parent, wxExFrame* frame, wxWindowID id, const wxPoint& pos, const wxSize& size) : wxComboBox(parent, id, wxEmptyString, pos, size) , m_Frame(frame) { const int accels = 1; wxAcceleratorEntry entries[accels]; entries[0].Set(wxACCEL_NORMAL, WXK_DELETE, wxID_DELETE); wxAcceleratorTable accel(accels, entries); SetAcceleratorTable(accel); SetFont(wxConfigBase::Get()->ReadObject("FindFont", wxSystemSettings::GetFont(wxSYS_OEM_FIXED_FONT))); wxExComboBoxFromList( this, wxExFindReplaceData::Get()->GetFindStrings()); // And override the value set by previous, as we want text to be same as in Find. SetValue(wxExFindReplaceData::Get()->GetFindString()); } void ComboBox::OnCommand(wxCommandEvent& event) { // README: The delete key default behaviour does not delete the char right from insertion point. // Instead, the event is sent to the editor and a char is deleted from the editor. // Therefore implement the delete here. switch (event.GetId()) { case wxID_DELETE: Remove(GetInsertionPoint(), GetInsertionPoint() + 1); break; default: wxFAIL; break; } } void ComboBox::OnKey(wxKeyEvent& event) { const int key = event.GetKeyCode(); if (key == WXK_RETURN) { wxExSTC* stc = m_Frame->GetSTC(); if (stc != NULL) { stc->FindNext(GetValue()); wxExFindReplaceData::Get()->SetFindString(GetValue()); Clear(); // so we can append again wxExComboBoxFromList(this, wxExFindReplaceData::Get()->GetFindStrings()); } } else { event.Skip(); } } BEGIN_EVENT_TABLE(wxExFindToolBar, wxExToolBar) EVT_CHECKBOX(ID_MATCH_WHOLE_WORD, wxExFindToolBar::OnCommand) EVT_CHECKBOX(ID_MATCH_CASE, wxExFindToolBar::OnCommand) EVT_CHECKBOX(ID_REGULAR_EXPRESSION, wxExFindToolBar::OnCommand) EVT_MENU(wxID_DOWN, wxExFindToolBar::OnCommand) EVT_MENU(wxID_UP, wxExFindToolBar::OnCommand) EVT_UPDATE_UI(wxID_DOWN, wxExFindToolBar::OnUpdateUI) EVT_UPDATE_UI(wxID_UP, wxExFindToolBar::OnUpdateUI) END_EVENT_TABLE() wxExFindToolBar::wxExFindToolBar( wxExFrame* frame, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) : wxExToolBar(frame, id, pos, size, style) { Initialize(); // And place the controls on the toolbar. AddControl(m_ComboBox); AddSeparator(); AddTool( wxID_DOWN, wxEmptyString, wxArtProvider::GetBitmap(wxART_GO_DOWN, wxART_TOOLBAR, GetToolBitmapSize()), _("Find next")); AddTool( wxID_UP, wxEmptyString, wxArtProvider::GetBitmap(wxART_GO_UP, wxART_TOOLBAR, GetToolBitmapSize()), _("Find previous")); AddSeparator(); AddControl(m_MatchWholeWord); AddControl(m_MatchCase); AddControl(m_RegularExpression); Realize(); } void wxExFindToolBar::Initialize() { #ifdef __WXMSW__ const wxSize size(150, 20); #else const wxSize size(150, -1); #endif ComboBox* cb = new ComboBox(this, m_Frame, wxID_ANY, wxDefaultPosition, size); m_ComboBox = cb; m_MatchCase = new wxCheckBox(this, ID_MATCH_CASE, wxExFindReplaceData::Get()->GetTextMatchCase()); m_MatchWholeWord = new wxCheckBox(this, ID_MATCH_WHOLE_WORD, wxExFindReplaceData::Get()->GetTextMatchWholeWord()); m_RegularExpression= new wxCheckBox(this, ID_REGULAR_EXPRESSION, wxExFindReplaceData::Get()->GetTextRegEx()); m_MatchCase->SetValue(wxExFindReplaceData::Get()->MatchCase()); m_MatchWholeWord->SetValue(wxExFindReplaceData::Get()->MatchWord()); m_RegularExpression->SetValue(wxExFindReplaceData::Get()->UseRegularExpression()); } void wxExFindToolBar::OnCommand(wxCommandEvent& event) { switch (event.GetId()) { case wxID_DOWN: case wxID_UP: { wxExSTC* stc = m_Frame->GetSTC(); if (stc != NULL) { stc->FindNext(m_ComboBox->GetValue(), (event.GetId() == wxID_DOWN)); } } break; case ID_MATCH_WHOLE_WORD: wxExFindReplaceData::Get()->SetMatchWord( m_MatchWholeWord->GetValue()); break; case ID_MATCH_CASE: wxExFindReplaceData::Get()->SetMatchCase( m_MatchCase->GetValue()); break; case ID_REGULAR_EXPRESSION: wxExFindReplaceData::Get()->SetUseRegularExpression( m_RegularExpression->GetValue()); break; default: wxFAIL; break; } } void wxExFindToolBar::OnUpdateUI(wxUpdateUIEvent& event) { event.Enable(!m_ComboBox->GetValue().empty()); } #endif // wxUSE_AUI #endif // wxUSE_GUI <commit_msg>reordered code<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: toolbar.cpp // Purpose: Implementation of wxExToolBar class // Author: Anton van Wezenbeek // Created: 2010-03-26 // RCS-ID: $Id$ // Copyright: (c) 2010 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/extension/toolbar.h> #include <wx/extension/art.h> #include <wx/extension/filedlg.h> #include <wx/extension/frame.h> #include <wx/extension/frd.h> #include <wx/extension/stcfile.h> #include <wx/extension/util.h> #if wxUSE_GUI #if wxUSE_AUI // Cannot use wxNewId here, as these are used in a switch statement. enum { ID_MATCH_WHOLE_WORD = 100, ID_MATCH_CASE, ID_REGULAR_EXPRESSION, ID_EDIT_HEX_MODE, ID_SYNC_MODE, }; // Support class. // Offers a find combobox that allows you to find text // on a current STC on an wxExFrame. class ComboBox : public wxComboBox { public: /// Constructor. Fills the combobox box with values from FindReplace from config. ComboBox( wxWindow* parent, wxExFrame* frame, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize); private: void OnCommand(wxCommandEvent& event); void OnKey(wxKeyEvent& event); wxExFrame* m_Frame; DECLARE_EVENT_TABLE() }; BEGIN_EVENT_TABLE(wxExToolBar, wxAuiToolBar) EVT_CHECKBOX(ID_EDIT_HEX_MODE, wxExToolBar::OnCommand) EVT_CHECKBOX(ID_SYNC_MODE, wxExToolBar::OnCommand) END_EVENT_TABLE() wxExToolBar::wxExToolBar(wxExFrame* frame, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) : wxAuiToolBar(frame, id, pos, size, style | wxAUI_TB_HORZ_TEXT) , m_Frame(frame) , m_HexModeCheckBox(NULL) , m_SyncCheckBox(NULL) { } wxExToolBar::~wxExToolBar() { if (m_HexModeCheckBox != NULL) { wxConfigBase::Get()->Write("HexMode", m_HexModeCheckBox->GetValue()); } } void wxExToolBar::AddControls() { AddTool(wxID_OPEN); AddTool(wxID_SAVE); AddTool(wxID_PRINT); AddSeparator(); AddTool(wxID_FIND); #ifdef __WXGTK__ // wxID_EXECUTE is not part of art provider, but GTK directly, // so the following does not present a bitmap. AddSeparator(); AddTool(wxID_EXECUTE); #endif AddSeparator(); AddControl( m_HexModeCheckBox = new wxCheckBox( this, ID_EDIT_HEX_MODE, "Hex")); // m_HexModeCheckBox->SetBackgroundColour(m_Frame->GetBackgroundColour()); // AddTool(ID_SYNC_MODE, "Sync", wxNullBitmap, wxEmptyString, wxITEM_CHECK); AddControl( m_SyncCheckBox = new wxCheckBox( this, ID_SYNC_MODE, "Sync")); #if wxUSE_TOOLTIPS m_HexModeCheckBox->SetToolTip(_("View in hex mode")); m_SyncCheckBox->SetToolTip(_("Synchronize modified files")); #endif m_HexModeCheckBox->SetValue(wxConfigBase::Get()->ReadBool("HexMode", false)); // default no hex m_SyncCheckBox->SetValue(wxConfigBase::Get()->ReadBool("AllowSync", true)); Realize(); } wxAuiToolBarItem* wxExToolBar::AddTool( int toolId, const wxString& label, const wxBitmap& bitmap, const wxString& shortHelp, wxItemKind kind) { const wxExStockArt art(toolId); if (art.GetBitmap().IsOk()) { return wxAuiToolBar::AddTool( toolId, wxEmptyString, art.GetBitmap(wxART_TOOLBAR, GetToolBitmapSize()), wxGetStockLabel(toolId, wxSTOCK_NOFLAGS), kind); } else { return wxAuiToolBar::AddTool( toolId, label, bitmap, shortHelp, kind); } } void wxExToolBar::OnCommand(wxCommandEvent& event) { switch (event.GetId()) { case ID_EDIT_HEX_MODE: wxConfigBase::Get()->Write("HexMode", m_HexModeCheckBox->GetValue()); { wxExSTCFile* stc = m_Frame->GetSTC(); if (stc != NULL) { long flags = 0; if (m_HexModeCheckBox->GetValue()) flags |= wxExSTCFile::STC_WIN_HEX; wxExFileDialog dlg(m_Frame, stc); if (dlg.ShowModalIfChanged() == wxID_CANCEL) return; stc->Open(stc->GetFileName(), 0, wxEmptyString, flags); } } break; case ID_SYNC_MODE: wxConfigBase::Get()->Write("AllowSync", m_SyncCheckBox->GetValue()); break; default: wxFAIL; break; } } BEGIN_EVENT_TABLE(wxExFindToolBar, wxExToolBar) EVT_CHECKBOX(ID_MATCH_WHOLE_WORD, wxExFindToolBar::OnCommand) EVT_CHECKBOX(ID_MATCH_CASE, wxExFindToolBar::OnCommand) EVT_CHECKBOX(ID_REGULAR_EXPRESSION, wxExFindToolBar::OnCommand) EVT_MENU(wxID_DOWN, wxExFindToolBar::OnCommand) EVT_MENU(wxID_UP, wxExFindToolBar::OnCommand) EVT_UPDATE_UI(wxID_DOWN, wxExFindToolBar::OnUpdateUI) EVT_UPDATE_UI(wxID_UP, wxExFindToolBar::OnUpdateUI) END_EVENT_TABLE() wxExFindToolBar::wxExFindToolBar( wxExFrame* frame, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) : wxExToolBar(frame, id, pos, size, style) { Initialize(); // And place the controls on the toolbar. AddControl(m_ComboBox); AddSeparator(); AddTool( wxID_DOWN, wxEmptyString, wxArtProvider::GetBitmap(wxART_GO_DOWN, wxART_TOOLBAR, GetToolBitmapSize()), _("Find next")); AddTool( wxID_UP, wxEmptyString, wxArtProvider::GetBitmap(wxART_GO_UP, wxART_TOOLBAR, GetToolBitmapSize()), _("Find previous")); AddSeparator(); AddControl(m_MatchWholeWord); AddControl(m_MatchCase); AddControl(m_RegularExpression); Realize(); } void wxExFindToolBar::Initialize() { #ifdef __WXMSW__ const wxSize size(150, 20); #else const wxSize size(150, -1); #endif ComboBox* cb = new ComboBox(this, m_Frame, wxID_ANY, wxDefaultPosition, size); m_ComboBox = cb; m_MatchCase = new wxCheckBox(this, ID_MATCH_CASE, wxExFindReplaceData::Get()->GetTextMatchCase()); m_MatchWholeWord = new wxCheckBox(this, ID_MATCH_WHOLE_WORD, wxExFindReplaceData::Get()->GetTextMatchWholeWord()); m_RegularExpression= new wxCheckBox(this, ID_REGULAR_EXPRESSION, wxExFindReplaceData::Get()->GetTextRegEx()); m_MatchCase->SetValue(wxExFindReplaceData::Get()->MatchCase()); m_MatchWholeWord->SetValue(wxExFindReplaceData::Get()->MatchWord()); m_RegularExpression->SetValue(wxExFindReplaceData::Get()->UseRegularExpression()); } void wxExFindToolBar::OnCommand(wxCommandEvent& event) { switch (event.GetId()) { case wxID_DOWN: case wxID_UP: { wxExSTC* stc = m_Frame->GetSTC(); if (stc != NULL) { stc->FindNext(m_ComboBox->GetValue(), (event.GetId() == wxID_DOWN)); } } break; case ID_MATCH_WHOLE_WORD: wxExFindReplaceData::Get()->SetMatchWord( m_MatchWholeWord->GetValue()); break; case ID_MATCH_CASE: wxExFindReplaceData::Get()->SetMatchCase( m_MatchCase->GetValue()); break; case ID_REGULAR_EXPRESSION: wxExFindReplaceData::Get()->SetUseRegularExpression( m_RegularExpression->GetValue()); break; default: wxFAIL; break; } } void wxExFindToolBar::OnUpdateUI(wxUpdateUIEvent& event) { event.Enable(!m_ComboBox->GetValue().empty()); } // Implementation of support class. BEGIN_EVENT_TABLE(ComboBox, wxComboBox) EVT_CHAR(ComboBox::OnKey) EVT_MENU(wxID_DELETE, ComboBox::OnCommand) END_EVENT_TABLE() ComboBox::ComboBox( wxWindow* parent, wxExFrame* frame, wxWindowID id, const wxPoint& pos, const wxSize& size) : wxComboBox(parent, id, wxEmptyString, pos, size) , m_Frame(frame) { const int accels = 1; wxAcceleratorEntry entries[accels]; entries[0].Set(wxACCEL_NORMAL, WXK_DELETE, wxID_DELETE); wxAcceleratorTable accel(accels, entries); SetAcceleratorTable(accel); SetFont(wxConfigBase::Get()->ReadObject("FindFont", wxSystemSettings::GetFont(wxSYS_OEM_FIXED_FONT))); wxExComboBoxFromList( this, wxExFindReplaceData::Get()->GetFindStrings()); // And override the value set by previous, as we want text to be same as in Find. SetValue(wxExFindReplaceData::Get()->GetFindString()); } void ComboBox::OnCommand(wxCommandEvent& event) { // README: The delete key default behaviour does not delete the char right from insertion point. // Instead, the event is sent to the editor and a char is deleted from the editor. // Therefore implement the delete here. switch (event.GetId()) { case wxID_DELETE: Remove(GetInsertionPoint(), GetInsertionPoint() + 1); break; default: wxFAIL; break; } } void ComboBox::OnKey(wxKeyEvent& event) { const int key = event.GetKeyCode(); if (key == WXK_RETURN) { wxExSTC* stc = m_Frame->GetSTC(); if (stc != NULL) { stc->FindNext(GetValue()); wxExFindReplaceData::Get()->SetFindString(GetValue()); Clear(); // so we can append again wxExComboBoxFromList(this, wxExFindReplaceData::Get()->GetFindStrings()); } } else { event.Skip(); } } #endif // wxUSE_AUI #endif // wxUSE_GUI <|endoftext|>
<commit_before>/** * @file trajectory_controller.cpp * @author Matheus Vieira Portela * @date 03/08/2015 * * @attention Copyright (C) 2015 UnBall Robot Soccer Team * * @brief Control robots trajectory by applying potential fields. */ #include <unball/strategy/trajectory_controller.hpp> TrajectoryController::TrajectoryController() { player_[0] = new AssistentPlayer(); player_[1] = new AssistentPlayer(); player_[2] = new Goalkeeper(); direct_motion_ = true; } TrajectoryController::~TrajectoryController() { for (int i = 2; i >= 0; --i) delete player_[i]; } void TrajectoryController::run() { Vector resultant_force; for (int i=0;i<3;i++) { player_[i]->buildPotentialFields(i); resultant_force = player_[i]->calculateResultantForce(i); //ROS_ERROR("resultant_force: mag: %.2f ang: %.2f", resultant_force.getMagnitude(), resultant_force.getDirection()*180/M_PI); player_[i]->clearPotentialFields(); controlRobot(i, resultant_force); } robot[2].setAngVel(5); robot[2].setLinVel(0); } void TrajectoryController::controlRobot(int robot_number, Vector force) { // Use histeresis to void quickly changing direction. float error_margin = 15*M_PI/180; if (direct_motion_) { if (fabs(math::reduceAngle(M_PI + force.getDirection() - robot[robot_number].getTh())) > M_PI/2 + error_margin) { direct_motion_ = false; } } else { if (fabs(math::reduceAngle(M_PI + force.getDirection() - robot[robot_number].getTh())) < M_PI/2 - error_margin) { direct_motion_ = true; } } //HACK: issue80 - We have to add M_PI because the force is being calculated backwards if (direct_motion_) { move(robot_number, force.getMagnitude()); turn(robot_number, force.getDirection()); } else { move(robot_number, -force.getMagnitude()); turn(robot_number, math::invertAngle(force.getDirection())); } } void TrajectoryController::move(int robot_number, float distance) { const float DIST_KP = 1; const float distance_tolerance = 0.05; // m float lin_vel = DIST_KP*distance; // P control // if (fabs(distance) > distance_tolerance) robot[robot_number].setLinVel(lin_vel); // else // robot[robot_number].setLinVel(0); } void TrajectoryController::turn(int robot_number, float angle) { const float ANG_KP = 0.008; const float ANG_KD = 0; //HACK: issue80 - Should be: angle - robot.getTh() float angle_error = math::reduceAngle(robot[robot_number].getTh() - angle); float angle_error_d = angle_error - angle_error_prev_; float ang_vel = ANG_KP*angle_error + ANG_KD*angle_error_d; // PD control angle_error_prev_ = angle_error; robot[robot_number].setAngVel(ang_vel); } void TrajectoryController::stopRobot(int robot_number) { robot[robot_number].setAngVel(0); robot[robot_number].setLinVel(0); } void TrajectoryController::updatePlayer(int robot_number, player_behaviour behaviour) { delete player_[robot_number]; if (behaviour == INITIAL_GOALKEEPER) player_[robot_number] = new InitialGoalkeeper(); if (behaviour == GOALKEEPER) player_[robot_number] = new Goalkeeper(); if (behaviour == REGULAR_PLAYER) player_[robot_number] = new RegularPlayer(); if (behaviour == KICKER_PLAYER) player_[robot_number] = new KickerPlayer(); if (behaviour == ASSISTENT_PLAYER) player_[robot_number] = new AssistentPlayer(); if (behaviour == GOALKEEPER_KICKER) player_[robot_number] = new GoalkeeperKicker(); } Player* TrajectoryController::getPlayer(int robot_number) { return player_[robot_number]; } <commit_msg>Sorry Vieira. Fixed last commit<commit_after>/** * @file trajectory_controller.cpp * @author Matheus Vieira Portela * @date 03/08/2015 * * @attention Copyright (C) 2015 UnBall Robot Soccer Team * * @brief Control robots trajectory by applying potential fields. */ #include <unball/strategy/trajectory_controller.hpp> TrajectoryController::TrajectoryController() { player_[0] = new AssistentPlayer(); player_[1] = new AssistentPlayer(); player_[2] = new Goalkeeper(); direct_motion_ = true; } TrajectoryController::~TrajectoryController() { for (int i = 2; i >= 0; --i) delete player_[i]; } void TrajectoryController::run() { Vector resultant_force; for (int i=0;i<3;i++) { player_[i]->buildPotentialFields(i); resultant_force = player_[i]->calculateResultantForce(i); //ROS_ERROR("resultant_force: mag: %.2f ang: %.2f", resultant_force.getMagnitude(), // resultant_force.getDirection()*180/M_PI); player_[i]->clearPotentialFields(); controlRobot(i, resultant_force); } robot[2].setAngVel(5); robot[2].setLinVel(0); } void TrajectoryController::controlRobot(int robot_number, Vector force) { // Use histeresis to void quickly changing direction. float error_margin = 15*M_PI/180; if (direct_motion_) { if (fabs(math::reduceAngle(M_PI + force.getDirection() - robot[robot_number].getTh())) > M_PI/2 + error_margin) { direct_motion_ = false; } } else { if (fabs(math::reduceAngle(M_PI + force.getDirection() - robot[robot_number].getTh())) < M_PI/2 - error_margin) { direct_motion_ = true; } } //HACK: issue80 - We have to add M_PI because the force is being calculated backwards if (direct_motion_) { move(robot_number, force.getMagnitude()); turn(robot_number, force.getDirection()); } else { move(robot_number, -force.getMagnitude()); turn(robot_number, math::invertAngle(force.getDirection())); } } void TrajectoryController::move(int robot_number, float distance) { const float DIST_KP = 1; const float distance_tolerance = 0.05; // m float lin_vel = DIST_KP*distance; // P control // if (fabs(distance) > distance_tolerance) robot[robot_number].setLinVel(lin_vel); // else // robot[robot_number].setLinVel(0); } void TrajectoryController::turn(int robot_number, float angle) { const float ANG_KP = 0.008; const float ANG_KD = 0; //HACK: issue80 - Should be: angle - robot.getTh() float angle_error = math::reduceAngle(robot[robot_number].getTh() - angle); float angle_error_d = angle_error - angle_error_prev_; float ang_vel = ANG_KP*angle_error + ANG_KD*angle_error_d; // PD control angle_error_prev_ = angle_error; robot[robot_number].setAngVel(ang_vel); } void TrajectoryController::stopRobot(int robot_number) { robot[robot_number].setAngVel(0); robot[robot_number].setLinVel(0); } void TrajectoryController::updatePlayer(int robot_number, player_behaviour behaviour) { delete player_[robot_number]; if (behaviour == INITIAL_GOALKEEPER) player_[robot_number] = new InitialGoalkeeper(); if (behaviour == GOALKEEPER) player_[robot_number] = new Goalkeeper(); if (behaviour == REGULAR_PLAYER) player_[robot_number] = new RegularPlayer(); if (behaviour == KICKER_PLAYER) player_[robot_number] = new KickerPlayer(); if (behaviour == ASSISTENT_PLAYER) player_[robot_number] = new AssistentPlayer(); if (behaviour == GOALKEEPER_KICKER) player_[robot_number] = new GoalkeeperKicker(); } Player* TrajectoryController::getPlayer(int robot_number) { return player_[robot_number]; } <|endoftext|>
<commit_before> #include "RooStats/HistFactory/Measurement.h" #include "RooStats/HistFactory/MakeModelAndMeasurementsFast.h" #include "TFile.h" #include "TROOT.h" using namespace RooStats; using namespace HistFactory; /* A ROOT script demonstrating an example of writing a HistFactory model using c++ only. This example was written to match the example.xml analysis in $ROOTSYS/tutorials/histfactory/ Written by George Lewis */ void example() { std::string InputFile = "./example.root"; // in case the file is not found TFile * ifile = TFile::Open(InputFile.c_str()); if (!ifile) { std::cout << "Input file is not found - run prepareHistFactory script " << std::endl; gROOT->ProcessLine(".! prepareHistFactory ."); } // Create the measurement Measurement meas("meas", "meas"); meas.SetOutputFilePrefix( "./results/example_UsingC" ); meas.SetPOI( "SigXsecOverSM" ); meas.AddConstantParam("alpha_syst1"); meas.AddConstantParam("Lumi"); meas.SetLumi( 1.0 ); meas.SetLumiRelErr( 0.10 ); meas.SetExportOnly( false ); meas.SetBinHigh( 2 ); // Create a channel Channel chan( "channel1" ); chan.SetData( "data", InputFile ); chan.SetStatErrorConfig( 0.05, "Poisson" ); // Now, create some samples // Create the signal sample Sample signal( "signal", "signal", InputFile ); signal.AddOverallSys( "syst1", 0.95, 1.05 ); signal.AddNormFactor( "SigXsecOverSM", 1, 0, 3 ); chan.AddSample( signal ); // Background 1 Sample background1( "background1", "background1", InputFile ); background1.ActivateStatError( "background1_statUncert", InputFile ); background1.AddOverallSys( "syst2", 0.95, 1.05 ); chan.AddSample( background1 ); // Background 1 Sample background2( "background2", "background2", InputFile ); background2.ActivateStatError(); background2.AddOverallSys( "syst3", 0.95, 1.05 ); chan.AddSample( background2 ); // Done with this channel // Add it to the measurement: meas.AddChannel( chan ); // Collect the histograms from their files, // print some output, meas.CollectHistograms(); meas.PrintTree(); // One can print XML code to an // output directory: // meas.PrintXML( "xmlFromCCode", meas.GetOutputFilePrefix() ); // Now, do the measurement MakeModelAndMeasurementFast( meas ); } <commit_msg>Revert the change of example.C on the location of the date file.<commit_after> #include "RooStats/HistFactory/Measurement.h" #include "RooStats/HistFactory/MakeModelAndMeasurementsFast.h" #include "TFile.h" #include "TROOT.h" using namespace RooStats; using namespace HistFactory; /* A ROOT script demonstrating an example of writing a HistFactory model using c++ only. This example was written to match the example.xml analysis in $ROOTSYS/tutorials/histfactory/ Written by George Lewis */ void example() { std::string InputFile = ".data/example.root"; // in case the file is not found TFile * ifile = TFile::Open(InputFile.c_str()); if (!ifile) { std::cout << "Input file is not found - run prepareHistFactory script " << std::endl; gROOT->ProcessLine(".! prepareHistFactory ."); } // Create the measurement Measurement meas("meas", "meas"); meas.SetOutputFilePrefix( "./results/example_UsingC" ); meas.SetPOI( "SigXsecOverSM" ); meas.AddConstantParam("alpha_syst1"); meas.AddConstantParam("Lumi"); meas.SetLumi( 1.0 ); meas.SetLumiRelErr( 0.10 ); meas.SetExportOnly( false ); meas.SetBinHigh( 2 ); // Create a channel Channel chan( "channel1" ); chan.SetData( "data", InputFile ); chan.SetStatErrorConfig( 0.05, "Poisson" ); // Now, create some samples // Create the signal sample Sample signal( "signal", "signal", InputFile ); signal.AddOverallSys( "syst1", 0.95, 1.05 ); signal.AddNormFactor( "SigXsecOverSM", 1, 0, 3 ); chan.AddSample( signal ); // Background 1 Sample background1( "background1", "background1", InputFile ); background1.ActivateStatError( "background1_statUncert", InputFile ); background1.AddOverallSys( "syst2", 0.95, 1.05 ); chan.AddSample( background1 ); // Background 1 Sample background2( "background2", "background2", InputFile ); background2.ActivateStatError(); background2.AddOverallSys( "syst3", 0.95, 1.05 ); chan.AddSample( background2 ); // Done with this channel // Add it to the measurement: meas.AddChannel( chan ); // Collect the histograms from their files, // print some output, meas.CollectHistograms(); meas.PrintTree(); // One can print XML code to an // output directory: // meas.PrintXML( "xmlFromCCode", meas.GetOutputFilePrefix() ); // Now, do the measurement MakeModelAndMeasurementFast( meas ); } <|endoftext|>
<commit_before> <commit_msg>open file for a single output<commit_after>#include<iostream> #include<fstream> #include<ctime> #include<cstring> using namespace std; const string OUT_DIR = "outputs"; string get_file_name(){ return "CODES_"+to_string(time(NULL))+".txt"; } int main(){ string filename=get_file_name(); cout<<"output at file : "<<filename<<endl; string outputPath=".\\" + OUT_DIR + "\\" + filename; ofstream outFile; outFile.open(outputPath); if(outFile != NULL){ //process files of codes outFile.close(); cout<<"Writing Completed !"; } else{ cout<<"Error opening file : "<<outputPath<<endl; cout<<"Progream failed!"; } return 0; } <|endoftext|>
<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "InteriorExplorerState.h" #include "IAppCameraController.h" #include "InteriorExplorerSetupState.h" #include "InteriorExplorerStreamState.h" #include "InteriorExplorerViewingState.h" #include "InteriorExplorerExitingState.h" #include "InteriorSelectionModel.h" #include "IAppModeModel.h" #include "InteriorsCameraController.h" #include "GpsGlobeCameraController.h" #include "GlobeCameraController.h" #include "CameraHelpers.h" #include "EcefTangentBasis.h" #include "NativeUIFactories.h" #include "IAlertBoxFactory.h" #include "LatLongAltitude.h" #include "MyPinCreationModel.h" #include "MyPinCreationStage.h" #include "InteriorExplorerUserInteractionModel.h" #include "ITourService.h" namespace ExampleApp { namespace AppModes { namespace States { namespace SdkModel { InteriorExplorerState::InteriorExplorerState(AppCamera::SdkModel::IAppCameraController& cameraController, Eegeo::Resources::Interiors::InteriorSelectionModel& interiorSelectionModel, Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel, int interiorCameraHandle, Tours::SdkModel::ITourService& tourService, Eegeo::Streaming::CameraFrustumStreamingVolume& cameraFrustumStreamingVolume, InteriorsExplorer::SdkModel::InteriorVisibilityUpdater& interiorVisibilityUpdater, InteriorsExplorer::SdkModel::InteriorsExplorerModel& interiorsExplorerModel, InteriorsExplorer::SdkModel::InteriorExplorerUserInteractionModel& interiorExplorerUserInteractionModel, AppModes::SdkModel::IAppModeModel& appModeModel, Eegeo::Camera::GlobeCamera::GpsGlobeCameraController& worldCameraController, Eegeo::Resources::Interiors::InteriorsCameraController& interiorsCameraController, Eegeo::UI::NativeUIFactories& nativeUIFactories, MyPinCreation::SdkModel::IMyPinCreationModel& myPinCreationModel) : m_tourService(tourService) , m_tourStartedCallback(this, &InteriorExplorerState::OnTourStarted) , m_interiorExplorerUserInteractionModel(interiorExplorerUserInteractionModel) , m_appModeModel(appModeModel) , m_worldCameraController(worldCameraController) , m_interiorsCameraController(interiorsCameraController) , m_nativeUIFactories(nativeUIFactories) , m_failAlertHandler(this, &InteriorExplorerState::OnFailAlertBoxDismissed) , m_myPinCreationModel(myPinCreationModel) , m_lastEntryAttemptSuccessful(false) { m_subStates.push_back(Eegeo_NEW(InteriorsExplorer::SdkModel::States::InteriorExplorerSetupState)(*this, cameraController, interiorCameraHandle)); m_subStates.push_back(Eegeo_NEW(InteriorsExplorer::SdkModel::States::InteriorExplorerStreamState)(*this, interiorInteractionModel, cameraFrustumStreamingVolume, interiorVisibilityUpdater)); m_subStates.push_back(Eegeo_NEW(InteriorsExplorer::SdkModel::States::InteriorExplorerViewingState)(*this, interiorsExplorerModel, interiorExplorerUserInteractionModel, cameraFrustumStreamingVolume)); m_subStates.push_back(Eegeo_NEW(InteriorsExplorer::SdkModel::States::InteriorExplorerExitingState)(*this, interiorSelectionModel, cameraFrustumStreamingVolume, interiorVisibilityUpdater, interiorsExplorerModel )); m_pSubStateMachine = Eegeo_NEW(Helpers::StateMachine)(m_subStates); } InteriorExplorerState::~InteriorExplorerState() { if(m_pSubStateMachine->GetCurrentStateIndex() >= 0) { m_pSubStateMachine->StopStateMachine(); } Eegeo_DELETE m_pSubStateMachine; m_pSubStateMachine = NULL; for(int i = 0; i < m_subStates.size(); ++i) { Eegeo_DELETE m_subStates[i]; } m_subStates.clear(); } void InteriorExplorerState::Enter(int previousState) { m_interiorExplorerUserInteractionModel.SetEnabled(false); m_tourService.RegisterTourStartedCallback(m_tourStartedCallback); m_myPinCreationModel.SetCreationStage(MyPinCreation::Inactive); m_pSubStateMachine->StartStateMachine(0); } void InteriorExplorerState::Update(float dt) { if(m_pSubStateMachine->GetCurrentStateIndex() >= 0) { m_pSubStateMachine->Update(dt); } } void InteriorExplorerState::Exit(int nextState) { Eegeo::Space::LatLongAltitude latLong = Eegeo::Space::LatLongAltitude::FromECEF(m_interiorsCameraController.GetCameraState().InterestPointEcef()); const float interestDistance = 500.0f; m_worldCameraController.SetView(latLong.GetLatitudeInDegrees(), latLong.GetLongitudeInDegrees(), m_interiorsCameraController.GetHeadingDegrees(), interestDistance); m_worldCameraController.GetGlobeCameraController().ApplyTilt(0.0f); if(m_pSubStateMachine->GetCurrentStateIndex() >= 0) { m_pSubStateMachine->StopStateMachine(); } m_tourService.UnregisterTourStartedCallback(m_tourStartedCallback); m_interiorExplorerUserInteractionModel.SetEnabled(true); } void InteriorExplorerState::SetSubState(InteriorExplorerSubStates::Values stateIndex) { m_pSubStateMachine->ChangeToState(stateIndex); } void InteriorExplorerState::ReturnToWorldMode() { m_appModeModel.SetAppMode(AppModes::SdkModel::WorldMode); } void InteriorExplorerState::ShowFailMessage() { m_nativeUIFactories.AlertBoxFactory().CreateSingleOptionAlertBox("Error", "We couldn't find the data for this interior", m_failAlertHandler); } void InteriorExplorerState::OnFailAlertBoxDismissed() { } void InteriorExplorerState::OnTourStarted() { m_appModeModel.SetAppMode(ExampleApp::AppModes::SdkModel::TourMode); } void InteriorExplorerState::SetLastEntryAttemptSuccessful(bool successful) { m_lastEntryAttemptSuccessful = successful; } bool InteriorExplorerState::GetLastEntryAttemptSuccessful() const { return m_lastEntryAttemptSuccessful; } } } } }<commit_msg>Fix for MPLY-6772. Interior camera no longer retains tilt when exiting interior. Buddy: Vimarsh<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "InteriorExplorerState.h" #include "IAppCameraController.h" #include "InteriorExplorerSetupState.h" #include "InteriorExplorerStreamState.h" #include "InteriorExplorerViewingState.h" #include "InteriorExplorerExitingState.h" #include "InteriorSelectionModel.h" #include "IAppModeModel.h" #include "InteriorsCameraController.h" #include "GpsGlobeCameraController.h" #include "GlobeCameraController.h" #include "CameraHelpers.h" #include "EcefTangentBasis.h" #include "NativeUIFactories.h" #include "IAlertBoxFactory.h" #include "LatLongAltitude.h" #include "MyPinCreationModel.h" #include "MyPinCreationStage.h" #include "InteriorExplorerUserInteractionModel.h" #include "ITourService.h" namespace ExampleApp { namespace AppModes { namespace States { namespace SdkModel { InteriorExplorerState::InteriorExplorerState(AppCamera::SdkModel::IAppCameraController& cameraController, Eegeo::Resources::Interiors::InteriorSelectionModel& interiorSelectionModel, Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel, int interiorCameraHandle, Tours::SdkModel::ITourService& tourService, Eegeo::Streaming::CameraFrustumStreamingVolume& cameraFrustumStreamingVolume, InteriorsExplorer::SdkModel::InteriorVisibilityUpdater& interiorVisibilityUpdater, InteriorsExplorer::SdkModel::InteriorsExplorerModel& interiorsExplorerModel, InteriorsExplorer::SdkModel::InteriorExplorerUserInteractionModel& interiorExplorerUserInteractionModel, AppModes::SdkModel::IAppModeModel& appModeModel, Eegeo::Camera::GlobeCamera::GpsGlobeCameraController& worldCameraController, Eegeo::Resources::Interiors::InteriorsCameraController& interiorsCameraController, Eegeo::UI::NativeUIFactories& nativeUIFactories, MyPinCreation::SdkModel::IMyPinCreationModel& myPinCreationModel) : m_tourService(tourService) , m_tourStartedCallback(this, &InteriorExplorerState::OnTourStarted) , m_interiorExplorerUserInteractionModel(interiorExplorerUserInteractionModel) , m_appModeModel(appModeModel) , m_worldCameraController(worldCameraController) , m_interiorsCameraController(interiorsCameraController) , m_nativeUIFactories(nativeUIFactories) , m_failAlertHandler(this, &InteriorExplorerState::OnFailAlertBoxDismissed) , m_myPinCreationModel(myPinCreationModel) , m_lastEntryAttemptSuccessful(false) { m_subStates.push_back(Eegeo_NEW(InteriorsExplorer::SdkModel::States::InteriorExplorerSetupState)(*this, cameraController, interiorCameraHandle)); m_subStates.push_back(Eegeo_NEW(InteriorsExplorer::SdkModel::States::InteriorExplorerStreamState)(*this, interiorInteractionModel, cameraFrustumStreamingVolume, interiorVisibilityUpdater)); m_subStates.push_back(Eegeo_NEW(InteriorsExplorer::SdkModel::States::InteriorExplorerViewingState)(*this, interiorsExplorerModel, interiorExplorerUserInteractionModel, cameraFrustumStreamingVolume)); m_subStates.push_back(Eegeo_NEW(InteriorsExplorer::SdkModel::States::InteriorExplorerExitingState)(*this, interiorSelectionModel, cameraFrustumStreamingVolume, interiorVisibilityUpdater, interiorsExplorerModel )); m_pSubStateMachine = Eegeo_NEW(Helpers::StateMachine)(m_subStates); } InteriorExplorerState::~InteriorExplorerState() { if(m_pSubStateMachine->GetCurrentStateIndex() >= 0) { m_pSubStateMachine->StopStateMachine(); } Eegeo_DELETE m_pSubStateMachine; m_pSubStateMachine = NULL; for(int i = 0; i < m_subStates.size(); ++i) { Eegeo_DELETE m_subStates[i]; } m_subStates.clear(); } void InteriorExplorerState::Enter(int previousState) { m_interiorExplorerUserInteractionModel.SetEnabled(false); m_tourService.RegisterTourStartedCallback(m_tourStartedCallback); m_myPinCreationModel.SetCreationStage(MyPinCreation::Inactive); m_interiorsCameraController.SetTilt(0.0f); m_pSubStateMachine->StartStateMachine(0); } void InteriorExplorerState::Update(float dt) { if(m_pSubStateMachine->GetCurrentStateIndex() >= 0) { m_pSubStateMachine->Update(dt); } } void InteriorExplorerState::Exit(int nextState) { Eegeo::Space::LatLongAltitude latLong = Eegeo::Space::LatLongAltitude::FromECEF(m_interiorsCameraController.GetCameraState().InterestPointEcef()); const float interestDistance = 500.0f; m_worldCameraController.SetView(latLong.GetLatitudeInDegrees(), latLong.GetLongitudeInDegrees(), m_interiorsCameraController.GetHeadingDegrees(), interestDistance); m_worldCameraController.GetGlobeCameraController().ApplyTilt(0.0f); if(m_pSubStateMachine->GetCurrentStateIndex() >= 0) { m_pSubStateMachine->StopStateMachine(); } m_tourService.UnregisterTourStartedCallback(m_tourStartedCallback); m_interiorExplorerUserInteractionModel.SetEnabled(true); } void InteriorExplorerState::SetSubState(InteriorExplorerSubStates::Values stateIndex) { m_pSubStateMachine->ChangeToState(stateIndex); } void InteriorExplorerState::ReturnToWorldMode() { m_appModeModel.SetAppMode(AppModes::SdkModel::WorldMode); } void InteriorExplorerState::ShowFailMessage() { m_nativeUIFactories.AlertBoxFactory().CreateSingleOptionAlertBox("Error", "We couldn't find the data for this interior", m_failAlertHandler); } void InteriorExplorerState::OnFailAlertBoxDismissed() { } void InteriorExplorerState::OnTourStarted() { m_appModeModel.SetAppMode(ExampleApp::AppModes::SdkModel::TourMode); } void InteriorExplorerState::SetLastEntryAttemptSuccessful(bool successful) { m_lastEntryAttemptSuccessful = successful; } bool InteriorExplorerState::GetLastEntryAttemptSuccessful() const { return m_lastEntryAttemptSuccessful; } } } } }<|endoftext|>
<commit_before>#include "vschdfsrecord.h" #include "hdddevice.hpp" #include "debug.hpp" #include "vschddone.h" #include "factory.hpp" extern Factory *gFactory; VSCHdfsRecord::VSCHdfsRecord(QWidget *parent) : QWidget(parent) { ui.setupUi(this); gFactory->GetHdfsRecordConf(m_Param); /* Setup the default value */ setupDefaultValue(); } void VSCHdfsRecord::setupDefaultValue() { ui.lineEditNameNode->setText(m_Param.data.conf.NameNode); ui.lineEditPort->setText(m_Param.data.conf.Port); ui.lineEditUser->setText(m_Param.data.conf.User); } void VSCHdfsRecord::applyConfig() { /* Update m_Param from UI */ updateParamValue(ui.lineEditNameNode, m_Param.data.conf.NameNode); updateParamValue(ui.lineEditPort, m_Param.data.conf.Port); updateParamValue(ui.lineEditUser, m_Param.data.conf.User); VDC_DEBUG( "%s Line %d\n",__FUNCTION__, __LINE__); gFactory->SetHdfsRecordConf(m_Param); } <commit_msg>add hdfs<commit_after>#include "vschdfsrecord.h" #include "hdddevice.hpp" #include "debug.hpp" #include "vschddone.h" #include "factory.hpp" extern Factory *gFactory; VSCHdfsRecord::VSCHdfsRecord(QWidget *parent) : QWidget(parent) { ui.setupUi(this); gFactory->GetHdfsRecordConf(m_Param); /* Setup the default value */ setupDefaultValue(); connect( this->ui.pushButtonApply, SIGNAL( clicked() ), this, SLOT(applyConfig())); } void VSCHdfsRecord::setupDefaultValue() { ui.lineEditNameNode->setText(m_Param.data.conf.NameNode); ui.lineEditPort->setText(m_Param.data.conf.Port); ui.lineEditUser->setText(m_Param.data.conf.User); } void VSCHdfsRecord::applyConfig() { /* Update m_Param from UI */ updateParamValue(ui.lineEditNameNode, m_Param.data.conf.NameNode); updateParamValue(ui.lineEditPort, m_Param.data.conf.Port); updateParamValue(ui.lineEditUser, m_Param.data.conf.User); VDC_DEBUG( "%s Line %d\n",__FUNCTION__, __LINE__); gFactory->SetHdfsRecordConf(m_Param); } <|endoftext|>
<commit_before>#include <babylon/meshes/builders/capsule_builder.h> #include <babylon/meshes/builders/mesh_builder_options.h> #include <babylon/meshes/mesh.h> #include <babylon/meshes/vertex_data.h> namespace BABYLON { MeshPtr CapsuleBuilder::CreateCapsule(const std::string& name, ICreateCapsuleOptions& options, Scene* scene) { const auto capsule = Mesh::New(name, scene); const auto vertexData = VertexData::CreateCapsule(options); vertexData->applyToMesh(*capsule); return capsule; } } // end of namespace BABYLON <commit_msg>Setting default capsule create options<commit_after>#include <babylon/meshes/builders/capsule_builder.h> #include <babylon/meshes/builders/mesh_builder_options.h> #include <babylon/meshes/mesh.h> #include <babylon/meshes/vertex_data.h> namespace BABYLON { MeshPtr CapsuleBuilder::CreateCapsule(const std::string& name, ICreateCapsuleOptions& options, Scene* scene) { // Set default values { options.orientation = options.orientation.value_or(Vector3::Up()); options.subdivisions = options.subdivisions.value_or(2u); options.tessellation = options.tessellation.value_or(16u); options.height = options.height.value_or(1.f); options.radius = options.radius.value_or(0.25f); options.capSubdivisions = options.capSubdivisions.value_or(6u); options.updatable = options.updatable.value_or(false); } const auto capsule = Mesh::New(name, scene); const auto vertexData = VertexData::CreateCapsule(options); vertexData->applyToMesh(*capsule, options.updatable); return capsule; } } // end of namespace BABYLON <|endoftext|>
<commit_before>#ifndef VIENNAGRID_IO_OPENDX_WRITER_GUARD #define VIENNAGRID_IO_OPENDX_WRITER_GUARD /* ======================================================================= Copyright (c) 2011-2012, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaGrid - The Vienna Grid Library ----------------- Authors: Karl Rupp rupp@iue.tuwien.ac.at Josef Weinbub weinbub@iue.tuwien.ac.at (A list of additional contributors can be found in the PDF manual) License: MIT (X11), see file LICENSE in the base directory ======================================================================= */ #include <fstream> #include <iostream> #include "viennagrid/forwards.h" #include "viennagrid/io/helper.hpp" #include "viennagrid/io/data_accessor.hpp" /** @file opendx_writer.hpp @brief Provides a writer for OpenDX files */ namespace viennagrid { namespace io { /////////////////// OpenDX export //////////////////////////// /** @brief Fix for a OpenDX bug: if floating-values occur, no integers (i.e. only zeros after decimal point) are allowed * * As a remedy, we add a value of 1e-5. Better to have a small error in the visualization instead of a crashed OpenDX... * * @tparam FloatingPointType Dummy template argument to disable external linkage. Almost always float or double. */ template <typename FloatingPointType> FloatingPointType DXfixer(FloatingPointType value) { if (value * 10000 == static_cast<long>(value * 10000)) return value + 0.00001; return value; } /** @brief A helper class returning dimension-dependent attribute strings. */ template <int DIM> struct DXHelper {}; template <> struct DXHelper<1> { static std::string getAttributes() { return "attribute \"element type\" string \"line\" "; } }; template <> struct DXHelper<2> { static std::string getAttributes() { return "attribute \"element type\" string \"triangles\" "; } }; template <> struct DXHelper<3> { static std::string getAttributes() { return "attribute \"element type\" string \"tetrahedra\" "; } }; /** @brief The OpenDX writer object. Does not support segments - always the full domain is written. * * @tparam DomainType The ViennaGrid domain. */ template <typename DomainType> class opendx_writer { typedef typename DomainType::config_type DomainConfiguration; typedef typename DomainConfiguration::numeric_type CoordType; typedef typename DomainConfiguration::coordinate_system_tag CoordinateSystemTag; typedef typename DomainConfiguration::cell_tag CellTag; typedef typename result_of::point<DomainConfiguration>::type PointType; typedef typename result_of::ncell<DomainConfiguration, 0>::type VertexType; typedef typename result_of::ncell<DomainConfiguration, CellTag::dim>::type CellType; typedef typename viennagrid::result_of::const_ncell_range<DomainType, 0>::type VertexRange; typedef typename viennagrid::result_of::iterator<VertexRange>::type VertexIterator; typedef typename viennagrid::result_of::const_ncell_range<DomainType, CellTag::dim>::type CellRange; typedef typename viennagrid::result_of::iterator<CellRange>::type CellIterator; typedef typename viennagrid::result_of::const_ncell_range<CellType, 0>::type VertexOnCellRange; typedef typename viennagrid::result_of::iterator<VertexOnCellRange>::type VertexOnCellIterator; public: /** @brief Triggers the writing of the domain to a file * * @param domain A ViennaGrid domain * @param filename Name of the file */ int operator()(DomainType const & domain, std::string const & filename) { typedef DXHelper<CoordinateSystemTag::dim> DXHelper; std::ofstream writer(filename.c_str()); if (!writer.is_open()) { throw cannot_open_file_exception(filename); return EXIT_FAILURE; } std::size_t pointnum = viennagrid::ncells<0>(domain).size(); writer << "object \"points\" class array type float rank 1 shape " << CoordinateSystemTag::dim << " items "; writer << pointnum << " data follows" << std::endl; //Nodes: VertexRange vertices = viennagrid::ncells<0>(domain); for (VertexIterator vit = vertices.begin(); vit != vertices.end(); ++vit) { PointWriter<CoordinateSystemTag::dim>::write(writer, vit->point()); writer << std::endl; } writer << std::endl; //Cells: std::size_t cellnum = viennagrid::ncells<CellTag::dim>(domain).size(); writer << "object \"grid_Line_One\" class array type int rank 1 shape " << (CoordinateSystemTag::dim + 1) << " items " << cellnum << " data follows" << std::endl; CellRange cells = viennagrid::ncells<CellTag::dim>(domain); for (CellIterator cit = cells.begin(); cit != cells.end(); ++cit) { VertexOnCellRange vertices_for_cell = viennagrid::ncells<0>(*cit); for (VertexOnCellIterator vocit = vertices_for_cell.begin(); vocit != vertices_for_cell.end(); ++vocit) { VertexType const & vertex = *vocit; writer << vertex.id() << " "; } writer << std::endl; } writer << DXHelper::getAttributes() << std::endl; writer << "attribute \"ref\" string \"positions\" " << std::endl; writer << std::endl; //set output-format: writer.flags(std::ios::fixed); writer.precision(5); //write quantity: if (vertex_data_scalar.size() > 0) { writer << "object \"VisData\" class array items " << pointnum << " data follows" << std::endl; //some quantity here for (VertexIterator vit = vertices.begin(); vit != vertices.end(); ++vit) { std::string value = vertex_data_scalar[0](*vit); writer << DXfixer(atof(value.c_str())); writer << std::endl; } writer << "attribute \"dep\" string \"positions\"" << std::endl; } else if (cell_data_scalar.size() > 0) { writer << "object \"VisData\" class array items " << cellnum << " data follows" << std::endl; //some quantity here for (CellIterator cit = cells.begin(); cit != cells.end(); ++cit) { std::string value = cell_data_scalar[0](*cit); writer << DXfixer(atof(value.c_str())); writer << std::endl; } writer << "attribute \"dep\" string \"connections\"" << std::endl; } writer << std::endl; writer << "object \"AttPotential\" class field " << std::endl; writer << "component \"data\" \"VisData\" " << std::endl; writer << "component \"positions\" \"points\"" << std::endl; writer << "component \"connections\" \"grid_Line_One\"" << std::endl; return EXIT_SUCCESS; } // operator() /** @brief Adds scalar data on vertices for writing to the OpenDX file. Only one quantity at a time is supported! */ template <typename T> void add_scalar_data_on_vertices(T const & accessor, std::string name) { data_accessor_wrapper<VertexType> wrapper(accessor.clone()); if (vertex_data_scalar.size() > 0) std::cout << "* ViennaGrid: Warning: OpenDX vertex data " << name << " will be ignored, because other data is already available!" << std::endl; vertex_data_scalar.push_back(wrapper); } /** @brief Adds scalar data on cells for writing to the OpenDX file. Note that vertex data has precedence. Only one quantity at a time is supported! */ template <typename T> void add_scalar_data_on_cells(T const & accessor, std::string name) { data_accessor_wrapper<CellType> wrapper(accessor.clone()); if (cell_data_scalar.size() > 0) std::cout << "* ViennaGrid: Warning: OpenDX cell data " << name << " will be ignored, because other cell data is already available!" << std::endl; if (vertex_data_scalar.size() > 0) std::cout << "* ViennaGrid: Warning: OpenDX cell data " << name << " will be ignored, because other vertex data is already available!" << std::endl; cell_data_scalar.push_back(wrapper); } private: std::vector< data_accessor_wrapper<VertexType> > vertex_data_scalar; std::vector< data_accessor_wrapper<CellType> > cell_data_scalar; }; // opendx_writer /** @brief Registers scalar-valued data on vertices at the OpenDX writer. At most one data set is allowed. * * @tparam KeyType Type of the key used with ViennaData * @tparam DataType Type of the data as used with ViennaData * @tparam DomainType The ViennaGrid domain type * @param writer The OpenDX writer object for which the data should be registered * @param key The key object for ViennaData * @param quantity_name Ignored. Only used for a homogeneous interface with VTK reader/writer. */ template <typename KeyType, typename DataType, typename DomainType> opendx_writer<DomainType> & add_scalar_data_on_vertices(opendx_writer<DomainType> & writer, KeyType const & key, std::string quantity_name) { typedef typename DomainType::config_type DomainConfiguration; typedef typename result_of::ncell<DomainConfiguration, 0>::type VertexType; data_accessor_wrapper<VertexType> wrapper(new global_scalar_data_accessor<VertexType, KeyType, DataType>(key)); writer.add_scalar_data_on_vertices(wrapper, quantity_name); return writer; } /** @brief Registers scalar-valued data on cells at the OpenDX writer. Note that vertex data has precedence. At most one data set is allowed. * * @tparam KeyType Type of the key used with ViennaData * @tparam DataType Type of the data as used with ViennaData * @tparam DomainType The ViennaGrid domain type * @param writer The OpenDX writer object for which the data should be registered * @param key The key object for ViennaData * @param quantity_name Ignored. Only used for a homogeneous interface with VTK reader/writer. */ template <typename KeyType, typename DataType, typename DomainType> opendx_writer<DomainType> & add_scalar_data_on_cells(opendx_writer<DomainType> & writer, KeyType const & key, std::string quantity_name) { typedef typename DomainType::config_type DomainConfiguration; typedef typename DomainConfiguration::cell_tag CellTag; typedef typename result_of::ncell<DomainConfiguration, CellTag::dim>::type CellType; data_accessor_wrapper<CellType> wrapper(new global_scalar_data_accessor<CellType, KeyType, DataType>(key)); writer.add_scalar_data_on_cells(wrapper, quantity_name); return writer; } } //namespace io } //namespace viennagrid #endif <commit_msg>adapted to new domain classes<commit_after>#ifndef VIENNAGRID_IO_OPENDX_WRITER_GUARD #define VIENNAGRID_IO_OPENDX_WRITER_GUARD /* ======================================================================= Copyright (c) 2011-2012, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaGrid - The Vienna Grid Library ----------------- Authors: Karl Rupp rupp@iue.tuwien.ac.at Josef Weinbub weinbub@iue.tuwien.ac.at (A list of additional contributors can be found in the PDF manual) License: MIT (X11), see file LICENSE in the base directory ======================================================================= */ #include <fstream> #include <iostream> #include "viennagrid/forwards.hpp" #include "viennagrid/io/helper.hpp" #include "viennagrid/io/data_accessor.hpp" /** @file opendx_writer.hpp @brief Provides a writer for OpenDX files */ namespace viennagrid { namespace io { /////////////////// OpenDX export //////////////////////////// /** @brief Fix for a OpenDX bug: if floating-values occur, no integers (i.e. only zeros after decimal point) are allowed * * As a remedy, we add a value of 1e-5. Better to have a small error in the visualization instead of a crashed OpenDX... * * @tparam FloatingPointType Dummy template argument to disable external linkage. Almost always float or double. */ template <typename FloatingPointType> FloatingPointType DXfixer(FloatingPointType value) { if (value * 10000 == static_cast<long>(value * 10000)) return value + 0.00001; return value; } /** @brief A helper class returning dimension-dependent attribute strings. */ template <int DIM> struct DXHelper {}; template <> struct DXHelper<1> { static std::string getAttributes() { return "attribute \"element type\" string \"line\" "; } }; template <> struct DXHelper<2> { static std::string getAttributes() { return "attribute \"element type\" string \"triangles\" "; } }; template <> struct DXHelper<3> { static std::string getAttributes() { return "attribute \"element type\" string \"tetrahedra\" "; } }; /** @brief The OpenDX writer object. Does not support segments - always the full domain is written. * * @tparam DomainType The ViennaGrid domain. */ template <typename CellTypeOrTag, typename DomainType> class opendx_writer { //typedef typename DomainType::config_type DomainConfiguration; typedef typename viennagrid::result_of::point_type<DomainType>::type PointType; typedef typename viennagrid::traits::value_type<PointType>::type CoordType; enum { geometric_dim = viennagrid::traits::static_size<PointType>::value }; //typedef typename DomainConfiguration::numeric_type CoordType; //typedef typename DomainConfiguration::coordinate_system_tag CoordinateSystemTag; //typedef typename DomainConfiguration::cell_tag CellTag; typedef typename viennagrid::result_of::element_tag<CellTypeOrTag>::type CellTag; //typedef typename result_of::point<DomainConfiguration>::type PointType; //typedef typename result_of::point_type<DomainType>::type PointType; typedef typename result_of::element<DomainType, viennagrid::vertex_tag>::type VertexType; typedef typename result_of::element<DomainType, CellTag>::type CellType; typedef typename viennagrid::result_of::const_element_range<DomainType, viennagrid::vertex_tag>::type VertexRange; typedef typename viennagrid::result_of::iterator<VertexRange>::type VertexIterator; typedef typename viennagrid::result_of::const_element_range<DomainType, CellTag>::type CellRange; typedef typename viennagrid::result_of::iterator<CellRange>::type CellIterator; typedef typename viennagrid::result_of::const_element_range<CellType, viennagrid::vertex_tag>::type VertexOnCellRange; typedef typename viennagrid::result_of::iterator<VertexOnCellRange>::type VertexOnCellIterator; public: /** @brief Triggers the writing of the domain to a file * * @param domain A ViennaGrid domain * @param filename Name of the file */ int operator()(DomainType const & domain, std::string const & filename) { typedef DXHelper<geometric_dim> DXHelper; std::ofstream writer(filename.c_str()); if (!writer.is_open()) { throw cannot_open_file_exception(filename); return EXIT_FAILURE; } std::size_t pointnum = viennagrid::ncells<0>(domain).size(); writer << "object \"points\" class array type float rank 1 shape " << geometric_dim << " items "; writer << pointnum << " data follows" << std::endl; //Nodes: VertexRange vertices = viennagrid::ncells<0>(domain); for (VertexIterator vit = vertices.begin(); vit != vertices.end(); ++vit) { PointWriter<geometric_dim>::write(writer, viennagrid::point( domain, *vit ) ); writer << std::endl; } writer << std::endl; //Cells: std::size_t cellnum = viennagrid::ncells<CellTag::dim>(domain).size(); writer << "object \"grid_Line_One\" class array type int rank 1 shape " << (geometric_dim + 1) << " items " << cellnum << " data follows" << std::endl; CellRange cells = viennagrid::ncells<CellTag::dim>(domain); for (CellIterator cit = cells.begin(); cit != cells.end(); ++cit) { VertexOnCellRange vertices_for_cell = viennagrid::ncells<0>(*cit); for (VertexOnCellIterator vocit = vertices_for_cell.begin(); vocit != vertices_for_cell.end(); ++vocit) { VertexType const & vertex = *vocit; writer << vertex.id() << " "; } writer << std::endl; } writer << DXHelper::getAttributes() << std::endl; writer << "attribute \"ref\" string \"positions\" " << std::endl; writer << std::endl; //set output-format: writer.flags(std::ios::fixed); writer.precision(5); //write quantity: if (vertex_data_scalar.size() > 0) { writer << "object \"VisData\" class array items " << pointnum << " data follows" << std::endl; //some quantity here for (VertexIterator vit = vertices.begin(); vit != vertices.end(); ++vit) { std::string value = vertex_data_scalar[0](*vit); writer << DXfixer(atof(value.c_str())); writer << std::endl; } writer << "attribute \"dep\" string \"positions\"" << std::endl; } else if (cell_data_scalar.size() > 0) { writer << "object \"VisData\" class array items " << cellnum << " data follows" << std::endl; //some quantity here for (CellIterator cit = cells.begin(); cit != cells.end(); ++cit) { std::string value = cell_data_scalar[0](*cit); writer << DXfixer(atof(value.c_str())); writer << std::endl; } writer << "attribute \"dep\" string \"connections\"" << std::endl; } writer << std::endl; writer << "object \"AttPotential\" class field " << std::endl; writer << "component \"data\" \"VisData\" " << std::endl; writer << "component \"positions\" \"points\"" << std::endl; writer << "component \"connections\" \"grid_Line_One\"" << std::endl; return EXIT_SUCCESS; } // operator() /** @brief Adds scalar data on vertices for writing to the OpenDX file. Only one quantity at a time is supported! */ template <typename T> void add_scalar_data_on_vertices(T const & accessor, std::string name) { data_accessor_wrapper<VertexType> wrapper(accessor.clone()); if (vertex_data_scalar.size() > 0) std::cout << "* ViennaGrid: Warning: OpenDX vertex data " << name << " will be ignored, because other data is already available!" << std::endl; vertex_data_scalar.push_back(wrapper); } /** @brief Adds scalar data on cells for writing to the OpenDX file. Note that vertex data has precedence. Only one quantity at a time is supported! */ template <typename T> void add_scalar_data_on_cells(T const & accessor, std::string name) { data_accessor_wrapper<CellType> wrapper(accessor.clone()); if (cell_data_scalar.size() > 0) std::cout << "* ViennaGrid: Warning: OpenDX cell data " << name << " will be ignored, because other cell data is already available!" << std::endl; if (vertex_data_scalar.size() > 0) std::cout << "* ViennaGrid: Warning: OpenDX cell data " << name << " will be ignored, because other vertex data is already available!" << std::endl; cell_data_scalar.push_back(wrapper); } private: std::vector< data_accessor_wrapper<VertexType> > vertex_data_scalar; std::vector< data_accessor_wrapper<CellType> > cell_data_scalar; }; // opendx_writer /** @brief Registers scalar-valued data on vertices at the OpenDX writer. At most one data set is allowed. * * @tparam KeyType Type of the key used with ViennaData * @tparam DataType Type of the data as used with ViennaData * @tparam DomainType The ViennaGrid domain type * @param writer The OpenDX writer object for which the data should be registered * @param key The key object for ViennaData * @param quantity_name Ignored. Only used for a homogeneous interface with VTK reader/writer. */ template <typename KeyType, typename DataType, typename CellTypeOrTag, typename DomainType> opendx_writer<CellTypeOrTag, DomainType> & add_scalar_data_on_vertices(opendx_writer<CellTypeOrTag, DomainType> & writer, KeyType const & key, std::string quantity_name) { //typedef typename DomainType::config_type DomainConfiguration; typedef typename result_of::element<DomainType, viennagrid::vertex_tag>::type VertexType; data_accessor_wrapper<VertexType> wrapper(new global_scalar_data_accessor<VertexType, KeyType, DataType>(key)); writer.add_scalar_data_on_vertices(wrapper, quantity_name); return writer; } /** @brief Registers scalar-valued data on cells at the OpenDX writer. Note that vertex data has precedence. At most one data set is allowed. * * @tparam KeyType Type of the key used with ViennaData * @tparam DataType Type of the data as used with ViennaData * @tparam DomainType The ViennaGrid domain type * @param writer The OpenDX writer object for which the data should be registered * @param key The key object for ViennaData * @param quantity_name Ignored. Only used for a homogeneous interface with VTK reader/writer. */ template <typename KeyType, typename DataType, typename CellTypeOrTag, typename DomainType> opendx_writer<CellTypeOrTag, DomainType> & add_scalar_data_on_cells(opendx_writer<CellTypeOrTag, DomainType> & writer, KeyType const & key, std::string quantity_name) { typedef typename DomainType::config_type DomainConfiguration; typedef typename result_of::element_tag<CellTypeOrTag>::type CellTag; typedef typename result_of::element<DomainConfiguration, CellTag>::type CellType; data_accessor_wrapper<CellType> wrapper(new global_scalar_data_accessor<CellType, KeyType, DataType>(key)); writer.add_scalar_data_on_cells(wrapper, quantity_name); return writer; } } //namespace io } //namespace viennagrid #endif <|endoftext|>
<commit_before>#include "guiwindow.h" #include "barcolor.h" #include "imagebackground.h" #include "textbutton.h" #include "group.h" #include "multiframe.h" #include "textitem.h" #include "textboxdraw.h" #include "inputnumberformatter.h" #include "choosenbrofplayers.h" #include "gamesprite.h" #include "gamefont.h" #include <mw/font.h> #include <mw/sprite.h> #include <mw/window.h> #include <iostream> #include <string> namespace gui { GuiWindow::GuiWindow() : mw::Window(500,600,"MWetris","images/tetris.bmp") { playFrameIndex_ = multiFrame_.addFrameBack(); highscoreFrameIndex_ = multiFrame_.addFrameBack(); customFrameIndex_ = multiFrame_.addFrameBack(); optionFrameIndex_ = multiFrame_.addFrameBack(); auto background = std::make_shared<ImageBackground>(spriteBackground); multiFrame_.setBackground(background,0); multiFrame_.setBackground(background,playFrameIndex_); multiFrame_.setBackground(background,highscoreFrameIndex_); multiFrame_.setBackground(background,customFrameIndex_); multiFrame_.setBackground(background,optionFrameIndex_); hDistance_ = 30; initFrameMenu(); initHighscoreFrame(); initPlayFrame(); initCustomPlayFrame(); initOptionFrame(); multiFrame_.setCurrentFrame(0); mw::Window::setUnicodeInputEnable(true); resize(500,600); pauseKey_ = SDLK_p; restartKey_ = SDLK_F2; } void GuiWindow::quit() { setQuiting(true); } ButtonPtr GuiWindow::createTextButton(std::string text, int size, std::function<void(GuiItem*)> onClick) { Color textColor(1.0,0.1,0.1); Color focus(0.8, 0.1, 0, 0.3); Color onHover(0.6, 0.1, 0.1); Color notHover(0.4, 0.0, 0.0,0.0); Color pushed(0.8, 0.0, 0, 0.7); ButtonPtr button(new TextButton(text, size, fontDefault, textColor,focus,onHover,notHover,pushed)); button->addOnClickListener(onClick); return button; } TextBoxPtr GuiWindow::createTextBox(int size) { Color textColor(1.0,1.0,1.0); Color focus(0.8, 0.1, 0, 0.3); Color onHover(0.6, 0.1, 0.1); return TextBoxPtr(new TextBoxDraw(size, fontDefault, 30, textColor, focus, onHover)); } void GuiWindow::initFrameMenu() { multiFrame_.setCurrentFrame(0); multiFrame_.add(std::make_shared<TextItem>("MWetris",fontDefault50,80,Color(0.9,0.2,0,0.9)),10,50,false,true); multiFrame_.add(std::make_shared<TextItem>("Made by Marcus Welander",fontDefault18,12,Color(0.9,0.2,0,0.9)),0,0,true,false); // Upper bar. multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30))); // Text is outside due to invY which dont know where the top of the text begin. // The bottom is put where it is supposed to but the invers not. ButtonPtr b1 = createTextButton("Resume", hDistance_, [&](GuiItem*) { multiFrame_.setCurrentFrame(playFrameIndex_); }); resumeButton_ = b1; resumeButton_->setVisible(false); // Menu. ButtonPtr b2 = createTextButton("Play", 35, [&](GuiItem*) { resumeButton_->setVisible(true); multiFrame_.setCurrentFrame(playFrameIndex_); restartGame(); }); ButtonPtr b3 = createTextButton("Custom play", 35, [&](GuiItem*) { multiFrame_.setCurrentFrame(customFrameIndex_); }); ButtonPtr b4 = createTextButton("Highscore", 35, [&](GuiItem*) { multiFrame_.setCurrentFrame(highscoreFrameIndex_); }); ButtonPtr b5 = createTextButton("Options", 35, [&](GuiItem*) { multiFrame_.setCurrentFrame(optionFrameIndex_); }); ButtonPtr b6 = createTextButton("Exit", 35, [&](GuiItem*) { quit(); }); b6->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) { switch (sdlEvent.type) { case SDL_KEYDOWN: SDLKey key = sdlEvent.key.keysym.sym; if (key == SDLK_ESCAPE) { quit(); break; } } }); int x = 10; int y = 150; int distance = 50; // In Bar. multiFrame_.add(b1,0,0,false,true); // Menu. multiFrame_.add(b2,x,y,false,true); y += distance; multiFrame_.add(b3,x,y,false,true); y += distance; multiFrame_.add(b4,x,y,false,true); y += distance; multiFrame_.add(b5,x,y,false,true); y += distance; multiFrame_.add(b6,x,y,false,true); auto textBox = createTextBox(100); multiFrame_.add(textBox,x+50,y+50,false,true); // Focus is switchable by the left and right arrow. GroupPtr group = std::make_shared<Group>(SDLK_UP,SDLK_DOWN); group->add(b1); group->add(b2); group->add(b3); group->add(b4); group->add(b5); group->add(b6); group->add(textBox); multiFrame_.add(group,0,0,false,false); } void GuiWindow::initPlayFrame() { multiFrame_.setCurrentFrame(playFrameIndex_); // Upper bar. multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30))); ButtonPtr b1 = createTextButton("Menu", hDistance_, [&](GuiItem* item) { multiFrame_.setCurrentFrame(0); item->setFocus(false); }); b1->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) { switch (sdlEvent.type) { case SDL_KEYDOWN: SDLKey key = sdlEvent.key.keysym.sym; if (key == SDLK_ESCAPE) { item->click(); break; } } }); ButtonPtr b2 = createTextButton("Restart[F2]", hDistance_, [&](GuiItem* item) { restartGame(); item->setFocus(false); }); b2->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) { switch (sdlEvent.type) { case SDL_KEYDOWN: SDLKey key = sdlEvent.key.keysym.sym; if (key == restartKey_) { item->click(); break; } } }); ButtonPtr b3 = std::make_shared<ChooseNbrOfPlayers>(hDistance_); b3->addOnClickListener([&](GuiItem* item) { ChooseNbrOfPlayers* nbrOfPlayers = (ChooseNbrOfPlayers*) item; int nbr = 1 + nbrOfPlayers->getNbrOfPlayers(); if (nbr > 4) { nbr = 1; } nbrOfPlayers->setNbrOfPlayers(nbr); restartLocalGame(nbr); }); ButtonPtr b4 = createTextButton("Pause[P]", hDistance_, [&](GuiItem* item) { TextButton* textB = (TextButton*) item; // The game is paused? if (isPaused()) { // The game will now be unpaused. textB->setText("Pause[P]"); } else { // The game will now be unpaused. textB->setText("Unpause[P]"); } setPause(!isPaused()); item->setFocus(false); }); b4->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) { switch (sdlEvent.type) { case SDL_KEYDOWN: SDLKey key = sdlEvent.key.keysym.sym; if (key == pauseKey_) { Button* button = (Button*) item; button->click(); break; } } }); multiFrame_.add(b1,0,0,false,true); multiFrame_.add(b2,80,0,false,true); multiFrame_.add(b3,80 + b2->getWidth(),0,false,true); multiFrame_.add(b4,0,0,true,true); } void GuiWindow::initHighscoreFrame() { multiFrame_.setCurrentFrame(highscoreFrameIndex_); // Upper bar. multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30))); ButtonPtr b1 = createTextButton("Menu", hDistance_, [&](GuiItem*) { multiFrame_.setCurrentFrame(0); }); b1->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) { switch (sdlEvent.type) { case SDL_KEYDOWN: SDLKey key = sdlEvent.key.keysym.sym; if (key == SDLK_ESCAPE) { item->click(); break; } } }); multiFrame_.add(b1,0,0,false,true); } void GuiWindow::initCustomPlayFrame() { multiFrame_.setCurrentFrame(customFrameIndex_); // Upper bar. multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30))); ButtonPtr menu = createTextButton("Menu", hDistance_, [&](GuiItem*) { multiFrame_.setCurrentFrame(0); }); multiFrame_.add(menu,0,0,false,true); // Set board size ------------------------------------------------------ TextItemPtr textItem(new TextItem("Width",fontDefault18,18,Color(1.0,1.0,1.0))); multiFrame_.add(textItem,45,50,false,true); customPlayWidth_ = createTextBox(35); customPlayWidth_->setInputFormatter(std::make_shared<InputNumberFormatter>(2)); customPlayWidth_->setText("10"); multiFrame_.add(customPlayWidth_,100,50,false,true); TextItemPtr textItem2(new TextItem("Height",fontDefault18,18,Color(1.0,1.0,1.0))); multiFrame_.add(textItem2,140,50,false,true); customPlayHeight_ = createTextBox(35); customPlayHeight_->setInputFormatter(std::make_shared<InputNumberFormatter>(2)); customPlayHeight_->setText("10"); multiFrame_.add(customPlayHeight_,200,50,false,true); // Set max level ----------------------------------------------------- TextItemPtr textItem3(new TextItem("Max Level",fontDefault18,18,Color(1.0,1.0,1.0))); multiFrame_.add(textItem3,45,100,false,true); customPlaymaxLevel_ = createTextBox(35); customPlaymaxLevel_->setInputFormatter(std::make_shared<InputNumberFormatter>(2)); customPlaymaxLevel_->setText("20"); multiFrame_.add(customPlaymaxLevel_,140,100,false,true); // Create game ----------------------------------------------------- auto button = createTextButton("Create game", 30, [&](GuiItem*) { multiFrame_.setCurrentFrame(playFrameIndex_); std::stringstream stream; stream << customPlayWidth_->getText() << " "; stream << customPlayHeight_->getText() << " "; stream << customPlaymaxLevel_->getText() << " "; int width, height, maxLevel; stream >> width >> height >> maxLevel; createCustomGame(width,height,maxLevel); resumeButton_->setVisible(true); }); multiFrame_.add(button,45,150,false,true); // Add all items to group! GroupPtr group = std::make_shared<Group>(SDLK_UP,SDLK_DOWN); group->add(customPlayWidth_); group->add(customPlayHeight_); group->add(customPlaymaxLevel_); group->add(button); group->add(menu); multiFrame_.add(group,0,0,false,false); } void GuiWindow::initOptionFrame() { multiFrame_.setCurrentFrame(optionFrameIndex_); // Upper bar. multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30))); ButtonPtr b1 = createTextButton("Menu", hDistance_, [&](GuiItem*) { multiFrame_.setCurrentFrame(0); }); b1->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) { switch (sdlEvent.type) { case SDL_KEYDOWN: SDLKey key = sdlEvent.key.keysym.sym; if (key == SDLK_ESCAPE) { item->click(); break; } } }); multiFrame_.add(b1,0,0,false,true); } void GuiWindow::initCreateClientFrame() { multiFrame_.setCurrentFrame(optionFrameIndex_); // Upper bar. multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30))); ButtonPtr b1 = createTextButton("Menu", hDistance_, [&](GuiItem*) { multiFrame_.setCurrentFrame(0); }); } void GuiWindow::resize(int width, int height) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(0,0,width,height); glOrtho(0,width,0,height,-1,1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } // Override mw::Window void GuiWindow::update(Uint32 deltaTime) { multiFrame_.draw(deltaTime/1000.0); if (isUpdatingGame()) { updateGame(deltaTime); } } // Override mw::Window void GuiWindow::eventUpdate(const SDL_Event& windowEvent) { multiFrame_.eventUpdate(windowEvent); if (isUpdatingGame()) { updateGameEvent(windowEvent); } } } // Namespace gui.<commit_msg>Fixed! Closing the window now makes it close.<commit_after>#include "guiwindow.h" #include "barcolor.h" #include "imagebackground.h" #include "textbutton.h" #include "group.h" #include "multiframe.h" #include "textitem.h" #include "textboxdraw.h" #include "inputnumberformatter.h" #include "choosenbrofplayers.h" #include "gamesprite.h" #include "gamefont.h" #include <mw/font.h> #include <mw/sprite.h> #include <mw/window.h> #include <iostream> #include <string> namespace gui { GuiWindow::GuiWindow() : mw::Window(500,600,"MWetris","images/tetris.bmp") { playFrameIndex_ = multiFrame_.addFrameBack(); highscoreFrameIndex_ = multiFrame_.addFrameBack(); customFrameIndex_ = multiFrame_.addFrameBack(); optionFrameIndex_ = multiFrame_.addFrameBack(); auto background = std::make_shared<ImageBackground>(spriteBackground); multiFrame_.setBackground(background,0); multiFrame_.setBackground(background,playFrameIndex_); multiFrame_.setBackground(background,highscoreFrameIndex_); multiFrame_.setBackground(background,customFrameIndex_); multiFrame_.setBackground(background,optionFrameIndex_); hDistance_ = 30; initFrameMenu(); initHighscoreFrame(); initPlayFrame(); initCustomPlayFrame(); initOptionFrame(); multiFrame_.setCurrentFrame(0); mw::Window::setUnicodeInputEnable(true); resize(500,600); pauseKey_ = SDLK_p; restartKey_ = SDLK_F2; } void GuiWindow::quit() { setQuiting(true); } ButtonPtr GuiWindow::createTextButton(std::string text, int size, std::function<void(GuiItem*)> onClick) { Color textColor(1.0,0.1,0.1); Color focus(0.8, 0.1, 0, 0.3); Color onHover(0.6, 0.1, 0.1); Color notHover(0.4, 0.0, 0.0,0.0); Color pushed(0.8, 0.0, 0, 0.7); ButtonPtr button(new TextButton(text, size, fontDefault, textColor,focus,onHover,notHover,pushed)); button->addOnClickListener(onClick); return button; } TextBoxPtr GuiWindow::createTextBox(int size) { Color textColor(1.0,1.0,1.0); Color focus(0.8, 0.1, 0, 0.3); Color onHover(0.6, 0.1, 0.1); return TextBoxPtr(new TextBoxDraw(size, fontDefault, 30, textColor, focus, onHover)); } void GuiWindow::initFrameMenu() { multiFrame_.setCurrentFrame(0); multiFrame_.add(std::make_shared<TextItem>("MWetris",fontDefault50,80,Color(0.9,0.2,0,0.9)),10,50,false,true); multiFrame_.add(std::make_shared<TextItem>("Made by Marcus Welander",fontDefault18,12,Color(0.9,0.2,0,0.9)),0,0,true,false); // Upper bar. multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30))); // Text is outside due to invY which dont know where the top of the text begin. // The bottom is put where it is supposed to but the invers not. ButtonPtr b1 = createTextButton("Resume", hDistance_, [&](GuiItem*) { multiFrame_.setCurrentFrame(playFrameIndex_); }); resumeButton_ = b1; resumeButton_->setVisible(false); // Menu. ButtonPtr b2 = createTextButton("Play", 35, [&](GuiItem*) { resumeButton_->setVisible(true); multiFrame_.setCurrentFrame(playFrameIndex_); restartGame(); }); ButtonPtr b3 = createTextButton("Custom play", 35, [&](GuiItem*) { multiFrame_.setCurrentFrame(customFrameIndex_); }); ButtonPtr b4 = createTextButton("Highscore", 35, [&](GuiItem*) { multiFrame_.setCurrentFrame(highscoreFrameIndex_); }); ButtonPtr b5 = createTextButton("Options", 35, [&](GuiItem*) { multiFrame_.setCurrentFrame(optionFrameIndex_); }); ButtonPtr b6 = createTextButton("Exit", 35, [&](GuiItem*) { quit(); }); b6->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) { switch (sdlEvent.type) { case SDL_QUIT: quit(); break; case SDL_KEYDOWN: SDLKey key = sdlEvent.key.keysym.sym; if (key == SDLK_ESCAPE) { quit(); break; } } }); int x = 10; int y = 150; int distance = 50; // In Bar. multiFrame_.add(b1,0,0,false,true); // Menu. multiFrame_.add(b2,x,y,false,true); y += distance; multiFrame_.add(b3,x,y,false,true); y += distance; multiFrame_.add(b4,x,y,false,true); y += distance; multiFrame_.add(b5,x,y,false,true); y += distance; multiFrame_.add(b6,x,y,false,true); auto textBox = createTextBox(100); multiFrame_.add(textBox,x+50,y+50,false,true); // Focus is switchable by the left and right arrow. GroupPtr group = std::make_shared<Group>(SDLK_UP,SDLK_DOWN); group->add(b1); group->add(b2); group->add(b3); group->add(b4); group->add(b5); group->add(b6); group->add(textBox); multiFrame_.add(group,0,0,false,false); } void GuiWindow::initPlayFrame() { multiFrame_.setCurrentFrame(playFrameIndex_); // Upper bar. multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30))); ButtonPtr b1 = createTextButton("Menu", hDistance_, [&](GuiItem* item) { multiFrame_.setCurrentFrame(0); item->setFocus(false); }); b1->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) { switch (sdlEvent.type) { case SDL_KEYDOWN: SDLKey key = sdlEvent.key.keysym.sym; if (key == SDLK_ESCAPE) { item->click(); break; } } }); ButtonPtr b2 = createTextButton("Restart[F2]", hDistance_, [&](GuiItem* item) { restartGame(); item->setFocus(false); }); b2->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) { switch (sdlEvent.type) { case SDL_KEYDOWN: SDLKey key = sdlEvent.key.keysym.sym; if (key == restartKey_) { item->click(); break; } } }); ButtonPtr b3 = std::make_shared<ChooseNbrOfPlayers>(hDistance_); b3->addOnClickListener([&](GuiItem* item) { ChooseNbrOfPlayers* nbrOfPlayers = (ChooseNbrOfPlayers*) item; int nbr = 1 + nbrOfPlayers->getNbrOfPlayers(); if (nbr > 4) { nbr = 1; } nbrOfPlayers->setNbrOfPlayers(nbr); restartLocalGame(nbr); }); ButtonPtr b4 = createTextButton("Pause[P]", hDistance_, [&](GuiItem* item) { TextButton* textB = (TextButton*) item; // The game is paused? if (isPaused()) { // The game will now be unpaused. textB->setText("Pause[P]"); } else { // The game will now be unpaused. textB->setText("Unpause[P]"); } setPause(!isPaused()); item->setFocus(false); }); b4->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) { switch (sdlEvent.type) { case SDL_KEYDOWN: SDLKey key = sdlEvent.key.keysym.sym; if (key == pauseKey_) { Button* button = (Button*) item; button->click(); break; } } }); multiFrame_.add(b1,0,0,false,true); multiFrame_.add(b2,80,0,false,true); multiFrame_.add(b3,80 + b2->getWidth(),0,false,true); multiFrame_.add(b4,0,0,true,true); } void GuiWindow::initHighscoreFrame() { multiFrame_.setCurrentFrame(highscoreFrameIndex_); // Upper bar. multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30))); ButtonPtr b1 = createTextButton("Menu", hDistance_, [&](GuiItem*) { multiFrame_.setCurrentFrame(0); }); b1->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) { switch (sdlEvent.type) { case SDL_KEYDOWN: SDLKey key = sdlEvent.key.keysym.sym; if (key == SDLK_ESCAPE) { item->click(); break; } } }); multiFrame_.add(b1,0,0,false,true); } void GuiWindow::initCustomPlayFrame() { multiFrame_.setCurrentFrame(customFrameIndex_); // Upper bar. multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30))); ButtonPtr menu = createTextButton("Menu", hDistance_, [&](GuiItem*) { multiFrame_.setCurrentFrame(0); }); multiFrame_.add(menu,0,0,false,true); // Set board size ------------------------------------------------------ TextItemPtr textItem(new TextItem("Width",fontDefault18,18,Color(1.0,1.0,1.0))); multiFrame_.add(textItem,45,50,false,true); customPlayWidth_ = createTextBox(35); customPlayWidth_->setInputFormatter(std::make_shared<InputNumberFormatter>(2)); customPlayWidth_->setText("10"); multiFrame_.add(customPlayWidth_,100,50,false,true); TextItemPtr textItem2(new TextItem("Height",fontDefault18,18,Color(1.0,1.0,1.0))); multiFrame_.add(textItem2,140,50,false,true); customPlayHeight_ = createTextBox(35); customPlayHeight_->setInputFormatter(std::make_shared<InputNumberFormatter>(2)); customPlayHeight_->setText("10"); multiFrame_.add(customPlayHeight_,200,50,false,true); // Set max level ----------------------------------------------------- TextItemPtr textItem3(new TextItem("Max Level",fontDefault18,18,Color(1.0,1.0,1.0))); multiFrame_.add(textItem3,45,100,false,true); customPlaymaxLevel_ = createTextBox(35); customPlaymaxLevel_->setInputFormatter(std::make_shared<InputNumberFormatter>(2)); customPlaymaxLevel_->setText("20"); multiFrame_.add(customPlaymaxLevel_,140,100,false,true); // Create game ----------------------------------------------------- auto button = createTextButton("Create game", 30, [&](GuiItem*) { multiFrame_.setCurrentFrame(playFrameIndex_); std::stringstream stream; stream << customPlayWidth_->getText() << " "; stream << customPlayHeight_->getText() << " "; stream << customPlaymaxLevel_->getText() << " "; int width, height, maxLevel; stream >> width >> height >> maxLevel; createCustomGame(width,height,maxLevel); resumeButton_->setVisible(true); }); multiFrame_.add(button,45,150,false,true); // Add all items to group! GroupPtr group = std::make_shared<Group>(SDLK_UP,SDLK_DOWN); group->add(customPlayWidth_); group->add(customPlayHeight_); group->add(customPlaymaxLevel_); group->add(button); group->add(menu); multiFrame_.add(group,0,0,false,false); } void GuiWindow::initOptionFrame() { multiFrame_.setCurrentFrame(optionFrameIndex_); // Upper bar. multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30))); ButtonPtr b1 = createTextButton("Menu", hDistance_, [&](GuiItem*) { multiFrame_.setCurrentFrame(0); }); b1->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) { switch (sdlEvent.type) { case SDL_KEYDOWN: SDLKey key = sdlEvent.key.keysym.sym; if (key == SDLK_ESCAPE) { item->click(); break; } } }); multiFrame_.add(b1,0,0,false,true); } void GuiWindow::initCreateClientFrame() { multiFrame_.setCurrentFrame(optionFrameIndex_); // Upper bar. multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30))); ButtonPtr b1 = createTextButton("Menu", hDistance_, [&](GuiItem*) { multiFrame_.setCurrentFrame(0); }); } void GuiWindow::resize(int width, int height) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(0,0,width,height); glOrtho(0,width,0,height,-1,1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } // Override mw::Window void GuiWindow::update(Uint32 deltaTime) { multiFrame_.draw(deltaTime/1000.0); if (isUpdatingGame()) { updateGame(deltaTime); } } // Override mw::Window void GuiWindow::eventUpdate(const SDL_Event& windowEvent) { multiFrame_.eventUpdate(windowEvent); if (isUpdatingGame()) { updateGameEvent(windowEvent); } } } // Namespace gui.<|endoftext|>
<commit_before>#include "catch.hpp" #include <cobalt/object.hpp> using namespace cobalt; class renderer : public basic_component<"renderer"_hash> { public: renderer(bool& destroyed) : _destroyed(destroyed) {} virtual ~renderer() { _destroyed = true; } virtual void draw() const { } private: bool& _destroyed; }; class transform : public basic_component<"transform"_hash> { public: }; class my_component : public component { public: virtual hash_type type() const noexcept override { return "my_component"_hash; } }; TEST_CASE("object") { ref_ptr<object> o = new object(); SECTION("information") { printf("sizeof(std::string) := %zu\n", sizeof(std::string)); printf("sizeof(std::vector<object>) := %zu\n", sizeof(std::vector<object>)); printf("sizeof(std::deque<object>) := %zu\n", sizeof(std::deque<object>)); printf("sizeof(object) := %zu\n", sizeof(object)); printf("sizeof(component) := %zu\n", sizeof(component)); printf("sizeof(renderer) := %zu\n", sizeof(renderer)); printf("sizeof(my_component) := %zu\n", sizeof(my_component)); } SECTION("add child") { auto child = o->add_child(new object()); REQUIRE(child->parent() == o.get()); } SECTION("add component") { bool renderer_destroyed = false; auto r = new renderer(renderer_destroyed); auto c = o->add_component(r); SECTION("check preconditions") { REQUIRE(c == r); REQUIRE(c->object() == o.get()); REQUIRE(renderer_destroyed == false); } SECTION("find component by component type") { auto f1 = (renderer*)o->find_component(renderer::component_type); REQUIRE(f1 == r); REQUIRE(o->find_component(transform::component_type) == nullptr); f1->draw(); } SECTION("find component by component name") { auto f1 = (renderer*)o->find_component("renderer"_hash); REQUIRE(f1 == r); REQUIRE(o->find_component("transform"_hash) == nullptr); REQUIRE(o->find_component("my_component"_hash) == nullptr); f1->draw(); } SECTION("find component with template") { auto f2 = o->find_component<renderer>(); REQUIRE(f2 == r); REQUIRE(o->find_component<transform>() == nullptr); //o->find_component<my_component>(); // won't compile due to enable_if<> f2->draw(); } SECTION("find components by component type") { std::vector<component*> vec; o->find_components(renderer::component_type, std::back_inserter(vec)); REQUIRE(vec.size() == 1); REQUIRE(vec[0] == r); } SECTION("find components with template") { std::vector<renderer*> vec; o->find_components<renderer>(std::back_inserter(vec)); REQUIRE(vec.size() == 1); REQUIRE(vec[0] == r); } SECTION("remove component") { r->remove_from_parent(); REQUIRE(renderer_destroyed == true); } } } <commit_msg>Added more unit tests for object.hpp<commit_after>#include "catch.hpp" #include <cobalt/object.hpp> using namespace cobalt; class renderer : public basic_component<"renderer"_hash> { public: renderer(bool& destroyed) : _destroyed(destroyed) {} virtual ~renderer() { _destroyed = true; } virtual void draw() const { } private: bool& _destroyed; }; class transform : public basic_component<"transform"_hash> { public: }; class my_component : public component { public: virtual hash_type type() const noexcept override { return "my_component"_hash; } }; TEST_CASE("information") { printf("sizeof(std::string) := %zu\n", sizeof(std::string)); printf("sizeof(std::vector<object>) := %zu\n", sizeof(std::vector<object>)); printf("sizeof(std::deque<object>) := %zu\n", sizeof(std::deque<object>)); printf("sizeof(object) := %zu\n", sizeof(object)); printf("sizeof(component) := %zu\n", sizeof(component)); printf("sizeof(renderer) := %zu\n", sizeof(renderer)); printf("sizeof(my_component) := %zu\n", sizeof(my_component)); } TEST_CASE("object") { ref_ptr<object> o = new object(); SECTION("add child") { auto child = o->add_child(new object()); REQUIRE(child->parent() == o.get()); SECTION("remove child") { auto removed = o->remove_child(child); REQUIRE(removed.get() == child); } SECTION("self remove child") { child->remove_from_parent(); REQUIRE(o->remove_child(child) == nullptr); } } SECTION("add component") { bool renderer_destroyed = false; auto r = new renderer(renderer_destroyed); auto c = o->add_component(r); o->add_component(new transform()); SECTION("check preconditions") { REQUIRE(c == r); REQUIRE(c->object() == o.get()); REQUIRE(renderer_destroyed == false); } SECTION("find component by type") { auto f1 = (renderer*)o->find_component(renderer::component_type); REQUIRE(f1 == r); REQUIRE_FALSE(o->find_component(transform::component_type) == nullptr); f1->draw(); // will compile } SECTION("find component by name") { auto f1 = (renderer*)o->find_component("renderer"_hash); REQUIRE(f1 == r); REQUIRE_FALSE(o->find_component("transform"_hash) == nullptr); REQUIRE(o->find_component("my_component"_hash) == nullptr); f1->draw(); // will compile } SECTION("find component with template") { auto f2 = o->find_component<renderer>(); REQUIRE(f2 == r); REQUIRE_FALSE(o->find_component<transform>() == nullptr); //o->find_component<my_component>(); // won't compile due to enable_if<> f2->draw(); // will compile } SECTION("find components by type") { std::vector<component*> vec; o->find_components(renderer::component_type, std::back_inserter(vec)); REQUIRE(vec.size() == 1); REQUIRE(vec[0] == r); } SECTION("find components with template") { std::vector<renderer*> vec; o->find_components<renderer>(std::back_inserter(vec)); REQUIRE(vec.size() == 1); REQUIRE(vec[0] == r); } SECTION("remove component") { r->remove_from_parent(); REQUIRE(renderer_destroyed == true); } } } <|endoftext|>
<commit_before><commit_msg>fix order optimizer poly_start at the cost of efficiency<commit_after><|endoftext|>
<commit_before><commit_msg>Correct Camera projection matrix<commit_after><|endoftext|>
<commit_before><commit_msg>Render: Render multiple layer of the level<commit_after><|endoftext|>
<commit_before><commit_msg>remove empty destructors in-lined on Mac, causing build errors<commit_after><|endoftext|>
<commit_before><commit_msg>Simplifications in unit tests for stencil<commit_after><|endoftext|>
<commit_before>/** \brief Utility for displaying various bits of info about a collection of MARC records. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2015-2018 Universitätsbibliothek Tübingen. 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 as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <map> #include <stdexcept> #include <unordered_set> #include <vector> #include <cstdio> #include <cstdlib> #include "FileUtil.h" #include "MARC.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--do-not-abort-on-empty-subfields] marc_data\n"; std::exit(EXIT_FAILURE); } void CheckFieldOrder(const MARC::Record &record) { std::string last_tag; for (const auto &field : record) { const std::string current_tag(field.getTag().toString()); if (unlikely(current_tag < last_tag)) LOG_ERROR("invalid tag order in the record with control number \"" + record.getControlNumber() + "\"!"); last_tag = current_tag; } } void CheckDataField(const bool do_not_abort_on_empty_subfields, const MARC::Record::Field &data_field, const std::string &control_number) { const std::string &contents(data_field.getContents()); if (contents.length() < 5) // Need at least 2 indicators a delimiter a subfield code + subfield contents LOG_ERROR("short data field in record w/ control number \"" + control_number + "\"!"); if (contents[2] != '\x1F') LOG_ERROR("first subfield delimiter is missing for the record w/ control number \"" + control_number + "\"!"); // Check the subfield structure for consistency: bool delimiter_seen(false), subfield_code_seen(false); for (const char ch : contents) { if (delimiter_seen) { delimiter_seen = false; subfield_code_seen = true; } else if (ch == '\x1F') { if (unlikely(subfield_code_seen)) { if (do_not_abort_on_empty_subfields) LOG_WARNING("empty subfield in a " + data_field.getTag().toString() +"-field in the record w/ control number \"" + control_number + "\"!"); else LOG_ERROR("empty subfield in a " + data_field.getTag().toString() +"-field in the record w/ control number \"" + control_number + "\"!"); } delimiter_seen = true; } else subfield_code_seen = false; } if (unlikely(delimiter_seen)) LOG_ERROR("subfield delimiter at end of " + data_field.getTag().toString() + "-field in record w/ control number \"" + control_number + "\"!"); if (unlikely(subfield_code_seen)) { if (do_not_abort_on_empty_subfields) LOG_WARNING("empty subfield at the end of a " + data_field.getTag().toString() + "-field in the record w/ control number \"" + control_number + "\"!"); else LOG_ERROR("empty subfield at the end of a " + data_field.getTag().toString() + "-field in the record w/ control number \"" + control_number + "\"!"); } } void CheckLocalBlockConsistency(const MARC::Record &record) { auto field(record.begin()); // Skip to the beginning of the first local block: while (field != record.end() and field->getTag().toString() != "LOK") ++field; // Check the internal structure of each local block: while (field != record.end()) { if (field->getLocalTag() != "000") LOG_ERROR("local block does not start w/ a 000 pseudo tag in the record w/ control number \"" + record.getControlNumber() + "\"!!"); if (++field == record.end() or field->getLocalTag() != "001") LOG_ERROR("local block does not contain a 001 pseudo tag after a 000 pseudo tag in the record w/ control number \"" + record.getControlNumber() + "\"!!"); std::string last_local_tag; while (field != record.end() and field->getLocalTag() != "000") { const std::string current_local_tag(field->getLocalTag()); if (unlikely(current_local_tag < last_local_tag)) LOG_ERROR("invalid tag order in a local block in the record with control number \"" + record.getControlNumber() + "\"!"); last_local_tag = current_local_tag; ++field; } } } void ProcessRecords(const bool do_not_abort_on_empty_subfields, MARC::Reader * const marc_reader) { unsigned record_count(0); while (const MARC::Record record = marc_reader->read()) { ++record_count; const std::string CONTROL_NUMBER(record.getControlNumber()); if (unlikely(CONTROL_NUMBER.empty())) LOG_ERROR("Record #" + std::to_string(record_count) + " is missing a control number!"); CheckFieldOrder(record); MARC::Tag last_tag(std::string(MARC::Record::TAG_LENGTH, ' ')); for (const auto &field : record) { if (not field.getTag().isTagOfControlField()) CheckDataField(do_not_abort_on_empty_subfields, field, CONTROL_NUMBER); if (unlikely(field.getTag() < last_tag)) LOG_ERROR("Incorrect non-alphanumeric field order in record w/ control number \"" + CONTROL_NUMBER + "\"!"); last_tag = field.getTag(); } CheckLocalBlockConsistency(record); } std::cout << "Data set contains " << record_count << " valid MARC record(s).\n"; } } // unnamed namespace int Main(int argc, char *argv[]) { ::progname = argv[0]; if (argc < 2) Usage(); bool do_not_abort_on_empty_subfields(false); if (std::strcmp(argv[1], "--do-not-abort-on-empty-subfields") == 0) { do_not_abort_on_empty_subfields = true; --argc, ++argv; } if (argc != 2) Usage(); std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(argv[1])); ProcessRecords(do_not_abort_on_empty_subfields, marc_reader.get()); return EXIT_SUCCESS; } <commit_msg>Update marc_check.cc<commit_after>/** \brief Utility for displaying various bits of info about a collection of MARC records. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2015-2018 Universitätsbibliothek Tübingen. 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 as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <map> #include <stdexcept> #include <unordered_set> #include <vector> #include <cstdio> #include <cstdlib> #include "FileUtil.h" #include "MARC.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--do-not-abort-on-empty-subfields] marc_data\n"; std::exit(EXIT_FAILURE); } void CheckFieldOrder(const MARC::Record &record) { std::string last_tag; for (const auto &field : record) { const std::string current_tag(field.getTag().toString()); if (unlikely(current_tag < last_tag)) LOG_ERROR("invalid tag order in the record with control number \"" + record.getControlNumber() + "\"!"); last_tag = current_tag; } } void CheckDataField(const bool do_not_abort_on_empty_subfields, const MARC::Record::Field &data_field, const std::string &control_number) { const std::string &contents(data_field.getContents()); if (contents.length() < 5) // Need at least 2 indicators a delimiter a subfield code + subfield contents LOG_ERROR("short data field in record w/ control number \"" + control_number + "\"!"); if (contents[2] != '\x1F') LOG_ERROR("first subfield delimiter is missing for the record w/ control number \"" + control_number + "\"!"); // Check the subfield structure for consistency: bool delimiter_seen(false), subfield_code_seen(false); for (const char ch : contents) { if (delimiter_seen) { delimiter_seen = false; subfield_code_seen = true; } else if (ch == '\x1F') { if (unlikely(subfield_code_seen)) { if (do_not_abort_on_empty_subfields) LOG_WARNING("empty subfield in a " + data_field.getTag().toString() + "-field in the record w/ control number \"" + control_number + "\"!"); else LOG_ERROR("empty subfield in a " + data_field.getTag().toString() + "-field in the record w/ control number \"" + control_number + "\"!"); } delimiter_seen = true; } else subfield_code_seen = false; } if (unlikely(delimiter_seen)) LOG_ERROR("subfield delimiter at end of " + data_field.getTag().toString() + "-field in record w/ control number \"" + control_number + "\"!"); if (unlikely(subfield_code_seen)) { if (do_not_abort_on_empty_subfields) LOG_WARNING("empty subfield at the end of a " + data_field.getTag().toString() + "-field in the record w/ control number \"" + control_number + "\"!"); else LOG_ERROR("empty subfield at the end of a " + data_field.getTag().toString() + "-field in the record w/ control number \"" + control_number + "\"!"); } } void CheckLocalBlockConsistency(const MARC::Record &record) { auto field(record.begin()); // Skip to the beginning of the first local block: while (field != record.end() and field->getTag().toString() != "LOK") ++field; // Check the internal structure of each local block: while (field != record.end()) { if (field->getLocalTag() != "000") LOG_ERROR("local block does not start w/ a 000 pseudo tag in the record w/ control number \"" + record.getControlNumber() + "\"!!"); if (++field == record.end() or field->getLocalTag() != "001") LOG_ERROR("local block does not contain a 001 pseudo tag after a 000 pseudo tag in the record w/ control number \"" + record.getControlNumber() + "\"!!"); std::string last_local_tag; while (field != record.end() and field->getLocalTag() != "000") { const std::string current_local_tag(field->getLocalTag()); if (unlikely(current_local_tag < last_local_tag)) LOG_ERROR("invalid tag order in a local block in the record with control number \"" + record.getControlNumber() + "\"!"); last_local_tag = current_local_tag; ++field; } } } void ProcessRecords(const bool do_not_abort_on_empty_subfields, MARC::Reader * const marc_reader) { unsigned record_count(0); while (const MARC::Record record = marc_reader->read()) { ++record_count; const std::string CONTROL_NUMBER(record.getControlNumber()); if (unlikely(CONTROL_NUMBER.empty())) LOG_ERROR("Record #" + std::to_string(record_count) + " is missing a control number!"); CheckFieldOrder(record); MARC::Tag last_tag(std::string(MARC::Record::TAG_LENGTH, ' ')); for (const auto &field : record) { if (not field.getTag().isTagOfControlField()) CheckDataField(do_not_abort_on_empty_subfields, field, CONTROL_NUMBER); if (unlikely(field.getTag() < last_tag)) LOG_ERROR("Incorrect non-alphanumeric field order in record w/ control number \"" + CONTROL_NUMBER + "\"!"); last_tag = field.getTag(); } CheckLocalBlockConsistency(record); } std::cout << "Data set contains " << record_count << " valid MARC record(s).\n"; } } // unnamed namespace int Main(int argc, char *argv[]) { ::progname = argv[0]; if (argc < 2) Usage(); bool do_not_abort_on_empty_subfields(false); if (std::strcmp(argv[1], "--do-not-abort-on-empty-subfields") == 0) { do_not_abort_on_empty_subfields = true; --argc, ++argv; } if (argc != 2) Usage(); std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(argv[1])); ProcessRecords(do_not_abort_on_empty_subfields, marc_reader.get()); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// \brief Command-line utility to send email messages. #include <iostream> #include <cstdlib> #include "IniFile.h" #include "EmailSender.h" #include "StringUtil.h" #include "TextUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--sender=sender] [-reply-to=reply_to] --recipients=recipients\n" << " [--cc-recipients=cc_recipients] [--bcc-recipients=bcc_recipients] [--expand-newline-escapes]\n" << " --subject=subject --message-body=message_body [--priority=priority] [--format=format]\n\n" << " \"priority\" has to be one of \"very_low\", \"low\", \"medium\", \"high\", or\n" << " \"very_high\". \"format\" has to be one of \"plain_text\" or \"html\" At least one\n" << " of \"sender\" or \"reply-to\" has to be specified. If \"--expand-newline-escapes\" has\n" << " been specified, all occurrences of \\n in the message body will be replaced by a line feed\n" << " and a double backslash by a single backslash. The message body is assumed to be UTF-8!\n\n"; std::exit(EXIT_FAILURE); } EmailSender::Priority StringToPriority(const std::string &priority_candidate) { if (priority_candidate == "very_low") return EmailSender::VERY_LOW; if (priority_candidate == "low") return EmailSender::LOW; if (priority_candidate == "medium") return EmailSender::MEDIUM; if (priority_candidate == "high") return EmailSender::HIGH; if (priority_candidate == "very_high") return EmailSender::VERY_HIGH; LOG_ERROR("\"" + priority_candidate + "\" is an unknown priority!"); } EmailSender::Format StringToFormat(const std::string &format_candidate) { if (format_candidate == "plain_text") return EmailSender::PLAIN_TEXT; else if (format_candidate == "html") return EmailSender::HTML; LOG_ERROR("\"" + format_candidate + "\" is an unknown format!"); } bool ExtractArg(const char * const argument, const std::string &arg_name, std::string * const arg_value) { if (StringUtil::StartsWith(argument, "--" + arg_name + "=")) { *arg_value = argument + arg_name.length() + 3 /* two dashes and one equal sign */; if (arg_value->empty()) LOG_ERROR(arg_name + " is missing!"); return true; } return false; } void ParseCommandLine(char **argv, std::string * const sender, std::string * const reply_to, std::string * const recipients, std::string * const cc_recipients, std::string * const bcc_recipients, std::string * const subject, std::string * const message_body, std::string * const priority, std::string * const format, bool * const expand_newline_escapes) { *expand_newline_escapes = false; while (*argv != nullptr) { if (std::strcmp(*argv, "--expand-newline-escapes") == 0) { *expand_newline_escapes = true; ++argv; } else if (ExtractArg(*argv, "sender", sender) or ExtractArg(*argv, "reply-to", reply_to) or ExtractArg(*argv, "recipients", recipients) or ExtractArg(*argv, "cc-recipients", cc_recipients) or ExtractArg(*argv, "bcc-recipients", bcc_recipients) or ExtractArg(*argv, "subject", subject) or ExtractArg(*argv, "message-body", message_body) or ExtractArg(*argv, "priority", priority) or ExtractArg(*argv, "format", format)) ++argv; else LOG_ERROR("unknown argument: " + std::string(*argv)); } if (recipients->empty() and cc_recipients->empty() and bcc_recipients->empty()) LOG_ERROR("you must specify a recipient!"); if (subject->empty()) LOG_ERROR("you must specify a subject!"); if (message_body->empty()) LOG_ERROR("you must specify a message-body!"); } std::vector<std::string> SplitRecipients(const std::string &recipients) { std::vector<std::string> individual_recipients; StringUtil::Split(recipients, ',', &individual_recipients); return individual_recipients; } // "text" is assumed to be UTF-8 encoded. std::string ExpandNewlineEscapes(const std::string &text) { std::wstring escaped_string; if (unlikely(not TextUtil::UTF8ToWCharString(text, &escaped_string))) LOG_ERROR("can't convert a supposed UTF-8 string to a wide string!"); std::wstring unescaped_string; bool backslash_seen(false); for (auto ch : escaped_string) { if (backslash_seen) { if (ch == '\\') unescaped_string += '\\'; else if (ch == 'n') unescaped_string += '\n'; else { std::string utf8_string; TextUtil::WCharToUTF8String(ch, &utf8_string); LOG_ERROR("unknown escape: \\" + utf8_string + "!"); } backslash_seen = false; } else if (ch == '\\') backslash_seen = true; else unescaped_string += ch; } std::string utf8_string; if (unlikely(not TextUtil::WCharToUTF8String(unescaped_string, &utf8_string))) LOG_ERROR("can't convert a supposed wide string to a UTF-8 string!"); return utf8_string; } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc == 1) Usage(); EmailSender::Priority priority(EmailSender::DO_NOT_SET_PRIORITY); EmailSender::Format format(EmailSender::PLAIN_TEXT); std::string sender, reply_to, recipients, cc_recipients, bcc_recipients, subject, message_body, priority_as_string, format_as_string; bool expand_newline_escapes; ParseCommandLine(++argv, &sender, &reply_to, &recipients, &cc_recipients, &bcc_recipients, &subject, &message_body, &priority_as_string, &format_as_string, &expand_newline_escapes); if (sender.empty() and reply_to.empty()) { IniFile ini_file("/usr/local/var/lib/tuelib/cronjobs/smtp_server.conf"); sender = ini_file.getString("SMTPServer", "server_user") + "@uni-tuebingen.de"; } if (not priority_as_string.empty()) priority = StringToPriority(priority_as_string); if (not format_as_string.empty()) format = StringToFormat(format_as_string); if (expand_newline_escapes) message_body = ExpandNewlineEscapes(message_body); if (not EmailSender::SendEmail(sender, SplitRecipients(recipients), SplitRecipients(cc_recipients), SplitRecipients(bcc_recipients), subject, message_body, priority, format, reply_to)) LOG_ERROR("failed to send your email!"); return EXIT_SUCCESS; } <commit_msg>Added a helpful message foe debugging problems.<commit_after>/** \brief Command-line utility to send email messages. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2018 Universitätsbibliothek Tübingen. 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 as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <cstdlib> #include "IniFile.h" #include "EmailSender.h" #include "MiscUtil.h" #include "StringUtil.h" #include "TextUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--sender=sender] [-reply-to=reply_to] --recipients=recipients\n" << " [--cc-recipients=cc_recipients] [--bcc-recipients=bcc_recipients] [--expand-newline-escapes]\n" << " --subject=subject --message-body=message_body [--priority=priority] [--format=format]\n\n" << " \"priority\" has to be one of \"very_low\", \"low\", \"medium\", \"high\", or\n" << " \"very_high\". \"format\" has to be one of \"plain_text\" or \"html\" At least one\n" << " of \"sender\" or \"reply-to\" has to be specified. If \"--expand-newline-escapes\" has\n" << " been specified, all occurrences of \\n in the message body will be replaced by a line feed\n" << " and a double backslash by a single backslash. The message body is assumed to be UTF-8!\n\n"; std::exit(EXIT_FAILURE); } EmailSender::Priority StringToPriority(const std::string &priority_candidate) { if (priority_candidate == "very_low") return EmailSender::VERY_LOW; if (priority_candidate == "low") return EmailSender::LOW; if (priority_candidate == "medium") return EmailSender::MEDIUM; if (priority_candidate == "high") return EmailSender::HIGH; if (priority_candidate == "very_high") return EmailSender::VERY_HIGH; LOG_ERROR("\"" + priority_candidate + "\" is an unknown priority!"); } EmailSender::Format StringToFormat(const std::string &format_candidate) { if (format_candidate == "plain_text") return EmailSender::PLAIN_TEXT; else if (format_candidate == "html") return EmailSender::HTML; LOG_ERROR("\"" + format_candidate + "\" is an unknown format!"); } bool ExtractArg(const char * const argument, const std::string &arg_name, std::string * const arg_value) { if (StringUtil::StartsWith(argument, "--" + arg_name + "=")) { *arg_value = argument + arg_name.length() + 3 /* two dashes and one equal sign */; if (arg_value->empty()) LOG_ERROR(arg_name + " is missing!"); return true; } return false; } void ParseCommandLine(char **argv, std::string * const sender, std::string * const reply_to, std::string * const recipients, std::string * const cc_recipients, std::string * const bcc_recipients, std::string * const subject, std::string * const message_body, std::string * const priority, std::string * const format, bool * const expand_newline_escapes) { *expand_newline_escapes = false; while (*argv != nullptr) { if (std::strcmp(*argv, "--expand-newline-escapes") == 0) { *expand_newline_escapes = true; ++argv; } else if (ExtractArg(*argv, "sender", sender) or ExtractArg(*argv, "reply-to", reply_to) or ExtractArg(*argv, "recipients", recipients) or ExtractArg(*argv, "cc-recipients", cc_recipients) or ExtractArg(*argv, "bcc-recipients", bcc_recipients) or ExtractArg(*argv, "subject", subject) or ExtractArg(*argv, "message-body", message_body) or ExtractArg(*argv, "priority", priority) or ExtractArg(*argv, "format", format)) ++argv; else LOG_ERROR("unknown argument: " + std::string(*argv)); } if (recipients->empty() and cc_recipients->empty() and bcc_recipients->empty()) LOG_ERROR("you must specify a recipient!"); if (subject->empty()) LOG_ERROR("you must specify a subject!"); if (message_body->empty()) LOG_ERROR("you must specify a message-body!"); } std::vector<std::string> SplitRecipients(const std::string &recipients) { std::vector<std::string> individual_recipients; StringUtil::Split(recipients, ',', &individual_recipients); return individual_recipients; } // "text" is assumed to be UTF-8 encoded. std::string ExpandNewlineEscapes(const std::string &text) { std::wstring escaped_string; if (unlikely(not TextUtil::UTF8ToWCharString(text, &escaped_string))) LOG_ERROR("can't convert a supposed UTF-8 string to a wide string!"); std::wstring unescaped_string; bool backslash_seen(false); for (auto ch : escaped_string) { if (backslash_seen) { if (ch == '\\') unescaped_string += '\\'; else if (ch == 'n') unescaped_string += '\n'; else { std::string utf8_string; TextUtil::WCharToUTF8String(ch, &utf8_string); LOG_ERROR("unknown escape: \\" + utf8_string + "!"); } backslash_seen = false; } else if (ch == '\\') backslash_seen = true; else unescaped_string += ch; } std::string utf8_string; if (unlikely(not TextUtil::WCharToUTF8String(unescaped_string, &utf8_string))) LOG_ERROR("can't convert a supposed wide string to a UTF-8 string!"); return utf8_string; } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc == 1) Usage(); EmailSender::Priority priority(EmailSender::DO_NOT_SET_PRIORITY); EmailSender::Format format(EmailSender::PLAIN_TEXT); std::string sender, reply_to, recipients, cc_recipients, bcc_recipients, subject, message_body, priority_as_string, format_as_string; bool expand_newline_escapes; ParseCommandLine(++argv, &sender, &reply_to, &recipients, &cc_recipients, &bcc_recipients, &subject, &message_body, &priority_as_string, &format_as_string, &expand_newline_escapes); if (sender.empty() and reply_to.empty()) { IniFile ini_file("/usr/local/var/lib/tuelib/cronjobs/smtp_server.conf"); sender = ini_file.getString("SMTPServer", "server_user") + "@uni-tuebingen.de"; } if (not priority_as_string.empty()) priority = StringToPriority(priority_as_string); if (not format_as_string.empty()) format = StringToFormat(format_as_string); if (expand_newline_escapes) message_body = ExpandNewlineEscapes(message_body); if (not EmailSender::SendEmail(sender, SplitRecipients(recipients), SplitRecipients(cc_recipients), SplitRecipients(bcc_recipients), subject, message_body, priority, format, reply_to)) { if (not MiscUtil::EnvironmentVariableExists("ENABLE_SMPT_CLIENT_PERFORM_LOGGING")) LOG_ERROR("failed to send your email! (You may want to set the ENABLE_SMPT_CLIENT_PERFORM_LOGGING to debug the problem.)"); else LOG_ERROR("failed to send your email!"); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "iostream" #include "stdlib.h" #include "GL/freeglut.h" #include "GL/gl.h" using namespace std; int play=0; // game's pause and play state int windowWidth=900,windowHeight=600; float x=410,y=60; // (x,y) are the mid point of square //float xtest=0,ytest=121,speedtest=0.4; int attach=0; // wheather to attach user with box or not float dx=0.0; // distance between player and inside box float xtest[8]={0,850,20,0,13,857,100,800}; //float xtest[8]={200,200,200,200,200,200,200,200s}; float ytest[8]={121,171,221,271,327,377,427,477}; //float speedtest[8]={0.4,-0.3,0.45,0,0.42,-0.52,0.47,-0.56}; //float speedtest[8]={0.3,-0.23,.130,-0,0.33,-0.43,0.33,-0.13}; float speedtest[8]={0.5,-0.03,.130,-0,0.23,-0.29,0.33,-0.13}; //float width[8]={120,130,140,windowWidth,150,127,127,120}; float width[8]={170,170,170,windowWidth,170,177,167,160}; int attachedbox=-1; //--------for second player--------- float x1=450,y1=60; // 2nd player int attach1=0; float dx1=0.0; int attachedbox1=-1; void init(void) { glClearColor(0.0,0.0,0.0,0.0); // rgb color to clean with glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0f,windowWidth,0.0f,windowHeight,0.0f,1.0f); } void display(void) { glClear(GL_COLOR_BUFFER_BIT); // clear color buffer glColor3f(1.0,1.0,1.0); // BASIC LINES --WHITE glBegin(GL_LINES); for(int a=121;a<=600;a+=50) { glVertex3i(0,a,0); glVertex3i(900,a,0); } glEnd(); //BOXES //if(play) { glBegin(GL_QUADS); { for(int j=0;j<8;j++) //All Boxes { glVertex3f(xtest[j],ytest[j]-25,0); glVertex3f(xtest[j]+width[j],ytest[j]-25,0); glVertex3f(xtest[j]+width[j],ytest[j]+25,0); glVertex3f(xtest[j],ytest[j]+25,0); } glColor3f(0.30,0.70,0.30); glVertex3f(0,101,0); // bottom area glVertex3f(windowWidth,101,0); glVertex3f(windowWidth,0,0); glVertex3f(0,0,0); glColor3f(0.10,0.80,0.50); glVertex3f(0,246,0); // middle area glVertex3f(windowWidth,246,0); glVertex3f(windowWidth,306,0); glVertex3f(0,306,0); glColor3f(0.10,0.90,0.20); glVertex3f(0,502,0); // top area glVertex3f(windowWidth,502,0); glVertex3f(windowWidth,windowHeight,0); glVertex3f(0,windowHeight,0); glColor3f(1.0,1.0,1.0); } glEnd(); } int xtemp=x; if(attach==1) { x=xtest[attachedbox]+dx; //cout<<"xtest "<<xtest<<" x"<<x<<"\n"; } //2player int xtemp1=x1; if(attach1==1) { x1=xtest[attachedbox1]+dx1; } //PLAYER1 BOX -- ORANGE wasd glColor3f(0.53,0.224,0.100); // set color glBegin(GL_POLYGON); glVertex3f(x-15,y-15,0); glVertex3f(x+15,y-15,0); glVertex3f(x+15,y+15,0); glVertex3f(x-15,y+15,0); glEnd(); //PLAYER2 BOX -- YELLOW ijkl glColor3f(0,.5,1.0); // set color glBegin(GL_POLYGON); glVertex3f(x1-15,y1-15,0); glVertex3f(x1+15,y1-15,0); glVertex3f(x1+15,y1+15,0); glVertex3f(x1-15,y1+15,0); glEnd(); //x=xtemp; glFlush(); // forces drawing to complete } void reshape(int w, int h) { windowHeight=h; windowWidth=w; glViewport(0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0,(GLdouble)w,0.0,(GLdouble)h,0.0,1.0); } void againDisplay() { for(int j=0;j<8;j++) { xtest[j]=xtest[j]+speedtest[j]; } // making boxes continues ones for(int j=0;j<8;j++) { if(xtest[j]>900) {xtest[j]=0;} else if(xtest[j]<0) {xtest[j]=900;} } //Game over conditions if((y>121-25 && y<246) || (y>306 && y<502)) { if(attach==0) { cout<<"Game Over Player1\n"; x=410,y=60; } } if((y>=246)&&(y<=306)||(y>802)) // middle area is safe zone { attach=1; } //Game over conditions for player2 if((y1>121-25 && y1<246) || (y1>306 && y1<502)) { if(attach1==0) { cout<<"Game Over Player2\n"; x1=450,y1=60; } } if((y1>=246)&&(y1<=306)||(y1>802)) // middle area is safe zone { attach1=1; } glutPostRedisplay(); } //For keyboard, p for pause // 112 for 'p' and 32 for 'space' void key(unsigned char key,int xm,int ym) { //cout<<"KEY.... "; if(key==97) {x=x-9; } else if(key==119) {y=y+9;} else if(key==100) {x=x+9; } else if(key==115) {y=y-9; } else if(key==112) // Game pause and play using key 'p' { cout<<"Game Starts"; if(play==0) {play=1; glutIdleFunc(againDisplay); if(y>=560 || y1>=560 ){x=410; y=60; x1=450; y1=60;} } else {play=0; glutIdleFunc(NULL);} // In pause also players can move } //for player2 if(key==106) {x1=x1-9; } else if(key==105) {y1=y1+9;} else if(key==108) {x1=x1+9; } else if(key==107) {y1=y1-9; } /*else if(key==112) // Game pause and play using key 'p' { cout<<"Game Starts"; if(play==0) {play=1; glutIdleFunc(againDisplay); if(x>=560){x=450; y=60;} } else {play=0; glutIdleFunc(NULL);} // In pause also players can move }*/ int flag=0; for(int j=0;j<8;j++) { // that's the best place to make this... if ((y>=ytest[j]-25 && y<=ytest[j]+25 )&&( xtest[j]<=x && xtest[j]+width[j]>=x)) { dx=x-xtest[j]; if(dx<0) dx=-dx; cout<<"attach=1\n"; attach=1; flag=1; attachedbox=j; cout<<"Player1 is on "<<j<<" - box. and attachedbox is "<<attachedbox<<"\n"; break; }else {cout<<"y "<<y<<" ytest "<<ytest[j]<<" j "<<j<<"\n";} } if(flag==0) {attach=0; cout<<"x: "<<x<<" y: "<<y<<" and Attach1=0\n";} // for player2 int flag1=0; for(int j=0;j<8;j++) { // that's the best place to make this... if ((y1>=ytest[j]-25 && y1<=ytest[j]+25 )&&( xtest[j]<=x1 && xtest[j]+width[j]>=x1)) { dx1=x1-xtest[j]; if(dx1<0) dx1=-dx1; cout<<"attach1=1\n"; attach1=1; flag1=1; attachedbox1=j; cout<<"Player2 is on "<<j<<" - box. and attachedbox is "<<attachedbox<<"\n"; break; }else {cout<<"y1 "<<y1<<" ytest "<<ytest[j]<<" j "<<j<<"\n";} } if(flag1==0) {attach1=0; cout<<"x1: "<<x1<<" y1: "<<y1<<" and Attach1=0\n";} //Game win condition if(y>=560) { cout<<"PLAYER1 WON\n"; play=0; glutIdleFunc(NULL); } if(y1>=560) { cout<<"PLAYER2 WON\n"; play=0; glutIdleFunc(NULL); } } int main(int argc,char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(windowWidth,windowHeight); glutInitWindowPosition(40,20); glutCreateWindow("CrossJump"); init(); cout<<"CrossJump starts\n"; glutReshapeFunc(reshape); // when window is resized redraw the shape with same coordinates. glutDisplayFunc(display); //glutMouseFunc(mouse); glutKeyboardFunc(key); glutMainLoop(); return 0; } <commit_msg>Recolor and other small changes<commit_after>#include "iostream" #include "stdlib.h" #include "GL/freeglut.h" #include "GL/gl.h" using namespace std; int play=0; // game's pause and play state int windowWidth=900,windowHeight=600; float x=410,y=60; // (x,y) are the mid point of square //float xtest=0,ytest=121,speedtest=0.4; int attach=0; // wheather to attach user with box or not float dx=0.0; // distance between player and inside box float xtest[8]={0,850,20,0,13,857,100,800}; //float xtest[8]={200,200,200,200,200,200,200,200s}; float ytest[8]={121,171,221,271,327,377,427,477}; //float speedtest[8]={0.4,-0.3,0.45,0,0.42,-0.52,0.47,-0.56}; //float speedtest[8]={0.3,-0.23,.130,-0,0.33,-0.43,0.33,-0.13}; float speedtest[8]={0.45,-0.13,.630,-0,0.76,-0.29,0.83,-0.73}; //float width[8]={120,130,140,windowWidth,150,127,127,120}; float width[8]={170,170,170,windowWidth,170,177,167,160}; int attachedbox=-1; //--------for second player--------- float x1=450,y1=60; // 2nd player int attach1=0; float dx1=0.0; int attachedbox1=-1; void init(void) { glClearColor(0.0,0.0,0.0,0.0); // rgb color to clean with glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0f,windowWidth,0.0f,windowHeight,0.0f,1.0f); } void display(void) { glClear(GL_COLOR_BUFFER_BIT); // clear color buffer glColor3f(1.0,1.0,1.0); // BASIC LINES --WHITE glBegin(GL_LINES); for(int a=121;a<=600;a+=50) { glVertex3i(0,a,0); glVertex3i(900,a,0); } glEnd(); //BOXES //if(play) { glBegin(GL_QUADS); { for(int j=0;j<8;j++) //All Boxes { glVertex3f(xtest[j],ytest[j]-25,0); glVertex3f(xtest[j]+width[j],ytest[j]-25,0); glVertex3f(xtest[j]+width[j],ytest[j]+25,0); glVertex3f(xtest[j],ytest[j]+25,0); } glColor3f(0.30,0.70,0.30); glVertex3f(0,101,0); // bottom area glVertex3f(windowWidth,101,0); glVertex3f(windowWidth,0,0); glVertex3f(0,0,0); glColor3f(0.10,0.80,0.50); glVertex3f(0,246,0); // middle area glVertex3f(windowWidth,246,0); glVertex3f(windowWidth,306,0); glVertex3f(0,306,0); glColor3f(0.10,0.90,0.20); glVertex3f(0,502,0); // top area glVertex3f(windowWidth,502,0); glVertex3f(windowWidth,windowHeight,0); glVertex3f(0,windowHeight,0); glColor3f(1.0,1.0,1.0); } glEnd(); } int xtemp=x; if(attach==1) { x=xtest[attachedbox]+dx; //cout<<"xtest "<<xtest<<" x"<<x<<"\n"; } //2player int xtemp1=x1; if(attach1==1) { x1=xtest[attachedbox1]+dx1; } //PLAYER1 BOX -- ORANGE wasd glColor3f(0.83,0.224,0.100); // set color glBegin(GL_POLYGON); glVertex3f(x-15,y-15,0); glVertex3f(x+15,y-15,0); glVertex3f(x+15,y+15,0); glVertex3f(x-15,y+15,0); glEnd(); //PLAYER2 BOX -- YELLOW ijkl glColor3f(0.1,.324,0.9); // set color glBegin(GL_POLYGON); glVertex3f(x1-15,y1-15,0); glVertex3f(x1+15,y1-15,0); glVertex3f(x1+15,y1+15,0); glVertex3f(x1-15,y1+15,0); glEnd(); glColor3f(1.0,1.0,0.2); //glLineStipple(1, 0x3F07); //glEnable(GL_LINE_STIPPLE); glBegin(GL_LINES); glVertex3f(0,560,0); glVertex3f(windowWidth,560,0); glEnd(); //x=xtemp; glFlush(); // forces drawing to complete } void reshape(int w, int h) { windowHeight=h; windowWidth=w; glViewport(0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0,(GLdouble)w,0.0,(GLdouble)h,0.0,1.0); } void againDisplay() { for(int j=0;j<8;j++) { xtest[j]=xtest[j]+speedtest[j]; } // making boxes continues ones for(int j=0;j<8;j++) { if(xtest[j]>900) {xtest[j]=0;} else if(xtest[j]<0) {xtest[j]=900;} } //Game over conditions if((y>121-25 && y<246) || (y>306 && y<502)) { if(attach==0) { cout<<"Game Over Player1\n"; x=410,y=60; } } if((y>=246)&&(y<=306)||(y>802)) // middle area is safe zone { attach=1; } //Game over conditions for player2 if((y1>121-25 && y1<246) || (y1>306 && y1<502)) { if(attach1==0) { cout<<"Game Over Player2\n"; x1=450,y1=60; } } if((y1>=246)&&(y1<=306)||(y1>802)) // middle area is safe zone { attach1=1; } glutPostRedisplay(); } //For keyboard, p for pause // 112 for 'p' and 32 for 'space' void key(unsigned char key,int xm,int ym) { //cout<<"KEY.... "; if(key==97) {x=x-9; } else if(key==119) {y=y+9;} else if(key==100) {x=x+9; } else if(key==115) {y=y-9; } else if(key==112) // Game pause and play using key 'p' { cout<<"Game Starts"; if(play==0) {play=1; glutIdleFunc(againDisplay); if(y>=560 || y1>=560 ){x=410; y=60; x1=450; y1=60;} } else {play=0; glutIdleFunc(NULL);} // In pause also players can move } //for player2 if(key==106) {x1=x1-9; } else if(key==105) {y1=y1+9;} else if(key==108) {x1=x1+9; } else if(key==107) {y1=y1-9; } /*else if(key==112) // Game pause and play using key 'p' { cout<<"Game Starts"; if(play==0) {play=1; glutIdleFunc(againDisplay); if(x>=560){x=450; y=60;} } else {play=0; glutIdleFunc(NULL);} // In pause also players can move }*/ int flag=0; for(int j=0;j<8;j++) { // that's the best place to make this... if ((y>=ytest[j]-25 && y<=ytest[j]+25 )&&( xtest[j]<=x && xtest[j]+width[j]>=x)) { dx=x-xtest[j]; if(dx<0) dx=-dx; cout<<"attach=1\n"; attach=1; flag=1; attachedbox=j; cout<<"Player1 is on "<<j<<" - box. and attachedbox is "<<attachedbox<<"\n"; break; }else {cout<<"y "<<y<<" ytest "<<ytest[j]<<" j "<<j<<"\n";} } if(flag==0) {attach=0; cout<<"x: "<<x<<" y: "<<y<<" and Attach1=0\n";} // for player2 int flag1=0; for(int j=0;j<8;j++) { // that's the best place to make this... if ((y1>=ytest[j]-25 && y1<=ytest[j]+25 )&&( xtest[j]<=x1 && xtest[j]+width[j]>=x1)) { dx1=x1-xtest[j]; if(dx1<0) dx1=-dx1; cout<<"attach1=1\n"; attach1=1; flag1=1; attachedbox1=j; cout<<"Player2 is on "<<j<<" - box. and attachedbox is "<<attachedbox<<"\n"; break; }else {cout<<"y1 "<<y1<<" ytest "<<ytest[j]<<" j "<<j<<"\n";} } if(flag1==0) {attach1=0; cout<<"x1: "<<x1<<" y1: "<<y1<<" and Attach1=0\n";} //Game win condition if(y>=560) { cout<<"PLAYER1 WON\n"; play=0; glutIdleFunc(NULL); } if(y1>=560) { cout<<"PLAYER2 WON\n"; play=0; glutIdleFunc(NULL); } } int main(int argc,char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(windowWidth,windowHeight); glutInitWindowPosition(40,20); glutCreateWindow("CrossJump"); init(); cout<<"CrossJump starts\n"; glutReshapeFunc(reshape); // when window is resized redraw the shape with same coordinates. glutDisplayFunc(display); //glutMouseFunc(mouse); glutKeyboardFunc(key); glutMainLoop(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) <2002-2006> <Jean-Philippe Barrette-LaPierre> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files * (cURLpp), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef CURLPP_HPP #define CURLPP_HPP #define LIBCURLPP_VERSION "0.7.0-pre1" #define LIBCURLPP_VERSION_NUM 0x000700 #include <string> #include <curl/curl.h> #include "dllfct.h" namespace cURLpp { /** * This function takes care of initializing cURLpp ( also libcURL). If you want * to cleanup cURL before your application quits just call cURLpp::terminate(). * This function should only be called once (no matter how many threads or * libcurl sessions that'll be used) by every application that uses libcurl, * it will throw a logic_error if you call it twice. * * The flags option is a bit pattern that tells libcurl exact what features * to init, as described below. Set the desired bits by ORing the values together. * * CURL_GLOBAL_ALL * Initialize everything possible. This sets all known bits. * * CURL_GLOBAL_SSL * Initialize SSL * * CURL_GLOBAL_WIN32 * Initialize the Win32 socket libraries. * * CURL_GLOBAL_NOTHING * Initialise nothing extra. This sets no bit. * * NOTE: you cannot call this function twice without first terminating it first. * it will throw a logic_error if you do this. */ void CURLPPAPI initialize(long flags = CURL_GLOBAL_ALL); /** * This function takes care of cleaning up cURLpp ( also libcURL). See * cURLpp::initialize( long flags ) for momre documentation. * * NOTE: you cannot call this function if cURLpp is not loaded. it will throw a * logic_error if you do this. */ void CURLPPAPI terminate(); /** * This class takes care of initialization and cleaning up cURLpp ( also libcURL ) * (it will call cURLpp:terminate() in his destructor). If you want to be sure that * cURLpp is cleanup after you reached the end of scope of a specific function using * cURLpp, instatiate this class. This function call cURLpp::initialize() in his * constructor, so you don't have to call it by yourself, when you have decided to * use it. * * See cURLpp::initialize( long flags ) and cURLpp:terminate() for more documentation. */ class CURLPPAPI Cleanup { public: Cleanup(); ~Cleanup(); }; /** * This function will convert the given input string to an URL encoded * string and return that as a new allocated string. All input characters * that are not a-z, A-Z or 0-9 will be converted to their "URL escaped" * version (%NN where NN is a two-digit hexadecimal number). */ std::string CURLPPAPI escape( const std::string& url ); /** * This function will convert the given URL encoded input string to a * "plain string" and return that as a new allocated string. All input * characters that are URL encoded (%XX) where XX is a two-digit * hexadecimal number, or +) will be converted to their plain text versions * (up to a ? letter, no + letters to the right of a ? letter will be * converted). */ std::string CURLPPAPI unescape( const std::string &url ); /** * this is a portable wrapper for the getenv() function, meant to emulate * its behaviour and provide an identical interface for all operating * systems libcurl builds on (including win32). Under unix operating * systems, there isn't any point in returning an allocated memory, * although other systems won't work properly if this isn't done. The unix * implementation thus have to suffer slightly from the drawbacks of other * systems. */ std::string CURLPPAPI getenv( const std::string &name ); /** * Returns a human readable string with the version number of libcurl and * some of its important components (like OpenSSL version). * * Note: this returns the actual running lib's version, you might have * installed a newer lib's include files in your system which may turn * your LIBCURL_VERSION #define value to differ from this result. */ std::string CURLPPAPI libcurlVersion(); /** * This function returns the number of seconds since January 1st 1970, * for the date and time that the datestring parameter specifies. The now * parameter is there and should hold the current time to allow the * datestring to specify relative dates/times. Read further in the date * string parser section below. * * PARSING DATES AND TIMES * A "date" is a string, possibly empty, containing many items separated * by whitespace. The whitespace may be omitted when no ambiguity * arises. The empty string means the beginning of today (i.e., midnight). * Order of the items is immaterial. A date string may contain many * flavors of items: * * calendar date items * This can be specified in a number of different ways. Including * 1970-09-17, 70-9-17, 70-09-17, 9/17/72, 24 September 1972, 24 Sept 72, * 24 Sep 72, Sep 24, 1972, 24-sep-72, 24sep72. The year can also be * omitted, for example: 9/17 or "sep 17". * * time of the day items * This string specifies the time on a given day. Syntax supported * includes: 18:19:0, 18:19, 6:19pm, 18:19-0500 (for specifying the time * zone as well). * * time zone items * Specifies international time zone. There are a few acronyms * supported, but in general you should instead use the specific * realtive time compared to UTC. Supported formats include: -1200, MST, * +0100. * * day of the week items * Specifies a day of the week. If this is mentioned alone it means that * day of the week in the future. Days of the week may be spelled out in * full: `Sunday', `Monday', etc or they may be abbreviated to their * first three letters, optionally followed by a period. The special * abbreviations `Tues' for `Tuesday', `Wednes' for `Wednesday' and `Thur' * or `Thurs' for `Thursday' are also allowed. A number may precede a day * of the week item to move forward supplementary weeks. It is best * used in expression like `third monday'. In this context, `last DAY' * or `next DAY' is also acceptable; they move one week before or after * the day that DAY by itself would represent. * * relative items * A relative item adjusts a date (or the current date if none) forward * or backward. Example syntax includes: "1 year", "1 year ago", * "2 days", "4 weeks". The string `tomorrow' is worth one day in the * future (equivalent to `day'), the string `yesterday' is worth one * day in the past (equivalent to `day ago'). * * pure numbers * If the decimal number is of the form YYYYMMDD and no other calendar date * item appears before it in the date string, then YYYY is read as * the year, MM as the month number and DD as the day of the month, for the * specified calendar date. */ time_t CURLPPAPI getdate( const std::string&date, time_t *now = 0 ); } #endif <commit_msg>Started the 0.7.1 development<commit_after>/* * Copyright (c) <2002-2006> <Jean-Philippe Barrette-LaPierre> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files * (cURLpp), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef CURLPP_HPP #define CURLPP_HPP #define LIBCURLPP_VERSION "0.7.1-devel" #define LIBCURLPP_VERSION_NUM 0x000700 #include <string> #include <curl/curl.h> #include "dllfct.h" namespace cURLpp { /** * This function takes care of initializing cURLpp ( also libcURL). If you want * to cleanup cURL before your application quits just call cURLpp::terminate(). * This function should only be called once (no matter how many threads or * libcurl sessions that'll be used) by every application that uses libcurl, * it will throw a logic_error if you call it twice. * * The flags option is a bit pattern that tells libcurl exact what features * to init, as described below. Set the desired bits by ORing the values together. * * CURL_GLOBAL_ALL * Initialize everything possible. This sets all known bits. * * CURL_GLOBAL_SSL * Initialize SSL * * CURL_GLOBAL_WIN32 * Initialize the Win32 socket libraries. * * CURL_GLOBAL_NOTHING * Initialise nothing extra. This sets no bit. * * NOTE: you cannot call this function twice without first terminating it first. * it will throw a logic_error if you do this. */ void CURLPPAPI initialize(long flags = CURL_GLOBAL_ALL); /** * This function takes care of cleaning up cURLpp ( also libcURL). See * cURLpp::initialize( long flags ) for momre documentation. * * NOTE: you cannot call this function if cURLpp is not loaded. it will throw a * logic_error if you do this. */ void CURLPPAPI terminate(); /** * This class takes care of initialization and cleaning up cURLpp ( also libcURL ) * (it will call cURLpp:terminate() in his destructor). If you want to be sure that * cURLpp is cleanup after you reached the end of scope of a specific function using * cURLpp, instatiate this class. This function call cURLpp::initialize() in his * constructor, so you don't have to call it by yourself, when you have decided to * use it. * * See cURLpp::initialize( long flags ) and cURLpp:terminate() for more documentation. */ class CURLPPAPI Cleanup { public: Cleanup(); ~Cleanup(); }; /** * This function will convert the given input string to an URL encoded * string and return that as a new allocated string. All input characters * that are not a-z, A-Z or 0-9 will be converted to their "URL escaped" * version (%NN where NN is a two-digit hexadecimal number). */ std::string CURLPPAPI escape( const std::string& url ); /** * This function will convert the given URL encoded input string to a * "plain string" and return that as a new allocated string. All input * characters that are URL encoded (%XX) where XX is a two-digit * hexadecimal number, or +) will be converted to their plain text versions * (up to a ? letter, no + letters to the right of a ? letter will be * converted). */ std::string CURLPPAPI unescape( const std::string &url ); /** * this is a portable wrapper for the getenv() function, meant to emulate * its behaviour and provide an identical interface for all operating * systems libcurl builds on (including win32). Under unix operating * systems, there isn't any point in returning an allocated memory, * although other systems won't work properly if this isn't done. The unix * implementation thus have to suffer slightly from the drawbacks of other * systems. */ std::string CURLPPAPI getenv( const std::string &name ); /** * Returns a human readable string with the version number of libcurl and * some of its important components (like OpenSSL version). * * Note: this returns the actual running lib's version, you might have * installed a newer lib's include files in your system which may turn * your LIBCURL_VERSION #define value to differ from this result. */ std::string CURLPPAPI libcurlVersion(); /** * This function returns the number of seconds since January 1st 1970, * for the date and time that the datestring parameter specifies. The now * parameter is there and should hold the current time to allow the * datestring to specify relative dates/times. Read further in the date * string parser section below. * * PARSING DATES AND TIMES * A "date" is a string, possibly empty, containing many items separated * by whitespace. The whitespace may be omitted when no ambiguity * arises. The empty string means the beginning of today (i.e., midnight). * Order of the items is immaterial. A date string may contain many * flavors of items: * * calendar date items * This can be specified in a number of different ways. Including * 1970-09-17, 70-9-17, 70-09-17, 9/17/72, 24 September 1972, 24 Sept 72, * 24 Sep 72, Sep 24, 1972, 24-sep-72, 24sep72. The year can also be * omitted, for example: 9/17 or "sep 17". * * time of the day items * This string specifies the time on a given day. Syntax supported * includes: 18:19:0, 18:19, 6:19pm, 18:19-0500 (for specifying the time * zone as well). * * time zone items * Specifies international time zone. There are a few acronyms * supported, but in general you should instead use the specific * realtive time compared to UTC. Supported formats include: -1200, MST, * +0100. * * day of the week items * Specifies a day of the week. If this is mentioned alone it means that * day of the week in the future. Days of the week may be spelled out in * full: `Sunday', `Monday', etc or they may be abbreviated to their * first three letters, optionally followed by a period. The special * abbreviations `Tues' for `Tuesday', `Wednes' for `Wednesday' and `Thur' * or `Thurs' for `Thursday' are also allowed. A number may precede a day * of the week item to move forward supplementary weeks. It is best * used in expression like `third monday'. In this context, `last DAY' * or `next DAY' is also acceptable; they move one week before or after * the day that DAY by itself would represent. * * relative items * A relative item adjusts a date (or the current date if none) forward * or backward. Example syntax includes: "1 year", "1 year ago", * "2 days", "4 weeks". The string `tomorrow' is worth one day in the * future (equivalent to `day'), the string `yesterday' is worth one * day in the past (equivalent to `day ago'). * * pure numbers * If the decimal number is of the form YYYYMMDD and no other calendar date * item appears before it in the date string, then YYYY is read as * the year, MM as the month number and DD as the day of the month, for the * specified calendar date. */ time_t CURLPPAPI getdate( const std::string&date, time_t *now = 0 ); } #endif <|endoftext|>
<commit_before>/*********************************************************************/ /** setvisu.cpp: initialisations de l'ecran d'affichage du composant **/ /*********************************************************************/ #include "fctsys.h" #include "common.h" #include "class_drawpanel.h" #include "id.h" #include "bitmaps.h" #include "cvpcb.h" #include "protos.h" #include "cvstruct.h" /* * NOTE: There is something in 3d_viewer.h that causes a compiler error in * <boost/foreach.hpp> in Linux so move it after cvpcb.h where it is * included to prevent the error from occuring. */ #include "3d_viewer.h" /* * Create or Update the frame showing the current highlighted footprint * and (if showed) the 3D display frame */ void WinEDA_CvpcbFrame::CreateScreenCmp() { wxString msg, FootprintName; bool IsNew = FALSE; FootprintName = m_FootprintList->GetSelectedFootprint(); if( DrawFrame == NULL ) { DrawFrame = new WinEDA_DisplayFrame( this, _( "Module" ), wxPoint( 0, 0 ), wxSize( 600, 400 ), KICAD_DEFAULT_DRAWFRAME_STYLE | wxFRAME_FLOAT_ON_PARENT ); IsNew = TRUE; DrawFrame->Show( TRUE ); } if( !FootprintName.IsEmpty() ) { msg = _( "Footprint: " ) + FootprintName; DrawFrame->SetTitle( msg ); FOOTPRINT* Module = GetModuleDescrByName( FootprintName, m_footprints ); msg = _( "Lib: " ); if( Module ) msg += Module->m_LibName; else msg += wxT( "???" ); DrawFrame->SetStatusText( msg, 0 ); if( DrawFrame->GetBoard()->m_Modules.GetCount() ) { // there is only one module in the list DrawFrame->GetBoard()->m_Modules.DeleteAll(); } MODULE* mod = DrawFrame->Get_Module( FootprintName ); if( mod ) DrawFrame->GetBoard()->m_Modules.PushBack( mod ); DrawFrame->Zoom_Automatique( FALSE ); DrawFrame->UpdateStatusBar(); /* Display new cursor coordinates and zoom value */ if( DrawFrame->m_Draw3DFrame ) DrawFrame->m_Draw3DFrame->NewDisplay(); } else if( !IsNew ) { DrawFrame->Refresh(); if( DrawFrame->m_Draw3DFrame ) DrawFrame->m_Draw3DFrame->NewDisplay(); } } /* * Draws the current highlighted footprint. */ void WinEDA_DisplayFrame::RedrawActiveWindow( wxDC* DC, bool EraseBg ) { if( !GetBoard() ) return; ActiveScreen = (PCB_SCREEN*) GetScreen(); if( EraseBg ) DrawPanel->EraseScreen( DC ); DrawPanel->DrawBackGround( DC ); GetBoard()->Draw( DrawPanel, DC, GR_COPY ); MODULE* Module = GetBoard()->m_Modules; if ( Module ) Module->DisplayInfo( this ); DrawPanel->Trace_Curseur( DC ); } /* * Redraw the BOARD items but not cursors, axis or grid. */ void BOARD::Draw( WinEDA_DrawPanel* aPanel, wxDC* DC, int aDrawMode, const wxPoint& offset ) { if( m_Modules ) { m_Modules->Draw( aPanel, DC, GR_COPY ); } } <commit_msg>fixed: refresh problem in display footprint window<commit_after>/*********************************************************************/ /** setvisu.cpp: initialisations de l'ecran d'affichage du composant **/ /*********************************************************************/ #include "fctsys.h" #include "common.h" #include "class_drawpanel.h" #include "id.h" #include "bitmaps.h" #include "cvpcb.h" #include "protos.h" #include "cvstruct.h" /* * NOTE: There is something in 3d_viewer.h that causes a compiler error in * <boost/foreach.hpp> in Linux so move it after cvpcb.h where it is * included to prevent the error from occuring. */ #include "3d_viewer.h" /* * Create or Update the frame showing the current highlighted footprint * and (if showed) the 3D display frame */ void WinEDA_CvpcbFrame::CreateScreenCmp() { wxString msg, FootprintName; bool IsNew = FALSE; FootprintName = m_FootprintList->GetSelectedFootprint(); if( DrawFrame == NULL ) { DrawFrame = new WinEDA_DisplayFrame( this, _( "Module" ), wxPoint( 0, 0 ), wxSize( 600, 400 ), KICAD_DEFAULT_DRAWFRAME_STYLE | wxFRAME_FLOAT_ON_PARENT ); IsNew = TRUE; DrawFrame->Show( TRUE ); } if( !FootprintName.IsEmpty() ) { msg = _( "Footprint: " ) + FootprintName; DrawFrame->SetTitle( msg ); FOOTPRINT* Module = GetModuleDescrByName( FootprintName, m_footprints ); msg = _( "Lib: " ); if( Module ) msg += Module->m_LibName; else msg += wxT( "???" ); DrawFrame->SetStatusText( msg, 0 ); if( DrawFrame->GetBoard()->m_Modules.GetCount() ) { // there is only one module in the list DrawFrame->GetBoard()->m_Modules.DeleteAll(); } MODULE* mod = DrawFrame->Get_Module( FootprintName ); if( mod ) DrawFrame->GetBoard()->m_Modules.PushBack( mod ); DrawFrame->Zoom_Automatique( FALSE ); DrawFrame->DrawPanel->Refresh(); DrawFrame->UpdateStatusBar(); /* Display new cursor coordinates and zoom value */ if( DrawFrame->m_Draw3DFrame ) DrawFrame->m_Draw3DFrame->NewDisplay(); } else if( !IsNew ) { DrawFrame->Refresh(); if( DrawFrame->m_Draw3DFrame ) DrawFrame->m_Draw3DFrame->NewDisplay(); } } /* * Draws the current highlighted footprint. */ void WinEDA_DisplayFrame::RedrawActiveWindow( wxDC* DC, bool EraseBg ) { if( !GetBoard() ) return; ActiveScreen = (PCB_SCREEN*) GetScreen(); if( EraseBg ) DrawPanel->EraseScreen( DC ); DrawPanel->DrawBackGround( DC ); GetBoard()->Draw( DrawPanel, DC, GR_COPY ); MODULE* Module = GetBoard()->m_Modules; if ( Module ) Module->DisplayInfo( this ); DrawPanel->Trace_Curseur( DC ); } /* * Redraw the BOARD items but not cursors, axis or grid. */ void BOARD::Draw( WinEDA_DrawPanel* aPanel, wxDC* DC, int aDrawMode, const wxPoint& offset ) { if( m_Modules ) { m_Modules->Draw( aPanel, DC, GR_COPY ); } } <|endoftext|>
<commit_before><commit_msg>Fix typo<commit_after><|endoftext|>
<commit_before>/* You can use one of the both BSD 3-Clause License or GNU Lesser General Public License 3.0 for this source. */ /* BSD 3-Clause License: * Copyright (c) 2013 - 2021, kazunobu watatsu. * 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 or other materials provided with the distribution. * Neither the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if !defined(_LINEAR_OPT_) using std::cerr; using std::flush; template <typename T> SimpleVector<T> inner(const SimpleMatrix<T>& A, const SimpleVector<T>& bl, const SimpleVector<T>& bu) { #if defined(_FLOAT_BITS_) static const auto epsilon(T(1) >> int64_t(mybits - 1)); #else static const auto epsilon(std::numeric_limits<T>::epsilon()); #endif assert(A.rows() == bl.size() && A.rows() == bu.size() && 0 < A.cols() && 0 < A.rows()); // cout << A << endl << b << endl << c.transpose() << endl; cerr << " (" << A.rows() << ", " << A.cols() << ")"; // bu - bb == A, bl - bb == - A <=> bu - bl == 2 A const auto bb(bu - (bu - bl) / T(2)); const auto upper(bu - bb); SimpleMatrix<T> AA(A.rows() * 2 - 1, A.cols() + 1); SimpleVector<T> one(AA.rows()); std::vector<std::pair<T, int> > fidx; fidx.reserve(A.rows()); for(int i = 0; i < A.rows(); i ++) { for(int j = 0; j < A.cols(); j ++) AA(i, j) = A(i, j); AA(i, A.cols()) = - bb[i]; if(upper[i] == T(0)) { const auto n2(AA.row(i).dot(AA.row(i))); if(n2 != T(0)) { fidx.emplace_back(std::make_pair(- T(1), i)); AA.row(i) /= sqrt(n2); } } else { AA.row(i) /= upper[i]; AA(i, A.cols()) -= T(1); } one[i] = T(1); assert(isfinite(AA.row(i).dot(AA.row(i)))); if(A.rows() - 1 <= i) break; AA.row(i + A.rows()) = - AA.row(i); one[i + A.rows()] = T(1); } SimpleMatrix<T> Pt(AA.cols(), AA.rows()); for(int i = 0; i < Pt.rows(); i ++) for(int j = 0; j < Pt.cols(); j ++) Pt(i, j) = T(0); std::vector<int> residue; for(int i = 0; i < AA.cols(); i ++) { const auto Atrowi(AA.col(i)); const auto work(Atrowi - Pt.projectionPt(Atrowi)); const auto n2(work.dot(work)); if(n2 <= epsilon) { residue.emplace_back(i); continue; } Pt.row(i) = work / sqrt(n2); } int ii(0); for(int j = 0; j < Pt.cols() && ii < residue.size(); j ++) { SimpleVector<T> ek(Pt.cols()); for(int k = 0; k < Pt.cols(); k ++) ek[k] = j == k ? T(1) : T(0); ek -= Pt.projectionPt(ek); const auto n2(ek.dot(ek)); if(n2 <= epsilon) continue; Pt.row(residue[ii ++]) = ek / sqrt(n2); } assert(residue.size() <= ii); cerr << "Q" << flush; const auto R(Pt * AA); const auto done(R.solve(Pt * one)); cerr << "R" << flush; const auto on(Pt.projectionPt(one)); fidx.reserve(fidx.size() + on.size()); for(int i = 0; i < on.size(); i ++) fidx.emplace_back(std::make_pair(abs(on[i]), i)); std::sort(fidx.begin(), fidx.end()); // worst case O(mn^2) over all in this function, // we can make this function better case it's O(n^3) but not now. for(int n_fixed = 0, idx = 0; n_fixed < Pt.rows() - 1 && idx < fidx.size(); n_fixed ++, idx ++) { const auto& iidx(fidx[idx].second); const auto orth(Pt.col(iidx)); const auto norm2orth(orth.dot(orth)); if(norm2orth <= epsilon) { n_fixed --; continue; } #if defined(_OPENMP) #pragma omp parallel for schedule(static, 1) #endif for(int j = 0; j < Pt.cols(); j ++) Pt.setCol(j, Pt.col(j) - orth * Pt.col(j).dot(orth) / norm2orth); } cerr << "G" << flush; auto rvec(R.solve(Pt * one)); cerr << "I" << flush; SimpleVector<T> rrvec(rvec.size() - 1); // | [A, - bb == - upper] [x t] | <= epsilon 1. for(int i = 0; i < rrvec.size(); i ++) rrvec[i] = rvec[i] * done[done.size() - 1] - done[i] * rvec[rvec.size() - 1]; return rrvec; } #define _LINEAR_OPT_ #endif <commit_msg>ok konbu.hh.<commit_after>/* You can use one of the both BSD 3-Clause License or GNU Lesser General Public License 3.0 for this source. */ /* BSD 3-Clause License: * Copyright (c) 2013 - 2021, kazunobu watatsu. * 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 or other materials provided with the distribution. * Neither the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if !defined(_LINEAR_OPT_) using std::cerr; using std::flush; template <typename T> SimpleVector<T> inner(const SimpleMatrix<T>& A, const SimpleVector<T>& bl, const SimpleVector<T>& bu) { #if defined(_FLOAT_BITS_) static const auto epsilon(T(1) >> int64_t(mybits - 1)); #else static const auto epsilon(std::numeric_limits<T>::epsilon()); #endif assert(A.rows() == bl.size() && A.rows() == bu.size() && 0 < A.cols() && 0 < A.rows()); // cout << A << endl << b << endl << c.transpose() << endl; cerr << " (" << A.rows() << ", " << A.cols() << ")"; // bu - bb == A, bl - bb == - A <=> bu - bl == 2 A const auto bb(bu - (bu - bl) / T(2)); const auto upper(bu - bb); SimpleMatrix<T> AA(A.rows() * 2 - 1, A.cols() + 1); SimpleVector<T> one(AA.rows()); std::vector<std::pair<T, int> > fidx; fidx.reserve(A.rows()); for(int i = 0; i < A.rows(); i ++) { for(int j = 0; j < A.cols(); j ++) AA(i, j) = A(i, j); AA(i, A.cols()) = - bb[i]; if(upper[i] == T(0)) { const auto n2(AA.row(i).dot(AA.row(i))); if(n2 != T(0)) { fidx.emplace_back(std::make_pair(- T(1), i)); AA.row(i) /= sqrt(n2); } } else { AA.row(i) /= upper[i]; AA(i, A.cols()) -= T(1); } one[i] = T(1); assert(isfinite(AA.row(i).dot(AA.row(i)))); if(A.rows() - 1 <= i) break; AA.row(i + A.rows()) = - AA.row(i); if(fidx.size() && fidx[fidx.size() - 1].second == i) AA(i + A.rows(), A.cols()) += T(2); one[i + A.rows()] = T(1); } SimpleMatrix<T> Pt(AA.cols(), AA.rows()); for(int i = 0; i < Pt.rows(); i ++) for(int j = 0; j < Pt.cols(); j ++) Pt(i, j) = T(0); std::vector<int> residue; for(int i = 0; i < AA.cols(); i ++) { const auto Atrowi(AA.col(i)); const auto work(Atrowi - Pt.projectionPt(Atrowi)); const auto n2(work.dot(work)); if(n2 <= epsilon) { residue.emplace_back(i); continue; } Pt.row(i) = work / sqrt(n2); } int ii(0); for(int j = 0; j < Pt.cols() && ii < residue.size(); j ++) { SimpleVector<T> ek(Pt.cols()); for(int k = 0; k < Pt.cols(); k ++) ek[k] = j == k ? T(1) : T(0); ek -= Pt.projectionPt(ek); const auto n2(ek.dot(ek)); if(n2 <= epsilon) continue; Pt.row(residue[ii ++]) = ek / sqrt(n2); } assert(residue.size() <= ii); cerr << "Q" << flush; const auto R(Pt * AA); const auto done(R.solve(Pt * one)); cerr << "R" << flush; const auto on(Pt.projectionPt(one)); fidx.reserve(fidx.size() + on.size()); for(int i = 0; i < on.size(); i ++) fidx.emplace_back(std::make_pair(abs(on[i]), i)); std::sort(fidx.begin(), fidx.end()); // worst case O(mn^2) over all in this function, // we can make this function better case it's O(n^3) but not now. for(int n_fixed = 0, idx = 0; n_fixed < Pt.rows() - 1 && idx < fidx.size(); n_fixed ++, idx ++) { const auto& iidx(fidx[idx].second); const auto orth(Pt.col(iidx)); const auto norm2orth(orth.dot(orth)); if(norm2orth <= epsilon) { n_fixed --; continue; } #if defined(_OPENMP) #pragma omp parallel for schedule(static, 1) #endif for(int j = 0; j < Pt.cols(); j ++) Pt.setCol(j, Pt.col(j) - orth * Pt.col(j).dot(orth) / norm2orth); } cerr << "G" << flush; auto rvec(R.solve(Pt * one)); cerr << "I" << flush; SimpleVector<T> rrvec(rvec.size() - 1); // | [A, - bb == - upper] [x t] | <= epsilon 1. for(int i = 0; i < rrvec.size(); i ++) rrvec[i] = rvec[i] * done[done.size() - 1] / rvec[rvec.size() - 1] - done[i]; return rrvec; } #define _LINEAR_OPT_ #endif <|endoftext|>
<commit_before>#pragma once namespace principia { namespace geometry { template<typename Scalar, typename Frame> Multivector<Scalar, Frame, 1>::Multivector(R3Element<Scalar> const& coordinates) : coordinates(coordinates) {}; template<typename Scalar, typename Frame> Multivector<Scalar, Frame, 2>::Multivector(R3Element<Scalar> const& coordinates) : coordinates(coordinates) {}; template<typename Scalar, typename Frame> Multivector<Scalar, Frame, 3>::Multivector(Scalar const& coordinates) : coordinates(coordinates) {}; template<typename LeftScalar, typename RightScalar, typename Frame> inline quantities::Product<LeftScalar, RightScalar> InnerProduct( Vector<LeftScalar, Frame> const& left, Vector<RightScalar, Frame> const& right) { return Dot(left.coordinates, right.coordinates); } template<typename LeftScalar, typename RightScalar, typename Frame> inline quantities::Product<LeftScalar, RightScalar> InnerProduct( Bivector<LeftScalar, Frame> const& left, Bivector<RightScalar, Frame> const& right) { return Dot(left.coordinates, right.coordinates); } template<typename LeftScalar, typename RightScalar, typename Frame> inline quantities::Product<LeftScalar, RightScalar> InnerProduct( Trivector<LeftScalar, Frame> const& left, Trivector<RightScalar, Frame> const& right) { return left.coordinates * right.coordinates; } template<typename LeftScalar, typename RightScalar, typename Frame> inline Bivector<quantities::Product<LeftScalar, RightScalar>, Frame> Wedge(Vector<LeftScalar, Frame> const& left, Vector<RightScalar, Frame> const& right) { return Bivector<quantities::Product<LeftScalar, RightScalar>, Frame>(Cross(left.coordinates, right.coordinates)); } template<typename LeftScalar, typename RightScalar, typename Frame> inline Trivector<quantities::Product<LeftScalar, RightScalar>, Frame> Wedge(Bivector<LeftScalar, Frame> const& left, Vector<RightScalar, Frame> const& right) { return Trivector<quantities::Product<LeftScalar, RightScalar>, Frame>(Dot(left.coordinates, right.coordinates)); } template<typename LeftScalar, typename RightScalar, typename Frame> inline Trivector<quantities::Product<LeftScalar, RightScalar>, Frame> Wedge(Vector<LeftScalar, Frame> const& left, Bivector<RightScalar, Frame> const& right) { return Trivector<quantities::Product<LeftScalar, RightScalar>, Frame>(Dot(left.coordinates, right.coordinates)); } // Lie bracket on V ^ V = so(V). template<typename LeftScalar, typename RightScalar, typename Frame> inline Bivector<quantities::Product<LeftScalar, RightScalar>, Frame> Commutator(Bivector<LeftScalar, Frame> const& left, Bivector<RightScalar, Frame> const& right) { return Bivector<quantities::Product<LeftScalar, RightScalar>, Frame>(Cross(left.coordinates, right.coordinates)); } // Left action of V ^ V = so(V) on V. template<typename LeftScalar, typename RightScalar, typename Frame> inline Vector<quantities::Product<LeftScalar, RightScalar>, Frame> operator*(Bivector<LeftScalar, Frame> const& left, Vector<RightScalar, Frame> const& right) { return Vector<quantities::Product<LeftScalar, RightScalar>, Frame>(Cross(left.coordinates, right.coordinates)); } // Right action of V ^ V = so(V) on V* = V. template<typename LeftScalar, typename RightScalar, typename Frame> inline Vector<quantities::Product<LeftScalar, RightScalar>, Frame> operator*(Vector<LeftScalar, Frame> const& left, Bivector<RightScalar, Frame> const& right) { return Vector<quantities::Product<LeftScalar, RightScalar>, Frame>(Cross(left.coordinates, right.coordinates)); } template<typename Scalar, typename Frame, unsigned int Rank> inline Multivector<Scalar, Frame, Rank> operator+( Multivector<Scalar, Frame, Rank> const& right) { return Multivector<Scalar, Frame, Rank>(+right.coordinates); } template<typename Scalar, typename Frame, unsigned int Rank> inline Multivector<Scalar, Frame, Rank> operator-( Multivector<Scalar, Frame, Rank> const& right) { return Multivector<Scalar, Frame, Rank>(-right.coordinates); } template<typename Scalar, typename Frame, unsigned int Rank> inline Multivector<Scalar, Frame, Rank> operator+( Multivector<Scalar, Frame, Rank> const& left, Multivector<Scalar, Frame, Rank> const& right) { return Multivector<Scalar, Frame, Rank>(left.coordinates + right.coordinates); } template<typename Scalar, typename Frame, unsigned int Rank> inline Multivector<Scalar, Frame, Rank> operator-( Multivector<Scalar, Frame, Rank> const& left, Multivector<Scalar, Frame, Rank> const& right) { return Multivector<Scalar, Frame, Rank>(left.coordinates - right.coordinates); } template<typename Scalar, typename Frame, unsigned int Rank> inline Multivector<Scalar, Frame, Rank> operator*( quantities::Dimensionless const& left, Multivector<Scalar, Frame, Rank> const& right) { return Multivector<Scalar, Frame, Rank>(left * right.coordinates); } template<typename Scalar, typename Frame, unsigned int Rank> inline Multivector<Scalar, Frame, Rank> operator*( Multivector<Scalar, Frame, Rank> const& left, quantities::Dimensionless const& right) { return Multivector<Scalar, Frame, Rank>(left.coordinates * right); } template<typename Scalar, typename Frame, unsigned int Rank> inline Multivector<Scalar, Frame, Rank> operator/( Multivector<Scalar, Frame, Rank> const& left, quantities::Dimensionless const& right) { return Multivector<Scalar, Frame, Rank>(left.coordinates / right); } template<typename DLeft, typename RightScalar, typename Frame, unsigned int Rank> inline Multivector< quantities::Product<quantities::Quantity<DLeft>, RightScalar>, Frame, Rank> operator*(quantities::Quantity<DLeft> const& left, Multivector<RightScalar, Frame, Rank> const& right) { return Multivector< quantities::Product<quantities::Quantity<DLeft>, RightScalar>, Frame, Rank>(left * right.coordinates); } template<typename LeftScalar, typename DRight, typename Frame, unsigned int Rank> inline Multivector< quantities::Product<LeftScalar, quantities::Quantity<DRight>>, Frame, Rank> operator*(Multivector<LeftScalar, Frame, Rank> const& left, quantities::Quantity<DRight> const& right) { return Multivector< quantities::Product<LeftScalar, quantities::Quantity<DRight>>, Frame, Rank>(left.coordinates * right); } template<typename LeftScalar, typename DRight, typename Frame, unsigned int Rank> inline Multivector< quantities::Quotient<LeftScalar, quantities::Quantity<DRight>>, Frame, Rank> operator/(Multivector<LeftScalar, Frame, Rank> const& left, quantities::Quantity<DRight> const& right) { return Multivector< quantities::Quotient<LeftScalar, quantities::Quantity<DRight>>, Frame, Rank>(left.coordinates / right); } template<typename Scalar, typename Frame, unsigned int Rank> inline void operator+=(Multivector<Scalar, Frame, Rank>& left, Multivector<Scalar, Frame, Rank> const& right) { left.coordinates += right.coordinates; } template<typename Scalar, typename Frame, unsigned int Rank> inline void operator-=(Multivector<Scalar, Frame, Rank>& left, Multivector<Scalar, Frame, Rank> const& right) { left.coordinates -= right.coordinates; } template<typename Scalar, typename Frame, unsigned int Rank> inline void operator*=(Multivector<Scalar, Frame, Rank>& left, quantities::Dimensionless const& right) { left.coordinates *= right; } template<typename Scalar, typename Frame, unsigned int Rank> inline void operator/=(Multivector<Scalar, Frame, Rank>& left, quantities::Dimensionless const& right) { left.coordinates /= right; } } // namespace geometry } // namespace principia <commit_msg>Spacing, remove redundant comments<commit_after>#pragma once namespace principia { namespace geometry { template<typename Scalar, typename Frame> Multivector<Scalar, Frame, 1>::Multivector(R3Element<Scalar> const& coordinates) : coordinates(coordinates) {}; template<typename Scalar, typename Frame> Multivector<Scalar, Frame, 2>::Multivector(R3Element<Scalar> const& coordinates) : coordinates(coordinates) {}; template<typename Scalar, typename Frame> Multivector<Scalar, Frame, 3>::Multivector(Scalar const& coordinates) : coordinates(coordinates) {}; template<typename LeftScalar, typename RightScalar, typename Frame> inline quantities::Product<LeftScalar, RightScalar> InnerProduct( Vector<LeftScalar, Frame> const& left, Vector<RightScalar, Frame> const& right) { return Dot(left.coordinates, right.coordinates); } template<typename LeftScalar, typename RightScalar, typename Frame> inline quantities::Product<LeftScalar, RightScalar> InnerProduct( Bivector<LeftScalar, Frame> const& left, Bivector<RightScalar, Frame> const& right) { return Dot(left.coordinates, right.coordinates); } template<typename LeftScalar, typename RightScalar, typename Frame> inline quantities::Product<LeftScalar, RightScalar> InnerProduct( Trivector<LeftScalar, Frame> const& left, Trivector<RightScalar, Frame> const& right) { return left.coordinates * right.coordinates; } template<typename LeftScalar, typename RightScalar, typename Frame> inline Bivector<quantities::Product<LeftScalar, RightScalar>, Frame> Wedge(Vector<LeftScalar, Frame> const& left, Vector<RightScalar, Frame> const& right) { return Bivector<quantities::Product<LeftScalar, RightScalar>, Frame>(Cross(left.coordinates, right.coordinates)); } template<typename LeftScalar, typename RightScalar, typename Frame> inline Trivector<quantities::Product<LeftScalar, RightScalar>, Frame> Wedge(Bivector<LeftScalar, Frame> const& left, Vector<RightScalar, Frame> const& right) { return Trivector<quantities::Product<LeftScalar, RightScalar>, Frame>(Dot(left.coordinates, right.coordinates)); } template<typename LeftScalar, typename RightScalar, typename Frame> inline Trivector<quantities::Product<LeftScalar, RightScalar>, Frame> Wedge(Vector<LeftScalar, Frame> const& left, Bivector<RightScalar, Frame> const& right) { return Trivector<quantities::Product<LeftScalar, RightScalar>, Frame>(Dot(left.coordinates, right.coordinates)); } template<typename LeftScalar, typename RightScalar, typename Frame> inline Bivector<quantities::Product<LeftScalar, RightScalar>, Frame> Commutator(Bivector<LeftScalar, Frame> const& left, Bivector<RightScalar, Frame> const& right) { return Bivector<quantities::Product<LeftScalar, RightScalar>, Frame>(Cross(left.coordinates, right.coordinates)); } template<typename LeftScalar, typename RightScalar, typename Frame> inline Vector<quantities::Product<LeftScalar, RightScalar>, Frame> operator*(Bivector<LeftScalar, Frame> const& left, Vector<RightScalar, Frame> const& right) { return Vector<quantities::Product<LeftScalar, RightScalar>, Frame>(Cross(left.coordinates, right.coordinates)); } template<typename LeftScalar, typename RightScalar, typename Frame> inline Vector<quantities::Product<LeftScalar, RightScalar>, Frame> operator*(Vector<LeftScalar, Frame> const& left, Bivector<RightScalar, Frame> const& right) { return Vector<quantities::Product<LeftScalar, RightScalar>, Frame>(Cross(left.coordinates, right.coordinates)); } template<typename Scalar, typename Frame, unsigned int Rank> inline Multivector<Scalar, Frame, Rank> operator+( Multivector<Scalar, Frame, Rank> const& right) { return Multivector<Scalar, Frame, Rank>(+right.coordinates); } template<typename Scalar, typename Frame, unsigned int Rank> inline Multivector<Scalar, Frame, Rank> operator-( Multivector<Scalar, Frame, Rank> const& right) { return Multivector<Scalar, Frame, Rank>(-right.coordinates); } template<typename Scalar, typename Frame, unsigned int Rank> inline Multivector<Scalar, Frame, Rank> operator+( Multivector<Scalar, Frame, Rank> const& left, Multivector<Scalar, Frame, Rank> const& right) { return Multivector<Scalar, Frame, Rank>(left.coordinates + right.coordinates); } template<typename Scalar, typename Frame, unsigned int Rank> inline Multivector<Scalar, Frame, Rank> operator-( Multivector<Scalar, Frame, Rank> const& left, Multivector<Scalar, Frame, Rank> const& right) { return Multivector<Scalar, Frame, Rank>(left.coordinates - right.coordinates); } template<typename Scalar, typename Frame, unsigned int Rank> inline Multivector<Scalar, Frame, Rank> operator*( quantities::Dimensionless const& left, Multivector<Scalar, Frame, Rank> const& right) { return Multivector<Scalar, Frame, Rank>(left * right.coordinates); } template<typename Scalar, typename Frame, unsigned int Rank> inline Multivector<Scalar, Frame, Rank> operator*( Multivector<Scalar, Frame, Rank> const& left, quantities::Dimensionless const& right) { return Multivector<Scalar, Frame, Rank>(left.coordinates * right); } template<typename Scalar, typename Frame, unsigned int Rank> inline Multivector<Scalar, Frame, Rank> operator/( Multivector<Scalar, Frame, Rank> const& left, quantities::Dimensionless const& right) { return Multivector<Scalar, Frame, Rank>(left.coordinates / right); } template<typename DLeft, typename RightScalar, typename Frame, unsigned int Rank> inline Multivector< quantities::Product<quantities::Quantity<DLeft>, RightScalar>, Frame, Rank> operator*(quantities::Quantity<DLeft> const& left, Multivector<RightScalar, Frame, Rank> const& right) { return Multivector< quantities::Product<quantities::Quantity<DLeft>, RightScalar>, Frame, Rank>(left * right.coordinates); } template<typename LeftScalar, typename DRight, typename Frame, unsigned int Rank> inline Multivector< quantities::Product<LeftScalar, quantities::Quantity<DRight>>, Frame, Rank> operator*(Multivector<LeftScalar, Frame, Rank> const& left, quantities::Quantity<DRight> const& right) { return Multivector< quantities::Product<LeftScalar, quantities::Quantity<DRight>>, Frame, Rank>(left.coordinates * right); } template<typename LeftScalar, typename DRight, typename Frame, unsigned int Rank> inline Multivector< quantities::Quotient<LeftScalar, quantities::Quantity<DRight>>, Frame, Rank> operator/(Multivector<LeftScalar, Frame, Rank> const& left, quantities::Quantity<DRight> const& right) { return Multivector< quantities::Quotient<LeftScalar, quantities::Quantity<DRight>>, Frame, Rank>(left.coordinates / right); } template<typename Scalar, typename Frame, unsigned int Rank> inline void operator+=(Multivector<Scalar, Frame, Rank>& left, Multivector<Scalar, Frame, Rank> const& right) { left.coordinates += right.coordinates; } template<typename Scalar, typename Frame, unsigned int Rank> inline void operator-=(Multivector<Scalar, Frame, Rank>& left, Multivector<Scalar, Frame, Rank> const& right) { left.coordinates -= right.coordinates; } template<typename Scalar, typename Frame, unsigned int Rank> inline void operator*=(Multivector<Scalar, Frame, Rank>& left, quantities::Dimensionless const& right) { left.coordinates *= right; } template<typename Scalar, typename Frame, unsigned int Rank> inline void operator/=(Multivector<Scalar, Frame, Rank>& left, quantities::Dimensionless const& right) { left.coordinates /= right; } } // namespace geometry } // namespace principia <|endoftext|>
<commit_before>#pragma once namespace Principia { namespace Geometry { template<typename T, typename Frame, unsigned int Rank> inline Multivector<T, Frame, Rank> operator+(Multivector<T, Frame, Rank> const& right) { return Multivector<T, Frame, Rank>(+right.coordinates); } template<typename T, typename Frame, unsigned int Rank> inline Multivector<T, Frame, Rank> operator-(Multivector<T, Frame, Rank> const& right) { return Multivector<T, Frame, Rank>(-right.coordinates); } template<typename T, typename Frame, unsigned int Rank> inline Multivector<T, Frame, Rank> operator+(Multivector<T, Frame, Rank> const& left, Multivector<T, Frame, Rank> const& right) { return Multivector<T, Frame, Rank>(left.coordinates + right.coordinates); } template<typename T, typename Frame, unsigned int Rank> inline Multivector<T, Frame, Rank> operator-(Multivector<T, Frame, Rank> const& left, Multivector<T, Frame, Rank> const& right) { return Multivector<T, Frame, Rank>(left.coordinates + left.coordinates); } template<typename T, typename Frame, unsigned int Rank> inline Multivector<T, Frame, Rank> operator*(Quantities::Dimensionless const& left, Multivector<T, Frame, Rank> const& right) { return Multivector<T, Frame, Rank>(left * right.coordinates); } template<typename T, typename Frame, unsigned int Rank> inline Multivector<T, Frame, Rank> operator*(Multivector<T, Frame, Rank> const& left, Quantities::Dimensionless const& right) { return Multivector<T, Frame, Rank>(left.coordinates * right); } template<typename T, typename Frame, unsigned int Rank> inline Multivector<T, Frame, Rank> operator/(Multivector<T, Frame, Rank> const& left, Quantities::Dimensionless const& right) { return Multivector<T, Frame, Rank>(left.coordinates / right); } template<typename T, typename U, typename Frame, unsigned int Rank> inline Multivector<Quantities::Product<U, T> , Frame, Rank> operator*(U const& left, Multivector<T, Frame, Rank> const& right) { return Multivector<T, Frame, Rank>(left * right.coordinates); } template<typename T, typename U, typename Frame, unsigned int Rank> inline Multivector<Quantities::Product<T, U>, Frame, Rank> operator*(Multivector<T, Frame, Rank> const& left, Quantities::Dimensionless const& right) { return Multivector<T, Frame, Rank>(left.coordinates * right); } template<typename T, typename U, typename Frame, unsigned int Rank> inline Multivector<Quantities::Quotient<T, U>, Frame, Rank> operator/(Multivector<T, Frame, Rank> const& left, Quantities::Dimensionless const& right) { return Multivector<T, Frame, Rank>(left.coordinates / right); } template<typename T, typename Frame, unsigned int Rank> inline void operator+=(Multivector<T, Frame, Rank>& left, Multivector<T, Frame, Rank> const& right) { left.coordinates += right.coordinates; } template<typename T, typename Frame, unsigned int Rank> inline void operator-=(Multivector<T, Frame, Rank>& left, Multivector<T, Frame, Rank> const& right) { left.coordinates -= right.coordinates; } template<typename T, typename Frame, unsigned int Rank> inline void operator*=(Multivector<T, Frame, Rank>& left, Quantities::Dimensionless const& right) { left.coordinates *= right; } template<typename T, typename Frame, unsigned int Rank> inline void operator/=(Multivector<T, Frame, Rank>& left, Quantities::Dimensionless const& right) { left.coordinates /= right; } } } <commit_msg>spacing<commit_after>#pragma once namespace Principia { namespace Geometry { template<typename T, typename Frame, unsigned int Rank> inline Multivector<T, Frame, Rank> operator+(Multivector<T, Frame, Rank> const& right) { return Multivector<T, Frame, Rank>(+right.coordinates); } template<typename T, typename Frame, unsigned int Rank> inline Multivector<T, Frame, Rank> operator-(Multivector<T, Frame, Rank> const& right) { return Multivector<T, Frame, Rank>(-right.coordinates); } template<typename T, typename Frame, unsigned int Rank> inline Multivector<T, Frame, Rank> operator+(Multivector<T, Frame, Rank> const& left, Multivector<T, Frame, Rank> const& right) { return Multivector<T, Frame, Rank>(left.coordinates + right.coordinates); } template<typename T, typename Frame, unsigned int Rank> inline Multivector<T, Frame, Rank> operator-(Multivector<T, Frame, Rank> const& left, Multivector<T, Frame, Rank> const& right) { return Multivector<T, Frame, Rank>(left.coordinates + left.coordinates); } template<typename T, typename Frame, unsigned int Rank> inline Multivector<T, Frame, Rank> operator*(Quantities::Dimensionless const& left, Multivector<T, Frame, Rank> const& right) { return Multivector<T, Frame, Rank>(left * right.coordinates); } template<typename T, typename Frame, unsigned int Rank> inline Multivector<T, Frame, Rank> operator*(Multivector<T, Frame, Rank> const& left, Quantities::Dimensionless const& right) { return Multivector<T, Frame, Rank>(left.coordinates * right); } template<typename T, typename Frame, unsigned int Rank> inline Multivector<T, Frame, Rank> operator/(Multivector<T, Frame, Rank> const& left, Quantities::Dimensionless const& right) { return Multivector<T, Frame, Rank>(left.coordinates / right); } template<typename T, typename U, typename Frame, unsigned int Rank> inline Multivector<Quantities::Product<U, T> , Frame, Rank> operator*(U const& left, Multivector<T, Frame, Rank> const& right) { return Multivector<T, Frame, Rank>(left * right.coordinates); } template<typename T, typename U, typename Frame, unsigned int Rank> inline Multivector<Quantities::Product<T, U>, Frame, Rank> operator*(Multivector<T, Frame, Rank> const& left, Quantities::Dimensionless const& right) { return Multivector<T, Frame, Rank>(left.coordinates * right); } template<typename T, typename U, typename Frame, unsigned int Rank> inline Multivector<Quantities::Quotient<T, U>, Frame, Rank> operator/(Multivector<T, Frame, Rank> const& left, Quantities::Dimensionless const& right) { return Multivector<T, Frame, Rank>(left.coordinates / right); } template<typename T, typename Frame, unsigned int Rank> inline void operator+=(Multivector<T, Frame, Rank>& left, Multivector<T, Frame, Rank> const& right) { left.coordinates += right.coordinates; } template<typename T, typename Frame, unsigned int Rank> inline void operator-=(Multivector<T, Frame, Rank>& left, Multivector<T, Frame, Rank> const& right) { left.coordinates -= right.coordinates; } template<typename T, typename Frame, unsigned int Rank> inline void operator*=(Multivector<T, Frame, Rank>& left, Quantities::Dimensionless const& right) { left.coordinates *= right; } template<typename T, typename Frame, unsigned int Rank> inline void operator/=(Multivector<T, Frame, Rank>& left, Quantities::Dimensionless const& right) { left.coordinates /= right; } } } <|endoftext|>
<commit_before>// // Landscape.cpp // // Created by Soso Limited on 5/26/15. // // #include "Landscape.h" #include "cinder/Log.h" #include "Constants.h" using namespace soso; using namespace cinder; namespace { struct alignas(16) Vertex { vec3 position; vec3 normal; vec2 tex_coord; vec2 color_tex_coord; float deform_scaling; float frame_offset; float color_weight; }; const auto kVertexLayout = ([] { auto layout = geom::BufferLayout(); layout.append( geom::Attrib::POSITION, 3, sizeof(Vertex), offsetof(Vertex, position) ); layout.append( geom::Attrib::NORMAL, 3, sizeof(Vertex), offsetof(Vertex, normal) ); layout.append( geom::Attrib::TEX_COORD_0, 2, sizeof(Vertex), offsetof(Vertex, tex_coord) ); layout.append( geom::Attrib::TEX_COORD_1, 2, sizeof(Vertex), offsetof(Vertex, color_tex_coord) ); layout.append( geom::Attrib::CUSTOM_0, 1, sizeof(Vertex), offsetof(Vertex, deform_scaling) ); layout.append( geom::Attrib::CUSTOM_1, 1, sizeof(Vertex), offsetof(Vertex, frame_offset) ); layout.append( geom::Attrib::CUSTOM_2, 1, sizeof(Vertex), offsetof(Vertex, color_weight) ); return layout; } ()); const auto kVertexMapping = ([] { return gl::Batch::AttributeMapping{ { geom::Attrib::CUSTOM_0, "DeformScaling" }, { geom::Attrib::CUSTOM_1, "FrameOffset" }, { geom::Attrib::CUSTOM_2, "ColorWeight" } }; } ()); // Load a shader and handle exceptions. Return nullptr on failure. gl::GlslProgRef loadShader( const fs::path &iVertex, const fs::path &iFragment ) { try { auto shader_format = gl::GlslProg::Format() .vertex( app::loadAsset( iVertex ) ) .fragment( app::loadAsset( iFragment ) ); return gl::GlslProg::create( shader_format ); } catch( ci::Exception &exc ) { CI_LOG_E( "Error loading shader: " << exc.what() ); } return nullptr; } /// /// Create a quadrilateral with clockwise vertices abcd. /// Maps to frame at time and a slice of the video frame. /// void addQuad( std::vector<Vertex> &vertices, const vec3 &a, const vec3 &b, const vec3 &c, const vec3 &d, float time, const Rectf &slice ) { auto normal = vec3( 0, 1, 0 ); auto deform_scaling = 0.0f; vertices.insert( vertices.end(), { Vertex{ a, normal, slice.getUpperLeft(), slice.getUpperLeft(), deform_scaling, time, 0.0f }, Vertex{ b, normal, slice.getUpperRight(), slice.getUpperRight(), deform_scaling, time, 0.0f }, Vertex{ c, normal, slice.getLowerRight(), slice.getLowerRight(), deform_scaling, time, 0.0f }, Vertex{ a, normal, slice.getUpperLeft(), slice.getUpperLeft(), deform_scaling, time, 0.0f }, Vertex{ c, normal, slice.getLowerRight(), slice.getLowerRight(), deform_scaling, time, 0.0f }, Vertex{ d, normal, slice.getLowerLeft(), slice.getLowerLeft(), deform_scaling, time, 0.0f } } ); } /// Add a ring of geometry containing a given number of time bands (slitscanning effect) and repeats around the donut. void addRing( std::vector<Vertex> &vertices, const vec3 &center, const vec3 &normal, float inner_radius, float outer_radius, float time_offset, int time_bands, int repeats, float color_weight, const vec2 &texture_insets = vec2( 0.05, 0.0875f ) ) { auto rings = time_bands; auto segments = 64; // Generate cartesian position. auto calc_pos = [=] (int r, int s) { auto distance = lmap<float>( r, 0, rings, 0.0f, 1.0f ); auto radius = mix( inner_radius, outer_radius, distance ); auto t = (float) s / segments; auto x = cos( t * Tau ) * radius; auto y = sin( t * Tau ) * radius; return vec3( x, 0, y ) + center; }; // Generate texture coordinate mirrored at halfway point. auto calc_tc = [=] (int r, int s) { auto t = (float) s / segments; if( t < 1 ) { t = glm::fract( t * repeats ); } // mirror copies t = std::abs( t - 0.5f ) * 2.0f; auto tc = vec2(0); // Repeat t with mirroring // insetting the texture coordinates minimizes edge color flashing. tc.y = mix( texture_insets.y, 1.0f - texture_insets.y, t ); tc.x = lmap<float>( r, 0, rings, 1.0f - texture_insets.x, texture_insets.x ); return tc; }; // Add a vertex to texture (color_tc parameter allows us to do flat shading in ES2) auto add_vert = [=,&vertices] (int r, int s, const ivec2 &provoking) { auto deform_scaling = 0.0f; auto pos = calc_pos(r, s); auto tc = calc_tc(r, s); auto color_tc = calc_tc( provoking.x, provoking.y ); auto time = time_offset; // + lmap<float>( r, 0, rings, 0.0f, 1.0f / 64.0f ); if (time_bands > 1) { time += lmap<float>( provoking.x, 0.0f, rings, 0.0f, time_bands ); } vertices.push_back( Vertex{ pos, normal, tc, color_tc, deform_scaling, time, color_weight } ); }; // Create triangles for flat shading for( auto r = 0; r < rings; r += 1 ) { for( auto s = 0; s < segments; s += 1 ) { auto provoking = ivec2(r, s); add_vert( r, s, provoking ); add_vert( r, s + 1, provoking ); add_vert( r + 1, s + 1, provoking ); add_vert( r, s, provoking ); add_vert( r + 1, s, provoking ); add_vert( r + 1, s + 1, provoking ); } } } } // namespace void Landscape::setup() { auto shader = loadShader( "landscape.vs", "landscape.fs" ); std::vector<Vertex> vertices; auto normal = vec3( 0, 1, 0 ); auto inner = 0.28f; auto outer = 3.0f; struct Params { float repeats; float frames; float color_weight; vec2 insets; }; auto params = std::vector<Params> { { 2, 1, 0.0f, vec2( 0.05, 0.0875f ) }, { 4, 1, 0.0f, vec2( 0.05, 0.0875f ) }, { 6, 1, 0.0f, vec2( 0.05, 0.0875f ) }, { 8, 1, 0.0f, vec2( 0.05, 0.0875f ) }, { 10, 1, 0.0f, vec2( 0.05, 0.0875f ) }, { 12, 1, 0.0f, vec2( 0.05, 0.0875f ) }, { 10, 1, 0.0f, vec2( 0.05, 0.0875f ) }, { 8, 1, 0.1f, vec2( 0.075, 0.1 ) }, { 10, 1, 0.25f, vec2( 0.1, 0.125 ) }, { 8, 1, 0.5f, vec2( 0.25, 0.15 ) } }; for( auto i = 0; i < params.size(); i += 1 ) { auto &p = params.at( i ); auto copies = p.repeats; auto t = (i + 0.0f) / params.size(); auto t2 = (i + 1.0f) / params.size(); auto r1 = mix( inner, outer, t ); auto r2 = mix( inner, outer, t2 ); addRing( vertices, vec3( 0, -4, 0 ), normal, r1, r2, i * 2 + 1.0f, 1, copies, p.color_weight, p.insets ); } addRing( vertices, vec3( 0, -4, 0 ), normal, outer, outer + 2.0f, params.size() * 2, 64 - (params.size() * 2), 1, 1.0f ); // Deform stuff // /* auto min_distance = inner; auto max_distance = outer; for( auto &v : vertices ) { auto distance = lmap<float>( length( v.position ), min_distance, max_distance, 0.0f, 1.0f ); // pos is on a radial axis, rotate it 90 degrees to bend along length auto axis = glm::rotate( glm::angleAxis( (float)Tau / 4.0f, vec3(0, 1, 0) ), normalize(v.position) ); auto theta = mix( 0.0f, -(float)Tau / 18.0f, distance ); auto xf = glm::rotate( theta, axis ); v.normal = vec3(xf * vec4(v.normal, 0.0f)); // v.deform_scaling = mix( 0.0f, 4.0f, distance ); v.position = vec3(xf * vec4(v.position, 1.0f)); // v.color_weight = 0.0f; // mix( 0.0f, 1.0f, distance * distance ); // if( distance >= 1.0f ) { // v.color_weight = 1.0f; // } } // */ // Plug center auto h = vec3( inner, 0, inner ) * 1.5f; auto c = vec3( 0, -4.0f, 0 ); addQuad( vertices, c + (h * vec3(-1, 0, -1)), c + (h * vec3(1, 0, -1)), c + (h * vec3(1, 0, 1)), c + (h * vec3(-1, 0, 1)), 0.0f, Rectf( 0, 1, 1, 0 ) ); auto vbo = gl::Vbo::create( GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW ); auto mesh = gl::VboMesh::create( vertices.size(), GL_TRIANGLES, {{ kVertexLayout, vbo }} ); batch = gl::Batch::create( mesh, shader, kVertexMapping ); } void Landscape::setTextureUnits( uint8_t iClearUnit, uint8_t iBlurredUnit ) { auto &shader = batch->getGlslProg(); shader->uniform( "uClearTexture", iClearUnit ); shader->uniform( "uBlurredTexture", iBlurredUnit ); } void Landscape::draw( float iFrameOffset ) { auto &shader = batch->getGlslProg(); shader->uniform( "uCurrentFrame", iFrameOffset ); batch->draw(); } <commit_msg>Gradually introduce slit-scanning.<commit_after>// // Landscape.cpp // // Created by Soso Limited on 5/26/15. // // #include "Landscape.h" #include "cinder/Log.h" #include "Constants.h" using namespace soso; using namespace cinder; namespace { struct alignas(16) Vertex { vec3 position; vec3 normal; vec2 tex_coord; vec2 color_tex_coord; float deform_scaling; float frame_offset; float color_weight; }; const auto kVertexLayout = ([] { auto layout = geom::BufferLayout(); layout.append( geom::Attrib::POSITION, 3, sizeof(Vertex), offsetof(Vertex, position) ); layout.append( geom::Attrib::NORMAL, 3, sizeof(Vertex), offsetof(Vertex, normal) ); layout.append( geom::Attrib::TEX_COORD_0, 2, sizeof(Vertex), offsetof(Vertex, tex_coord) ); layout.append( geom::Attrib::TEX_COORD_1, 2, sizeof(Vertex), offsetof(Vertex, color_tex_coord) ); layout.append( geom::Attrib::CUSTOM_0, 1, sizeof(Vertex), offsetof(Vertex, deform_scaling) ); layout.append( geom::Attrib::CUSTOM_1, 1, sizeof(Vertex), offsetof(Vertex, frame_offset) ); layout.append( geom::Attrib::CUSTOM_2, 1, sizeof(Vertex), offsetof(Vertex, color_weight) ); return layout; } ()); const auto kVertexMapping = ([] { return gl::Batch::AttributeMapping{ { geom::Attrib::CUSTOM_0, "DeformScaling" }, { geom::Attrib::CUSTOM_1, "FrameOffset" }, { geom::Attrib::CUSTOM_2, "ColorWeight" } }; } ()); // Load a shader and handle exceptions. Return nullptr on failure. gl::GlslProgRef loadShader( const fs::path &iVertex, const fs::path &iFragment ) { try { auto shader_format = gl::GlslProg::Format() .vertex( app::loadAsset( iVertex ) ) .fragment( app::loadAsset( iFragment ) ); return gl::GlslProg::create( shader_format ); } catch( ci::Exception &exc ) { CI_LOG_E( "Error loading shader: " << exc.what() ); } return nullptr; } /// /// Create a quadrilateral with clockwise vertices abcd. /// Maps to frame at time and a slice of the video frame. /// void addQuad( std::vector<Vertex> &vertices, const vec3 &a, const vec3 &b, const vec3 &c, const vec3 &d, float time, const Rectf &slice ) { auto normal = vec3( 0, 1, 0 ); auto deform_scaling = 0.0f; vertices.insert( vertices.end(), { Vertex{ a, normal, slice.getUpperLeft(), slice.getUpperLeft(), deform_scaling, time, 0.0f }, Vertex{ b, normal, slice.getUpperRight(), slice.getUpperRight(), deform_scaling, time, 0.0f }, Vertex{ c, normal, slice.getLowerRight(), slice.getLowerRight(), deform_scaling, time, 0.0f }, Vertex{ a, normal, slice.getUpperLeft(), slice.getUpperLeft(), deform_scaling, time, 0.0f }, Vertex{ c, normal, slice.getLowerRight(), slice.getLowerRight(), deform_scaling, time, 0.0f }, Vertex{ d, normal, slice.getLowerLeft(), slice.getLowerLeft(), deform_scaling, time, 0.0f } } ); } /// Add a ring of geometry containing a given number of time bands (slitscanning effect) and repeats around the donut. void addRing( std::vector<Vertex> &vertices, const vec3 &center, const vec3 &normal, float inner_radius, float outer_radius, float time_offset, int time_bands, int repeats, float color_weight, const vec2 &texture_insets = vec2( 0.05, 0.0875f ) ) { auto rings = time_bands; auto segments = 64; // Generate cartesian position. auto calc_pos = [=] (int r, int s) { auto distance = lmap<float>( r, 0, rings, 0.0f, 1.0f ); auto radius = mix( inner_radius, outer_radius, distance ); auto t = (float) s / segments; auto x = cos( t * Tau ) * radius; auto y = sin( t * Tau ) * radius; return vec3( x, 0, y ) + center; }; // Generate texture coordinate mirrored at halfway point. auto calc_tc = [=] (int r, int s) { auto t = (float) s / segments; if( t < 1 ) { t = glm::fract( t * repeats ); } // mirror copies t = std::abs( t - 0.5f ) * 2.0f; auto tc = vec2(0); // Repeat t with mirroring // insetting the texture coordinates minimizes edge color flashing. tc.y = mix( texture_insets.y, 1.0f - texture_insets.y, t ); tc.x = lmap<float>( r, 0, rings, 1.0f - texture_insets.x, texture_insets.x ); return tc; }; // Add a vertex to texture (color_tc parameter allows us to do flat shading in ES2) auto add_vert = [=,&vertices] (int r, int s, const ivec2 &provoking) { auto deform_scaling = 0.0f; auto pos = calc_pos(r, s); auto tc = calc_tc(r, s); auto color_tc = calc_tc( provoking.x, provoking.y ); auto time = time_offset; // + lmap<float>( r, 0, rings, 0.0f, 1.0f / 64.0f ); if (time_bands > 1) { time += lmap<float>( provoking.x, 0.0f, rings, 0.0f, time_bands ); } vertices.push_back( Vertex{ pos, normal, tc, color_tc, deform_scaling, time, color_weight } ); }; // Create triangles for flat shading for( auto r = 0; r < rings; r += 1 ) { for( auto s = 0; s < segments; s += 1 ) { auto provoking = ivec2(r, s); add_vert( r, s, provoking ); add_vert( r, s + 1, provoking ); add_vert( r + 1, s + 1, provoking ); add_vert( r, s, provoking ); add_vert( r + 1, s, provoking ); add_vert( r + 1, s + 1, provoking ); } } } } // namespace void Landscape::setup() { auto shader = loadShader( "landscape.vs", "landscape.fs" ); std::vector<Vertex> vertices; auto normal = vec3( 0, 1, 0 ); auto inner = 0.28f; auto outer = 3.0f; struct Params { float repeats; float frames; float color_weight; vec2 insets; }; auto params = std::vector<Params> { { 2, 1, 0.0f, vec2( 0.05, 0.0875f ) }, { 4, 1, 0.0f, vec2( 0.05, 0.0875f ) }, { 6, 1, 0.0f, vec2( 0.05, 0.0875f ) }, { 8, 1, 0.0f, vec2( 0.05, 0.0875f ) }, { 10, 1, 0.0f, vec2( 0.05, 0.0875f ) }, { 12, 1, 0.0f, vec2( 0.05, 0.0875f ) }, { 10, 1, 0.0f, vec2( 0.05, 0.0875f ) }, { 8, 1, 0.1f, vec2( 0.075, 0.1 ) }, { 10, 2, 0.25f, vec2( 0.1, 0.125 ) }, { 8, 8, 0.5f, vec2( 0.25, 0.15 ) } }; for( auto i = 0; i < params.size(); i += 1 ) { auto &p = params.at( i ); auto copies = p.repeats; auto t = (i + 0.0f) / params.size(); auto t2 = (i + 1.0f) / params.size(); auto r1 = mix( inner, outer, t ); auto r2 = mix( inner, outer, t2 ); addRing( vertices, vec3( 0, -4, 0 ), normal, r1, r2, i * 2 + 1.0f, p.frames, copies, p.color_weight, p.insets ); } auto last_frame = params.size() * 2 + 4.0f; // actually some overlap auto remaining_frames = 64.0f - last_frame; addRing( vertices, vec3( 0, -4, 0 ), normal, outer, outer + 2.0f, last_frame, remaining_frames, 1, 1.0f ); // Deform stuff // /* auto min_distance = inner; auto max_distance = outer; for( auto &v : vertices ) { auto distance = lmap<float>( length( v.position ), min_distance, max_distance, 0.0f, 1.0f ); // pos is on a radial axis, rotate it 90 degrees to bend along length auto axis = glm::rotate( glm::angleAxis( (float)Tau / 4.0f, vec3(0, 1, 0) ), normalize(v.position) ); auto theta = mix( 0.0f, -(float)Tau / 18.0f, distance ); auto xf = glm::rotate( theta, axis ); v.normal = vec3(xf * vec4(v.normal, 0.0f)); // v.deform_scaling = mix( 0.0f, 4.0f, distance ); v.position = vec3(xf * vec4(v.position, 1.0f)); // v.color_weight = 0.0f; // mix( 0.0f, 1.0f, distance * distance ); // if( distance >= 1.0f ) { // v.color_weight = 1.0f; // } } // */ // Plug center auto h = vec3( inner, 0, inner ) * 1.5f; auto c = vec3( 0, -4.0f, 0 ); addQuad( vertices, c + (h * vec3(-1, 0, -1)), c + (h * vec3(1, 0, -1)), c + (h * vec3(1, 0, 1)), c + (h * vec3(-1, 0, 1)), 0.0f, Rectf( 0, 1, 1, 0 ) ); auto vbo = gl::Vbo::create( GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW ); auto mesh = gl::VboMesh::create( vertices.size(), GL_TRIANGLES, {{ kVertexLayout, vbo }} ); batch = gl::Batch::create( mesh, shader, kVertexMapping ); } void Landscape::setTextureUnits( uint8_t iClearUnit, uint8_t iBlurredUnit ) { auto &shader = batch->getGlslProg(); shader->uniform( "uClearTexture", iClearUnit ); shader->uniform( "uBlurredTexture", iBlurredUnit ); } void Landscape::draw( float iFrameOffset ) { auto &shader = batch->getGlslProg(); shader->uniform( "uCurrentFrame", iFrameOffset ); batch->draw(); } <|endoftext|>
<commit_before>6cd56b62-5216-11e5-93de-6c40088e03e4<commit_msg>6cdc4338-5216-11e5-85c2-6c40088e03e4<commit_after>6cdc4338-5216-11e5-85c2-6c40088e03e4<|endoftext|>
<commit_before>68864ed4-2fa5-11e5-98ec-00012e3d3f12<commit_msg>6888bfd4-2fa5-11e5-b326-00012e3d3f12<commit_after>6888bfd4-2fa5-11e5-b326-00012e3d3f12<|endoftext|>
<commit_before>f0fe3573-2e4e-11e5-8b48-28cfe91dbc4b<commit_msg>f10a501c-2e4e-11e5-bbc0-28cfe91dbc4b<commit_after>f10a501c-2e4e-11e5-bbc0-28cfe91dbc4b<|endoftext|>
<commit_before>29c35aae-2f67-11e5-9431-6c40088e03e4<commit_msg>29caa0a2-2f67-11e5-a6ad-6c40088e03e4<commit_after>29caa0a2-2f67-11e5-a6ad-6c40088e03e4<|endoftext|>
<commit_before>7775cd38-2d53-11e5-baeb-247703a38240<commit_msg>77764c18-2d53-11e5-baeb-247703a38240<commit_after>77764c18-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>af5e1128-4b02-11e5-8d98-28cfe9171a43<commit_msg>For bobby to integrate at some point<commit_after>af6bdf3a-4b02-11e5-844e-28cfe9171a43<|endoftext|>
<commit_before>d6523b8c-35ca-11e5-8f66-6c40088e03e4<commit_msg>d659b6a2-35ca-11e5-9b7a-6c40088e03e4<commit_after>d659b6a2-35ca-11e5-9b7a-6c40088e03e4<|endoftext|>
<commit_before>d7ed0af3-2e4e-11e5-8c2e-28cfe91dbc4b<commit_msg>d7f78c40-2e4e-11e5-9587-28cfe91dbc4b<commit_after>d7f78c40-2e4e-11e5-9587-28cfe91dbc4b<|endoftext|>
<commit_before>8bd284d9-2d3d-11e5-8de5-c82a142b6f9b<commit_msg>8c8490e3-2d3d-11e5-840b-c82a142b6f9b<commit_after>8c8490e3-2d3d-11e5-840b-c82a142b6f9b<|endoftext|>
<commit_before>9101ad47-2d14-11e5-af21-0401358ea401<commit_msg>9101ad48-2d14-11e5-af21-0401358ea401<commit_after>9101ad48-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>d1abc008-35ca-11e5-adaf-6c40088e03e4<commit_msg>d1b259a4-35ca-11e5-af56-6c40088e03e4<commit_after>d1b259a4-35ca-11e5-af56-6c40088e03e4<|endoftext|>
<commit_before>822db400-2e4f-11e5-a94d-28cfe91dbc4b<commit_msg>8234f045-2e4f-11e5-b137-28cfe91dbc4b<commit_after>8234f045-2e4f-11e5-b137-28cfe91dbc4b<|endoftext|>
<commit_before>5e5893e1-2d16-11e5-af21-0401358ea401<commit_msg>5e5893e2-2d16-11e5-af21-0401358ea401<commit_after>5e5893e2-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>5bf6738e-2d16-11e5-af21-0401358ea401<commit_msg>5bf6738f-2d16-11e5-af21-0401358ea401<commit_after>5bf6738f-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>8c3d2147-2d14-11e5-af21-0401358ea401<commit_msg>8c3d2148-2d14-11e5-af21-0401358ea401<commit_after>8c3d2148-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>278af6ab-2e4f-11e5-bfd0-28cfe91dbc4b<commit_msg>279445f5-2e4f-11e5-a4f7-28cfe91dbc4b<commit_after>279445f5-2e4f-11e5-a4f7-28cfe91dbc4b<|endoftext|>
<commit_before>#include <iostream> #include <string> #include "Class.hpp" using namespace std; int main() { string newName; int newHeight; double newWeight; BMI student_1; cout << "Enter Name: "; cin >> newName; cout << "\nEnter Height: "; cin >> newHeight; cout << "\nEnter Weight: "; cin >> newWeight; student_1.setName(newName); student_1.setHeight(newHeight); student_1.setWeight(newWeight); cout << "Name: " << student_1.getName() << endl << "Height: " << student_1.getHeight() << endl << "Weight: " << student_1.getWeight() << endl; return 0; } <commit_msg>changed class name to "BMI"<commit_after>#include <iostream> #include <string> #include "BMI.hpp" using namespace std; int main() { string newName; int newHeight; double newWeight; BMI student_1; cout << "Enter Name: "; cin >> newName; cout << "\nEnter Height: "; cin >> newHeight; cout << "\nEnter Weight: "; cin >> newWeight; student_1.setName(newName); student_1.setHeight(newHeight); student_1.setWeight(newWeight); cout << "Name: " << student_1.getName() << endl << "Height: " << student_1.getHeight() << endl << "Weight: " << student_1.getWeight() << endl; return 0; } <|endoftext|>
<commit_before>83000dd2-2d15-11e5-af21-0401358ea401<commit_msg>83000dd3-2d15-11e5-af21-0401358ea401<commit_after>83000dd3-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>0cdff5ee-585b-11e5-802a-6c40088e03e4<commit_msg>0ce94810-585b-11e5-96f6-6c40088e03e4<commit_after>0ce94810-585b-11e5-96f6-6c40088e03e4<|endoftext|>
<commit_before>9101add5-2d14-11e5-af21-0401358ea401<commit_msg>9101add6-2d14-11e5-af21-0401358ea401<commit_after>9101add6-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>7b078211-4b02-11e5-bafb-28cfe9171a43<commit_msg>Boyaaah!<commit_after>7b1664c7-4b02-11e5-bca1-28cfe9171a43<|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <unordered_map> #include <random> #include <unordered_set> #include <math.h> #include <chrono> #include <string> using namespace std; // Maximum allowed duration int maxDuration = 98; int heuristicConstant = 1; double biasParameter = 1 / sqrt(2); bool TESTING = true; random_device rseed; mt19937 rgen(rseed()); // mersenne_twister int randomIntRange(int min, int max){ uniform_int_distribution<int> idist(min, max); return idist(rgen); } class Point { int x, y; public: Point(int _x, int _y){ x = _x; y = _y; } Point(){ x = 0; y = 0; } const int getX() const { return x; } const int getY() const { return y; } bool operator==(const Point &other) const { return (x == other.x && y == other.y); } }; namespace std { template <> struct hash<Point> { size_t operator()(const Point& k) const { // Compute individual hash values for two data members and combine them using XOR and bit shifting return ((hash<int>()(k.getX()) ^ (hash<int>()(k.getY()) << 1)) >> 1); } }; } vector<vector<Point*>> points; int width = 30, height = 20; class Board{ unordered_set<Point*> blocked; public: Board(){} Board(const Board& board) : blocked(board.blocked){} void setBlocked(Point* p){ blocked.insert(p); } unordered_set<Point*> getBlocked(){ return blocked; } bool isBlocked(Point* p){ return blocked.find(p) != blocked.end(); } Point* getPoint(int x, int y){ if(x >= 0 && width > x && y >= 0 && height > y){ return points.at(x).at(y); }else{ return nullptr; } } vector<Point*> getNeighbors(int x, int y){ vector<Point*> neighbors; Point* bottom = getPoint(x, y-1); Point* top = getPoint(x, y+1); Point* left = getPoint(x-1, y); Point* right = getPoint(x+1, y); if(top != nullptr){ neighbors.push_back(top); } if(bottom != nullptr){ neighbors.push_back(bottom); } if(left != nullptr){ neighbors.push_back(left); } if(right != nullptr){ neighbors.push_back(right); } return neighbors; } vector<Point*> validNeighbors(int x, int y){ vector<Point*> valid; for(Point*& p : getNeighbors(x, y)){ if( !isBlocked(p) ){ valid.push_back(p); } } return valid; } operator std::string() const { return "Hi"; } }; class Player{ public: Point* position; explicit Player(Point* pos) : position(pos){} Player(const Player& p){ position = p.position; } Player(){} Point* getRandomMove(Board& board){ vector<Point*> possibleMoves = board.validNeighbors(position->getX(), position->getY()); if( !possibleMoves.empty() ){ int randomPos = (unsigned int) randomIntRange(1, possibleMoves.size()) - 1; return possibleMoves.at(randomPos); }else{ // If the enemy cant return a valid choice it has lost return nullptr; } } void setPosition(Point* p){ this->position = p; } Point* getPosition(){ return this->position; } Point* getSemiRandomMove(Board& board, vector<Player>& enemies){ vector<Point*> possibleMoves = board.validNeighbors(position->getX(), position->getY()); Point* bestMove = nullptr; double bestScore = numeric_limits<double>::max(); for(Point* move: possibleMoves){ double currentScore = domainHeuristic(enemies, move); if( bestScore > currentScore ){ bestScore = currentScore; bestMove = move; } } if( !possibleMoves.empty() ){ if( randomIntRange(1, 100) > 60 ){ return bestMove; }else{ int randomPos = (unsigned int) randomIntRange(1, possibleMoves.size()) - 1; return possibleMoves.at(randomPos); } }else{ // If the enemy cant return a valid choice it has lost return nullptr; } } /** * Using a domain specific heuristic that should help the algorithm choose a better path * This will primarily be used for simulating moves for the evemies so that they dont loose as easily in the simulations * @param enemies * @param player * @return */ double domainHeuristic(vector<Player>& enemies, Point*& playerPosition){ double heuristic = 0; for(Player e: enemies){ heuristic += abs(e.position->getX() - playerPosition->getX()) + abs(e.position->getY() - playerPosition->getY()); } return heuristic; } }; class ActionTree { public: Point* move; vector<ActionTree*> children; ActionTree* parent = nullptr; float wins = 0, plays = 0; ActionTree(Point* _move, ActionTree* _parent){ move = _move; wins = 0; plays = 0; parent = _parent; } void win(){ wins += 1; plays += 1; if( parent != nullptr){ parent->win(); } } void loss(){ plays += 1; if( parent != nullptr ){ parent->loss(); } } void deleteTree(){ for(ActionTree*& child : children){ child->deleteTree(); } delete this; } double getVariance(){ int totalWins = 0; int total = 0; int rewardSquared = 0; if( parent != nullptr){ for(ActionTree*& child : parent->children){ total += child->plays; totalWins += child->wins; rewardSquared += pow(child->wins/child->plays, 2); } } if( total > 0 ){ return rewardSquared - pow(totalWins/total, 2); }else { return 0; } } double ubc1TunedScore(){ double winPercentage = 0, exploration = 0; // Avoid division by zero if (plays != 0){ winPercentage = wins / plays; if( parent != nullptr ){ exploration = 2 * biasParameter * sqrt( 2*log(parent->plays) / plays ); //exploration = sqrt( (log(parent->plays) / plays) * // min(0.25, // (getVariance() + sqrt(2 * log(parent->plays) / plays) ))); } } // + return avg_payoff + math.sqrt(math.log(number_sampled) / sampled_arm.total) * min(MAX_BERNOULLI_RANDOM_VARIABLE_VARIANCE, variance + math.sqrt(2.0 * math.log(number_sampled) / sampled_arm.total)) return winPercentage + exploration; } /* Get the best child based ubc score: higher is better */ ActionTree* getOptimalChild(Board& board){ ActionTree* bestChild = nullptr; double bestScore = -INFINITY; for(ActionTree*& child : children){ if( !board.isBlocked(child->move) ){ double ubcScore = child->ubc1TunedScore(); if( bestScore < ubcScore){ bestScore = ubcScore; bestChild = child; } } } return bestChild; } ActionTree* getFinalChoiceChild(){ cerr << "Position: " << move->getX() << " " << move->getY() << endl; cerr << "Amount children " << children.size() << endl; ActionTree* bestChild = nullptr; double bestScore = -INFINITY; for(ActionTree*& child : children){ if( child->plays > 0 ){ double score = child->wins / child->plays; if( bestScore < score){ bestScore = score; bestChild = child; } } } return bestChild; } }; class MCTS { ActionTree* rootNode; bool simulateMove(Point*& move, Board board, vector<Player>& enemies, Player player){ if( board.isBlocked(move) ){ return false; }else{ board.setBlocked(move); player.position = move; return playSimulation(board, enemies, player); } } bool playSimulation(Board& board, vector<Player> enemies, Player player){ vector<Player> playerVector = {player}; // Run until we are the only one standing while( !enemies.empty() ){ // The enemies makes the first move for(Player& enemy : enemies){ // Make a random move //Point* move = enemy.getRandomMove(board); Point* move = enemy.getSemiRandomMove(board, playerVector); // Check if the move is a valid one i.e. not nullpointer if ( move == nullptr ){ // Needs to be adjused for more players return true; } // Move the player to the new positon enemy.position = move; // And mark the old one as used board.setBlocked(move); } Point* playerMove = player.getRandomMove(board); if( playerMove == nullptr ){ return false; } player.position = playerMove; board.setBlocked(playerMove); } } public: MCTS(){ rootNode = nullptr; }; Point* getBestChoice(const Board& board, const vector<Player>& enemies, const Player& player){ if( rootNode == nullptr){ rootNode = new ActionTree(player.position, nullptr); } int count = 0; auto begin = std::chrono::steady_clock::now(); //RESETLOOP:while ( int(chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()-begin).count()) < maxDuration ) { count++; RESETLOOP:while ( count++ < 150) { // Start from the rootnode ActionTree* currentNode = rootNode; Board currentBoard = Board(board); vector<Player> currentEnemies = vector<Player>{enemies}; Player currentPlayer = Player(player); while( true ){ // The node has not been visited before, get neighbors as children if( currentNode->plays < 2 ){ vector<ActionTree*> children = {}; // Loop through and add children for(Point*& p: currentBoard.getNeighbors(currentNode->move->getX(), currentNode->move->getY())){ ActionTree* childAction = new ActionTree(p, currentNode); // check if this is a valid move if( simulateMove(p, currentBoard, currentEnemies, currentPlayer) ){ childAction->win(); }else { childAction->loss(); } // We need to add a simulation for each child children.push_back(childAction); } // Add the children to the node currentNode->children = children; // Start again from rootnode goto RESETLOOP; // The node has been visited before }else{ for(Player& e: currentEnemies){ Point* newPosition = e.getRandomMove(currentBoard); e.position = newPosition; // They have lost if( newPosition == nullptr){ currentNode->win(); goto RESETLOOP; }else{ currentBoard.setBlocked(newPosition); } } ActionTree* bestChild = currentNode->getOptimalChild(currentBoard); // if the best child is nullptr, we have lost if( bestChild == nullptr ){ currentNode->loss(); goto RESETLOOP; }else{ currentNode = bestChild; currentBoard.setBlocked(currentNode->move); currentPlayer.position = bestChild->move; } } } } cerr << " Amount in while " << count << endl; // Continue using the branch that we choose -> more simulations will lead to // better result and this will lead to more and more simulations as the game progress. rootNode = rootNode->getFinalChoiceChild(); // We cant do anything, do something just to end the turn if ( rootNode == nullptr){ return new Point(-1, -1); }else{ rootNode->parent = nullptr; return rootNode->move; } }; }; string getDirection(Point* origin, Point* destination){ if( origin->getX() == destination->getX() ){ if( origin->getY() > destination->getY() ){ return "UP"; }else{ return "DOWN"; } }else{ if( origin->getX() > destination->getX() ){ return "LEFT"; }else{ return "RIGHT"; } } } void gameLoop(Board& board, MCTS& mcts){ vector<Player> enemies; Player player; // THE FRIST POSITION IS NOT MARKED AS BLOCKED // game loop while (1) { int N; // total number of players (2 to 4). int P; // your player number (0 to 3). cin >> N >> P; cin.ignore(); for (int i = 0; i < N; i++) { int X0; // starting X coordinate of lightcycle (or -1) int Y0; // starting Y coordinate of lightcycle (or -1) int X1; // starting X coordinate of lightcycle (can be the same as X0 if you play before this player) int Y1; // starting Y coordinate of lightcycle (can be the same as Y0 if you play before this player) cin >> X0 >> Y0 >> X1 >> Y1; cin.ignore(); if( X0 != -1 && Y0 != -1 ){ board.setBlocked(board.getPoint(X0, Y0)); } board.setBlocked(board.getPoint(X1, Y1)); // This player is me if(i == P && enemies.size() != N){ player = Player(board.getPoint(X1, Y1)); }else if( i == P ){ player.position = board.getPoint(X1, Y1); }else{ if (enemies.size() != N){ enemies.push_back(Player(board.getPoint(X1, Y1))); }else { enemies.at(i).position = board.getPoint(X1, Y1); } } } // Write an action using cout. DON'T FORGET THE "<< endl" // To debug: cerr << "Debug messages..." << endl; Point* result = mcts.getBestChoice(board, enemies, player); cerr << "Amount of blocked points " << board.getBlocked().size() << endl; // IF no valid path exists if( result->getX() == -1 ){ cout << "No Move" << endl; }else{ cout << getDirection(player.position, result) << endl; } } } void init(){ for(int x = 0; x < width; x++){ vector<Point*> yVector; for(int y = 0; y < height; y++){ Point* p = new Point(x, y); yVector.push_back(p); } points.push_back(yVector); } } int main() { init(); MCTS mcts = MCTS(); Board board = Board(); if(TESTING){ Player enemy = Player(board.getPoint(10, 10)); vector<Player> enemies = { enemy }; Player player = Player(board.getPoint(15, 15)); for(int i = 0; i < 13; i++){ board.setBlocked(player.position); board.setBlocked(enemy.position); Point* result = mcts.getBestChoice(board, enemies, player); cout << "The best move is: (" << result->getX() << ", " << result->getY() << ")" << std::endl; cout << "Direction: " << getDirection(player.position, result) << " FROM (" << player.position->getX() << ", " << player.position->getY() << ") TO (" << result->getX() << ", " << result->getY() << ")" << std::endl; player.position = result; } }else{ gameLoop(board, mcts); } return 0; }<commit_msg>Added a domain heuristic<commit_after>#include <iostream> #include <vector> #include <unordered_map> #include <random> #include <unordered_set> #include <math.h> #include <chrono> #include <string> using namespace std; // Maximum allowed duration int maxDuration = 98; int heuristicConstant = 1; double biasParameter = 1 / sqrt(2); bool TESTING = true; random_device rseed; mt19937 rgen(rseed()); // mersenne_twister class Player; class Point; class Board; double domainHeuristic(vector<Player>& enemies, Point*& playerPosition); int randomIntRange(int min, int max){ uniform_int_distribution<int> idist(min, max); return idist(rgen); } class Point { int x, y; public: Point(int _x, int _y){ x = _x; y = _y; } Point(){ x = 0; y = 0; } const int getX() const { return x; } const int getY() const { return y; } bool operator==(const Point &other) const { return (x == other.x && y == other.y); } }; namespace std { template <> struct hash<Point> { size_t operator()(const Point& k) const { // Compute individual hash values for two data members and combine them using XOR and bit shifting return ((hash<int>()(k.getX()) ^ (hash<int>()(k.getY()) << 1)) >> 1); } }; } vector<vector<Point*>> points; int width = 30, height = 20; class Board{ unordered_set<Point*> blocked; public: Board(){} Board(const Board& board) : blocked(board.blocked){} void setBlocked(Point* p){ blocked.insert(p); } unordered_set<Point*> getBlocked(){ return blocked; } bool isBlocked(Point* p){ return blocked.find(p) != blocked.end(); } Point* getPoint(int x, int y){ if(x >= 0 && width > x && y >= 0 && height > y){ return points.at(x).at(y); }else{ return nullptr; } } vector<Point*> getNeighbors(int x, int y){ vector<Point*> neighbors; Point* bottom = getPoint(x, y-1); Point* top = getPoint(x, y+1); Point* left = getPoint(x-1, y); Point* right = getPoint(x+1, y); if(top != nullptr){ neighbors.push_back(top); } if(bottom != nullptr){ neighbors.push_back(bottom); } if(left != nullptr){ neighbors.push_back(left); } if(right != nullptr){ neighbors.push_back(right); } return neighbors; } vector<Point*> validNeighbors(int x, int y){ vector<Point*> valid; for(Point*& p : getNeighbors(x, y)){ if( !isBlocked(p) ){ valid.push_back(p); } } return valid; } operator std::string() const { return "Hi"; } }; class Player{ public: Point* position; explicit Player(Point* pos) : position(pos){} Player(const Player& p){ position = p.position; } Player(){} Point* getRandomMove(Board& board){ vector<Point*> possibleMoves = board.validNeighbors(position->getX(), position->getY()); if( !possibleMoves.empty() ){ int randomPos = (unsigned int) randomIntRange(1, possibleMoves.size()) - 1; return possibleMoves.at(randomPos); }else{ // If the enemy cant return a valid choice it has lost return nullptr; } } Point* getSemiRandomMove(Board& board, vector<Player>& enemies){ vector<Point*> possibleMoves = board.validNeighbors(position->getX(), position->getY()); Point* bestMove = nullptr; double bestScore = numeric_limits<double>::max(); for(Point* move: possibleMoves){ double currentScore = domainHeuristic(enemies, move); if( bestScore > currentScore ){ bestScore = currentScore; bestMove = move; } } if( !possibleMoves.empty() ){ if( randomIntRange(1, 100) > 60 ){ return bestMove; }else{ int randomPos = (unsigned int) randomIntRange(1, possibleMoves.size()) - 1; return possibleMoves.at(randomPos); } }else{ // If the enemy cant return a valid choice it has lost return nullptr; } } }; /** * Using a domain specific heuristic that should help the algorithm choose a better path * This will primarily be used for simulating moves for the evemies so that they dont loose as easily in the simulations * @param enemies * @param player * @return */ double domainHeuristic(vector<Player>& enemies, Point*& playerPosition){ double heuristic = 0; for(Player e: enemies){ heuristic += abs(e.position->getX() - playerPosition->getX()) + abs(e.position->getY() - playerPosition->getY()); } return heuristic; } class ActionTree { public: Point* move; vector<ActionTree*> children; ActionTree* parent = nullptr; float wins = 0, plays = 0; ActionTree(Point* _move, ActionTree* _parent){ move = _move; wins = 0; plays = 0; parent = _parent; } void win(){ wins += 1; plays += 1; if( parent != nullptr){ parent->win(); } } void loss(){ plays += 1; if( parent != nullptr ){ parent->loss(); } } void deleteTree(){ for(ActionTree*& child : children){ child->deleteTree(); } delete this; } double getVariance(){ int totalWins = 0; int total = 0; int rewardSquared = 0; if( parent != nullptr){ for(ActionTree*& child : parent->children){ total += child->plays; totalWins += child->wins; rewardSquared += pow(child->wins/child->plays, 2); } } if( total > 0 ){ return rewardSquared - pow(totalWins/total, 2); }else { return 0; } } /** * The algorithm that is used to calculate the best child * @return */ double ubc1TunedScore(vector<Player>& enemies){ double winPercentage = 0, exploration = 0, domain = 0; // Avoid division by zero if (plays != 0){ winPercentage = wins / plays; if( parent != nullptr ){ exploration = 2 * biasParameter * sqrt( 2*log(parent->plays) / plays ) ; } } // Domain specific heuristic domain = domainHeuristic(enemies, move) / (1 + plays); return winPercentage + exploration + domain; } /* Get the best child based ubc score: higher is better */ ActionTree* getOptimalChild(Board& board, vector<Player>& enemies){ ActionTree* bestChild = nullptr; double bestScore = -INFINITY; for(ActionTree*& child : children){ if( !board.isBlocked(child->move) ){ double ubcScore = child->ubc1TunedScore(enemies); if( bestScore < ubcScore){ bestScore = ubcScore; bestChild = child; } } } return bestChild; } ActionTree* getFinalChoiceChild(){ cerr << "Position: " << move->getX() << " " << move->getY() << endl; cerr << "Amount children " << children.size() << endl; ActionTree* bestChild = nullptr; double bestScore = -INFINITY; for(ActionTree*& child : children){ if( child->plays > 0 ){ double score = child->plays; if( bestScore < score){ bestScore = score; bestChild = child; } } } return bestChild; } }; class MCTS { ActionTree* rootNode; bool simulateMove(Point*& move, Board board, vector<Player>& enemies, Player player){ if( board.isBlocked(move) ){ return false; }else{ board.setBlocked(move); player.position = move; return playSimulation(board, enemies, player); } } bool playSimulation(Board& board, vector<Player> enemies, Player player){ vector<Player> playerVector = {player}; // Run until we are the only one standing while( !enemies.empty() ){ // The enemies makes the first move for(Player& enemy : enemies){ // Make a random move //Point* move = enemy.getRandomMove(board); Point* move = enemy.getSemiRandomMove(board, playerVector); // Check if the move is a valid one i.e. not nullpointer if ( move == nullptr ){ // Needs to be adjused for more players return true; } // Move the player to the new positon enemy.position = move; // And mark the old one as used board.setBlocked(move); } Point* playerMove = player.getRandomMove(board); if( playerMove == nullptr ){ return false; } player.position = playerMove; board.setBlocked(playerMove); } } public: MCTS(){ rootNode = nullptr; }; Point* getBestChoice(const Board& board, const vector<Player>& enemies, const Player& player){ if( rootNode == nullptr){ rootNode = new ActionTree(player.position, nullptr); } int count = 0; auto begin = std::chrono::steady_clock::now(); RESETLOOP:while ( (TESTING && count++ < 150) || int(chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()-begin).count()) < maxDuration ) { // Start from the rootnode ActionTree* currentNode = rootNode; Board currentBoard = Board(board); vector<Player> currentEnemies = vector<Player>{enemies}; Player currentPlayer = Player(player); while( true ){ // The node has not been visited before, get neighbors as children if( currentNode->plays < 2 ){ vector<ActionTree*> children = {}; // Loop through and add children for(Point*& p: currentBoard.getNeighbors(currentNode->move->getX(), currentNode->move->getY())){ ActionTree* childAction = new ActionTree(p, currentNode); // check if this is a valid move if( simulateMove(p, currentBoard, currentEnemies, currentPlayer) ){ childAction->win(); }else { childAction->loss(); } // We need to add a simulation for each child children.push_back(childAction); } // Add the children to the node currentNode->children = children; // Start again from rootnode goto RESETLOOP; // The node has been visited before }else{ for(Player& e: currentEnemies){ Point* newPosition = e.getRandomMove(currentBoard); e.position = newPosition; // They have lost if( newPosition == nullptr){ currentNode->win(); goto RESETLOOP; }else{ currentBoard.setBlocked(newPosition); } } ActionTree* bestChild = currentNode->getOptimalChild(currentBoard, currentEnemies); // if the best child is nullptr, we have lost if( bestChild == nullptr ){ currentNode->loss(); goto RESETLOOP; }else{ currentNode = bestChild; currentBoard.setBlocked(currentNode->move); currentPlayer.position = bestChild->move; } } } } cerr << " Amount in while " << count << endl; // Continue using the branch that we choose -> more simulations will lead to // better result and this will lead to more and more simulations as the game progress. rootNode = rootNode->getFinalChoiceChild(); // We cant do anything, do something just to end the turn if ( rootNode == nullptr){ return new Point(-1, -1); }else{ rootNode->parent = nullptr; return rootNode->move; } }; }; string getDirection(Point* origin, Point* destination){ if( origin->getX() == destination->getX() ){ if( origin->getY() > destination->getY() ){ return "UP"; }else{ return "DOWN"; } }else{ if( origin->getX() > destination->getX() ){ return "LEFT"; }else{ return "RIGHT"; } } } void gameLoop(Board& board, MCTS& mcts){ vector<Player> enemies; Player player; // THE FRIST POSITION IS NOT MARKED AS BLOCKED // game loop while (1) { int N; // total number of players (2 to 4). int P; // your player number (0 to 3). cin >> N >> P; cin.ignore(); for (int i = 0; i < N; i++) { int X0; // starting X coordinate of lightcycle (or -1) int Y0; // starting Y coordinate of lightcycle (or -1) int X1; // starting X coordinate of lightcycle (can be the same as X0 if you play before this player) int Y1; // starting Y coordinate of lightcycle (can be the same as Y0 if you play before this player) cin >> X0 >> Y0 >> X1 >> Y1; cin.ignore(); if( X0 != -1 && Y0 != -1 ){ board.setBlocked(board.getPoint(X0, Y0)); } board.setBlocked(board.getPoint(X1, Y1)); // This player is me if(i == P && enemies.size() != N){ player = Player(board.getPoint(X1, Y1)); }else if( i == P ){ player.position = board.getPoint(X1, Y1); }else{ if (enemies.size() != N){ enemies.push_back(Player(board.getPoint(X1, Y1))); }else { enemies.at(i).position = board.getPoint(X1, Y1); } } } // Write an action using cout. DON'T FORGET THE "<< endl" // To debug: cerr << "Debug messages..." << endl; Point* result = mcts.getBestChoice(board, enemies, player); cerr << "Amount of blocked points " << board.getBlocked().size() << endl; // IF no valid path exists if( result->getX() == -1 ){ cout << "No Move" << endl; }else{ cout << getDirection(player.position, result) << endl; } } } void init(){ for(int x = 0; x < width; x++){ vector<Point*> yVector; for(int y = 0; y < height; y++){ Point* p = new Point(x, y); yVector.push_back(p); } points.push_back(yVector); } } int main() { init(); MCTS mcts = MCTS(); Board board = Board(); if(TESTING){ Player enemy = Player(board.getPoint(10, 10)); vector<Player> enemies = { enemy }; Player player = Player(board.getPoint(15, 15)); for(int i = 0; i < 13; i++){ board.setBlocked(player.position); board.setBlocked(enemy.position); Point* result = mcts.getBestChoice(board, enemies, player); cout << "The best move is: (" << result->getX() << ", " << result->getY() << ")" << std::endl; cout << "Direction: " << getDirection(player.position, result) << " FROM (" << player.position->getX() << ", " << player.position->getY() << ") TO (" << result->getX() << ", " << result->getY() << ")" << std::endl; player.position = result; } }else{ gameLoop(board, mcts); } return 0; }<|endoftext|>
<commit_before>#include <iostream> #include <string> #include <fstream> #include "main.h" using namespace std; int atomic_distance (int atom_dist_x, int atom_dist_y, int atom_dist_z); //Defines atomic distance as combination of x, y, z coordinates int main() { string input_file_name; ifstream input_file; //Display prompt for input file name cout << "Please input the name of Gaussian optimization file: "; cin >> input_file_name; //Check that input file opens input_file.open(input_file_name.c_str() ); if (!input_file.is_open() ) { cout << "Error: Unable to open the input file."; return 1; } const string gaussian_output::HEADER_STRING = "OPTIMIZED PARAMETERS"; const string gaussian_output::FOOTER_STRING = "GradGradGradGradGradGradGradGradGradGradGrad"; //Read through the file and for now output the coordinates while (getline(input_file, gaussian_coordinates, FOOTER_STRING)) { if (gaussian_coordinates.find(HEADER_STRING) != string::npos) { cout << gaussian_coordinates << "\n"; } } return 0; } <commit_msg>Revised main.cpp to be compilable<commit_after>#include <iostream> #include <string> #include <fstream> #include "main.h" using namespace std; int atomic_distance (int atom_dist_x, int atom_dist_y, int atom_dist_z); //Defines atomic distance as combination of x, y, z coordinates int main() { ifstream inputfile; string line; string header = "OPTIMIZED PARAMETERS"; //Open the input file and check that it opened inputfile.open("gaussian_opt_file"); if (!inputfile.is_open() ) { cout << "Error: Unable to open the input file."; return 1; } //Search the input file while (getline(inputfile, line)) { if (line.find(header, 0) != string::npos) { cout << "Found: " << header << endl; } } inputfile.close(); return 0; } //const string gaussian_output::HEADER_STRING = "OPTIMIZED PARAMETERS"; //const string gaussian_output::FOOTER_STRING = "GradGradGradGradGradGradGradGradGradGradGrad"; //Read through the file and for now output the coordinates //while (getline(input_file, gaussian_coordinates, FOOTER_STRING)) //{ //if (gaussian_coordinates.find(HEADER_STRING) != string::npos) //{ //cout << gaussian_coordinates << "\n"; //} //} //return 0; //} <|endoftext|>
<commit_before>29dc0e47-2e4f-11e5-b023-28cfe91dbc4b<commit_msg>29e56f54-2e4f-11e5-81c3-28cfe91dbc4b<commit_after>29e56f54-2e4f-11e5-81c3-28cfe91dbc4b<|endoftext|>
<commit_before>41e36805-2d3f-11e5-80dc-c82a142b6f9b<commit_msg>423e8cf5-2d3f-11e5-b0f9-c82a142b6f9b<commit_after>423e8cf5-2d3f-11e5-b0f9-c82a142b6f9b<|endoftext|>
<commit_before>//% Rollup drumkit userspace driver //% Alex Grabovski <hurufu@gmail.com> //% 2014-04-21 //% WTFPL #include <iostream> #include <csignal> #include <unistd.h> #include <libusb.h> #include <jack/jack.h> #include <jack/midiport.h> #define VERSION 0.2 #define DRUMKIT_VENDOR_ID 0x1941 #define DRUMKIT_PRODUCT_ID 0x8021 #define DRUMKIT_WMAXPACKETSIZE 8 #define DRUMKIT_ENDPOINT 1 #define NOF_PADS 6 // Error codes #define SUCCESS 0 #define ERR_ANSWER_LENGTH_MISMATCH 0xff #define ERR_TRANSFER_FAILED 0xfe #define ERR_LIBUSB_SPECIFIC 0xfd #define ERR_JACK_SPECIFIC 0xfc #define ERR_BAD_ARGUMENT 0xfb #define ERR_UNKNOWN 0xfa #define ERR_JACK_SERVER_CLOSED 0xf9 // Program state flags int r = SUCCESS; int status = SUCCESS; int verbatim = 0; bool run = true; struct jack_callback_arg { jack_port_t * output_port; char pad_map[NOF_PADS]; bool pad_states[NOF_PADS]; int loop_buffer; }; libusb_device_handle * open_device(int vendor, int product); static int process(jack_nframes_t nframes, void * arg); void option_handler(int ac, char ** av, jack_callback_arg * drumkit_callback); static void signal_handler(int); void jack_shutdown_handler(void *); int main (int ac, char ** av) { libusb_device_handle * usb_drumkit_handle = NULL; jack_client_t * jack_midi_drum = NULL; const char jack_midi_drum_str[] = "Dreamlink Foldup Drumk Kit"; volatile unsigned char raw[DRUMKIT_WMAXPACKETSIZE]; int transfered; struct jack_callback_arg drumkit_callback; for (int i=0; i < NOF_PADS; i++) drumkit_callback.pad_map[i] = 0x20 + i; drumkit_callback.loop_buffer = 0; option_handler(ac, av, &drumkit_callback); r = libusb_init(NULL); if (r != SUCCESS) { std::cerr << "libusb_init: " << libusb_strerror((enum libusb_error)r) << "\n"; return ERR_LIBUSB_SPECIFIC; } libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_INFO); usb_drumkit_handle = open_device(DRUMKIT_VENDOR_ID, DRUMKIT_PRODUCT_ID); if ( usb_drumkit_handle == NULL ) { std::cerr << "Unable to open drumkit! Probably it isn't connected.\n"; status = ERR_LIBUSB_SPECIFIC; goto usb_exit; } r = libusb_set_auto_detach_kernel_driver(usb_drumkit_handle, 1); if (r != SUCCESS) { std::cerr << "libusb_set_auto_detach_kernel_driver: " << libusb_strerror((enum libusb_error)r) << "\n"; status = ERR_LIBUSB_SPECIFIC; goto usb_close; } r = libusb_claim_interface(usb_drumkit_handle, 0); if (r != SUCCESS) { std::cerr << "libusb_claim_interface: " << libusb_strerror((enum libusb_error)r) << "\n"; status = ERR_LIBUSB_SPECIFIC; goto usb_close; } jack_midi_drum = jack_client_open(jack_midi_drum_str, JackNullOption, NULL); if (jack_midi_drum == NULL) { std::cerr << "Unable to initiate jack client! Is JACK server running?\n"; status = ERR_JACK_SPECIFIC; goto usb_release; } drumkit_callback.output_port = jack_port_register(jack_midi_drum, "out", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0); jack_set_process_callback(jack_midi_drum, process, &drumkit_callback); jack_on_shutdown(jack_midi_drum, jack_shutdown_handler, &r); r = jack_activate(jack_midi_drum); if (r != SUCCESS) { std::cerr << "Cannot activate client --- " << r << "\n"; status = ERR_JACK_SPECIFIC; goto jack_close; } signal(SIGQUIT, signal_handler); signal(SIGHUP, signal_handler); signal(SIGTERM, signal_handler); signal(SIGINT, signal_handler); while(run) { unsigned char p = 0; for(int i = 0; i <= drumkit_callback.loop_buffer; i++) { r = libusb_interrupt_transfer ( usb_drumkit_handle, DRUMKIT_ENDPOINT | LIBUSB_ENDPOINT_IN, (unsigned char*) raw, DRUMKIT_WMAXPACKETSIZE, &transfered, 0 ); if(r >= 0) { if (transfered != DRUMKIT_WMAXPACKETSIZE) { std::cerr << "Answer length mismatch.\n"; status = ERR_ANSWER_LENGTH_MISMATCH; goto jack_deact; } for (int j = 0; j < transfered; j++) p |= raw[j]; } else { std::cerr << libusb_strerror((enum libusb_error)r) << ".\n"; status = ERR_TRANSFER_FAILED; goto jack_deact; } } for (int i = 0; i < NOF_PADS; i++) { drumkit_callback.pad_states[i] = p & 1; p >>= 1; } } jack_deact: if (status != ERR_JACK_SERVER_CLOSED) jack_deactivate(jack_midi_drum); jack_close: if (status != ERR_JACK_SERVER_CLOSED) jack_client_close(jack_midi_drum); usb_release: libusb_release_interface(usb_drumkit_handle, 0); usb_close: libusb_close(usb_drumkit_handle); usb_exit: libusb_exit(NULL); return status; } void option_handler(int ac, char ** av, jack_callback_arg * drumkit_callback) { //FIXME I dont have enough stamina to write getopt, and I don't want getopt // to be larger than actual driver! I have a plan 'bout ultimate™ getopt, // but I don't think I'll make it soon... And yeah next routine is // dnagerous, but I like danger :P. char c; int p_tmp = -1; int n_tmp; while ((c = getopt (ac, av, "Vhv:p:n:b:")) != -1) { switch (c) { case 'V': std::cout << "Verison " << VERSION << std::endl; exit(0); case '?': r = ERR_BAD_ARGUMENT; case 'h': std::cout << "Usage:\n" << "\t-h\t\tOutput this message and exit\n" << "\t-v <level>\tVerbosity level (default 0). Values 1+ are not implemented\n" << "\t-p <number>\tAsign to pad 0..5\n" << "\t-n <note>\tnote in range 0..127\n" << "\t-b <integer>\tSelect size of loop_buffer (default 0)\n"; exit(r); case 'v': verbatim = atoi(optarg); break; case 'p': p_tmp = atoi(optarg); if (p_tmp >= NOF_PADS) exit(ERR_BAD_ARGUMENT); break; case 'n': n_tmp = atoi(optarg); if (n_tmp > 127) exit(ERR_BAD_ARGUMENT); drumkit_callback->pad_map[p_tmp] = n_tmp; break; case 'b': drumkit_callback->loop_buffer = atoi(optarg); break; default: abort(); } } if (verbatim) std::cout << "Selected loop_buffer: " << drumkit_callback->loop_buffer << std::endl; if (p_tmp != -1) { std::cout << "Reassigned mapping:"; for(int q=0; q<NOF_PADS; q++) std::cout << "\tPad" << q << ": " << (int) drumkit_callback->pad_map[q]; std::cout << std::endl; } } static void signal_handler(int sig) { run = false; std::cerr << "Signal " << sig << " received, exiting ...\n"; } void jack_shutdown_handler(void * arg) { //TODO: Generate signal SIGHUP or SIGUSR1. run = false; status = ERR_JACK_SERVER_CLOSED; std::cerr << "JACK server is not running anymore, exiting\n"; } static int process(jack_nframes_t nframes, void * arg) { jack_callback_arg drumkit_callback = *(jack_callback_arg*) arg; void * port_buf = jack_port_get_buffer(drumkit_callback.output_port, nframes); unsigned char * midi_buffer; jack_midi_clear_buffer(port_buf); static bool was_free[6]; for (int i = 0; i < 6; i++) if (drumkit_callback.pad_states[i]) { if (was_free[i]) { was_free[i] = false; midi_buffer = jack_midi_event_reserve(port_buf, 0, 3); midi_buffer[0] = 0x99; midi_buffer[1] = drumkit_callback.pad_map[i]; midi_buffer[2] = 0x7F; } } else { if (!was_free[i]) { was_free[i] = true; midi_buffer = jack_midi_event_reserve(port_buf, 0, 3); midi_buffer[0] = 0x89; midi_buffer[1] = drumkit_callback.pad_map[i]; midi_buffer[2] = 0x00; } } return 0; } libusb_device_handle * open_device(int vendor, int product) { libusb_device ** devices; libusb_device_descriptor desc; libusb_config_descriptor * config; libusb_device_handle * devh; int r; int cnt = libusb_get_device_list(NULL, &devices); if (cnt < 0) { std::cerr << "libusb_get_device_list: " << libusb_strerror((enum libusb_error)cnt) << "\n"; return NULL; } for (int i = 0; i < cnt; i++) { libusb_get_device_descriptor(devices[i], &desc); if (desc.idVendor == vendor && desc.idProduct == product) { if (verbatim) std::cout << "Rollup Drumkit connected!\n" << std::endl; r = libusb_get_config_descriptor(devices[i], 0, &config); if (r < 0) { std::cerr << "libusb_get_config_descriptor: " << libusb_strerror((enum libusb_error)r) << "\n"; return NULL; } r = libusb_open(devices[i], &devh); if (r < 0) { std::cerr << "libusb_open: " << libusb_strerror((enum libusb_error)r) << "\n"; return NULL; } } } libusb_free_device_list(devices, 1); return devh; } <commit_msg>Refactoring<commit_after>//% Rollup drumkit userspace driver //% Alex Grabovski <hurufu@gmail.com> //% 2014-04-21 //% WTFPL #include <iostream> #include <csignal> #include <unistd.h> #include <libusb.h> #include <jack/jack.h> #include <jack/midiport.h> #define VERSION 0.3 #define DRUMKIT_VENDOR_ID 0x1941 #define DRUMKIT_PRODUCT_ID 0x8021 #define DRUMKIT_WMAXPACKETSIZE 8 #define DRUMKIT_ENDPOINT 1 #define NOF_PADS 6 // Error codes #define SUCCESS 0 #define ERR_ANSWER_LENGTH_MISMATCH 0x1f #define ERR_TRANSFER_FAILED 0x1e #define ERR_LIBUSB_SPECIFIC 0x1d #define ERR_JACK_SPECIFIC 0x1c #define ERR_BAD_ARGUMENT 0x1b #define ERR_UNKNOWN 0x1a #define ERR_JACK_SERVER_CLOSED 0x19 // Program state flags int r = SUCCESS; // Is used to temporary hold functions return values int status = SUCCESS; // Overall program status int verbatim = 0; // Verbosity level bool run = true; // Main loop trigger struct jack_callback_arg { jack_port_t * output_port; char pad_map[NOF_PADS]; bool pad_states[NOF_PADS]; int loop_buffer; }; libusb_device_handle * open_device(int vendor, int product); static int process(jack_nframes_t nframes, void * arg); void option_handler(int ac, char ** av, jack_callback_arg * drumkit_callback); static void signal_handler(int); void jack_shutdown_handler(void *); int main (int ac, char ** av) { libusb_device_handle * usb_drumkit_handle = NULL; jack_client_t * jack_midi_drum = NULL; const char jack_midi_drum_str[] = "Dreamlink Foldup Drumk Kit"; volatile unsigned char raw[DRUMKIT_WMAXPACKETSIZE]; int transfered; struct jack_callback_arg drumkit_callback; for (int i=0; i < NOF_PADS; i++) drumkit_callback.pad_map[i] = 0x20 + i; drumkit_callback.loop_buffer = 0; option_handler(ac, av, &drumkit_callback); r = libusb_init(NULL); if (r != SUCCESS) { std::cerr << "ERROR: " << libusb_strerror((enum libusb_error)r) << "\n"; return ERR_LIBUSB_SPECIFIC; } libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_INFO); usb_drumkit_handle = open_device(DRUMKIT_VENDOR_ID, DRUMKIT_PRODUCT_ID); if ( usb_drumkit_handle == NULL ) { std::cerr << "ERROR: Unable to open drumkit! Probably it isn't connected.\n"; status = ERR_LIBUSB_SPECIFIC; goto usb_exit; } r = libusb_set_auto_detach_kernel_driver(usb_drumkit_handle, 1); if (r != SUCCESS) { std::cerr << "ERROR: Could not set auto detach usb kernel driver. " << libusb_strerror((enum libusb_error)r) << "\n"; status = ERR_LIBUSB_SPECIFIC; goto usb_close; } r = libusb_claim_interface(usb_drumkit_handle, 0); if (r != SUCCESS) { std::cerr << "ERROR: Cannot claim interface. " << libusb_strerror((enum libusb_error)r) << "\n"; status = ERR_LIBUSB_SPECIFIC; goto usb_close; } jack_midi_drum = jack_client_open(jack_midi_drum_str, JackNullOption, NULL); if (jack_midi_drum == NULL) { std::cerr << "ERROR: Unable to initiate JACK client! Is JACK server running?\n"; status = ERR_JACK_SPECIFIC; goto usb_release; } drumkit_callback.output_port = jack_port_register(jack_midi_drum, "out", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0); jack_set_process_callback(jack_midi_drum, process, &drumkit_callback); jack_on_shutdown(jack_midi_drum, jack_shutdown_handler, &r); r = jack_activate(jack_midi_drum); if (r != SUCCESS) { std::cerr << "ERROR: Cannot activate JACK client --- " << r << "\n"; status = ERR_JACK_SPECIFIC; goto jack_close; } signal(SIGQUIT, signal_handler); signal(SIGHUP, signal_handler); signal(SIGTERM, signal_handler); signal(SIGINT, signal_handler); while(run) { unsigned char p = 0; for(int i = 0; i <= drumkit_callback.loop_buffer; i++) { r = libusb_interrupt_transfer ( usb_drumkit_handle, DRUMKIT_ENDPOINT | LIBUSB_ENDPOINT_IN, (unsigned char*) raw, DRUMKIT_WMAXPACKETSIZE, &transfered, 0 ); if(r >= 0) { if (transfered != DRUMKIT_WMAXPACKETSIZE) { std::cerr << "ERROR: Answer length mismatch.\n"; status = ERR_ANSWER_LENGTH_MISMATCH; goto jack_deact; } for (int j = 0; j < transfered; j++) p |= raw[j]; } else { std::cerr << "ERROR: " << libusb_strerror((enum libusb_error)r) << ".\n"; status = ERR_TRANSFER_FAILED; goto jack_deact; } } for (int i = 0; i < NOF_PADS; i++) { drumkit_callback.pad_states[i] = p & 1; p >>= 1; } } jack_deact: if (status != ERR_JACK_SERVER_CLOSED) jack_deactivate(jack_midi_drum); jack_close: if (status != ERR_JACK_SERVER_CLOSED) jack_client_close(jack_midi_drum); usb_release: libusb_release_interface(usb_drumkit_handle, 0); usb_close: libusb_close(usb_drumkit_handle); usb_exit: libusb_exit(NULL); return status; } void option_handler(int ac, char ** av, jack_callback_arg * drumkit_callback) { //FIXME I dont have enough stamina to write getopt, and I don't want getopt // to be larger than actual driver! I have a plan 'bout ultimate™ getopt, // but I don't think I'll make it soon... And yeah next routine is // dnagerous, but I like danger :P. char c; int p_tmp = -1; int n_tmp; while ((c = getopt (ac, av, "Vhv:p:n:b:")) != -1) { switch (c) { case 'V': std::cout << "Verison " << VERSION << std::endl; exit(0); case '?': r = ERR_BAD_ARGUMENT; case 'h': std::cout << "Usage:\n" << "\t-h\t\tOutput this message and exit\n" << "\t-v <level>\tVerbosity level (default 0). Values 1+ are not implemented\n" << "\t-p <number>\tAsign to pad 0..5\n" << "\t-n <note>\tnote in range 0..127\n" << "\t-b <integer>\tSelect size of loop buffer (default 0)\n"; exit(r); case 'v': verbatim = atoi(optarg); break; case 'p': p_tmp = atoi(optarg); if (p_tmp >= NOF_PADS) exit(ERR_BAD_ARGUMENT); break; case 'n': n_tmp = atoi(optarg); if (n_tmp > 127) exit(ERR_BAD_ARGUMENT); drumkit_callback->pad_map[p_tmp] = n_tmp; break; case 'b': drumkit_callback->loop_buffer = atoi(optarg); break; default: abort(); } } if (verbatim) std::cout << "INFO: Selected loop buffer size: " << drumkit_callback->loop_buffer << std::endl; if (p_tmp != -1) { std::cout << "INFO: Reassigned mapping:"; for(int q=0; q<NOF_PADS; q++) std::cout << "\tPad" << q << ": " << (int) drumkit_callback->pad_map[q]; std::cout << std::endl; } } static void signal_handler(int sig) { run = false; std::cerr << "Signal " << sig << " received, exiting ...\n"; } void jack_shutdown_handler(void * arg) { //TODO: Generate signal SIGHUP or SIGUSR1. run = false; status = ERR_JACK_SERVER_CLOSED; std::cerr << "ERROR: JACK server is not running anymore, exiting\n"; } static int process(jack_nframes_t nframes, void * arg) { jack_callback_arg drumkit_callback = *(jack_callback_arg*) arg; void * port_buf = jack_port_get_buffer(drumkit_callback.output_port, nframes); unsigned char * midi_buffer; jack_midi_clear_buffer(port_buf); static bool was_free[6]; for (int i = 0; i < 6; i++) if (drumkit_callback.pad_states[i]) { if (was_free[i]) { was_free[i] = false; midi_buffer = jack_midi_event_reserve(port_buf, 0, 3); midi_buffer[0] = 0x99; midi_buffer[1] = drumkit_callback.pad_map[i]; midi_buffer[2] = 0x7F; } } else { if (!was_free[i]) { was_free[i] = true; midi_buffer = jack_midi_event_reserve(port_buf, 0, 3); midi_buffer[0] = 0x89; midi_buffer[1] = drumkit_callback.pad_map[i]; midi_buffer[2] = 0x00; } } return 0; } libusb_device_handle * open_device(int vendor, int product) { libusb_device ** devices; libusb_device_descriptor desc; libusb_config_descriptor * config; libusb_device_handle * devh; int r; int cnt = libusb_get_device_list(NULL, &devices); if (cnt < 0) { std::cerr << "ERROR: Cannot get usb devices list." << libusb_strerror((enum libusb_error)cnt) << "\n"; return NULL; } for (int i = 0; i < cnt; i++) { libusb_get_device_descriptor(devices[i], &desc); if (desc.idVendor == vendor && desc.idProduct == product) { if (verbatim) std::cout << "INFO: Rollup Drumkit connected.\n" << std::endl; r = libusb_get_config_descriptor(devices[i], 0, &config); if (r < 0) { std::cerr << "ERROR: Cannot get config descriptor. " << libusb_strerror((enum libusb_error)r) << "\n"; return NULL; } r = libusb_open(devices[i], &devh); if (r < 0) { std::cerr << "ERROR: Cannot open usb device. " << libusb_strerror((enum libusb_error)r) << "\n"; return NULL; } } } libusb_free_device_list(devices, 1); return devh; } <|endoftext|>
<commit_before>76ef441e-ad5a-11e7-9409-ac87a332f658<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>779be175-ad5a-11e7-a4bc-ac87a332f658<|endoftext|>
<commit_before>f9c8e4c8-585a-11e5-9e60-6c40088e03e4<commit_msg>f9cf62e4-585a-11e5-9fa6-6c40088e03e4<commit_after>f9cf62e4-585a-11e5-9fa6-6c40088e03e4<|endoftext|>
<commit_before>e45c235c-585a-11e5-950f-6c40088e03e4<commit_msg>e4634c22-585a-11e5-ba8f-6c40088e03e4<commit_after>e4634c22-585a-11e5-ba8f-6c40088e03e4<|endoftext|>
<commit_before>d24eeab8-313a-11e5-9f66-3c15c2e10482<commit_msg>d254b29c-313a-11e5-ad08-3c15c2e10482<commit_after>d254b29c-313a-11e5-ad08-3c15c2e10482<|endoftext|>
<commit_before>283d994c-2f67-11e5-91b7-6c40088e03e4<commit_msg>28459540-2f67-11e5-bcd4-6c40088e03e4<commit_after>28459540-2f67-11e5-bcd4-6c40088e03e4<|endoftext|>
<commit_before>#include <bitset> #include <iomanip> #include <iostream> #ifndef FLOAT_VAL #define FLOAT_VAL 0xc32d3be7 // -173.234 //#define FLOAT_VAL 0x00000000 // +0 //#define FLOAT_VAL 0x80000000 // -0 //#define FLOAT_VAL 0x7f800000 // +inf //#define FLOAT_VAL 0xff800000 // -inf //#define FLOAT_VAL 0xffc20200 // NaN #endif namespace { // anonymous // sign * 2^exponent * mantissa static const uint8_t sign_bits = 1; static const uint8_t exponent_bits = 8; static const uint8_t mantissa_bits = 23; // SEEEEEEE EMMMMMMM MMMMMMMM MMMMMMMM // 00 7F FF FF Mantissa MASK // 80 00 00 00 Sign MASK // 7F 80 00 00 Exponent MASK static const uint32_t sign_mask = 0x80000000; static const uint32_t exponent_mask = 0x7F800000; static const uint32_t mantissa_mask = 0x007FFFFF; static const uint16_t buffer_size = 256; } // end anonymous namespace template <uint32_t sign, uint32_t exponent, uint32_t mantissa> class IEEE_754 { private: enum colour_codes_e { console_red = 31, console_green = 32, console_blue = 34, console_purple = 35, console_default = 39 }; template <colour_codes_e colour> void print_colour(const char* c_str) { std::cout << "\033[" << colour << "m"; std::cout << c_str; std::cout << "\033[" << console_default << "m"; } template <colour_codes_e colour, size_t bitset_size> void print_colour(std::bitset<bitset_size> bitset) { std::cout << "\033[" << colour << "m"; std::cout << bitset; std::cout << "\033[" << console_default << "m"; } void print_int_as_string(uint32_t x) const { while (x != 0) { int rem = x % 10; s_printable_buffer[s_buffer_index++] = (rem > 9) ? (rem - 10) + 'a' : rem + '0'; x = x / 10; } } static char s_printable_buffer[buffer_size]; static unsigned int s_buffer_index; public: constexpr IEEE_754() { if (sign) s_printable_buffer[s_buffer_index++] = '-'; // Exponent is a 2's complement number // exponent has a bias of 127, which we must subtract const int32_t adjusted_exp = static_cast<int32_t>(exponent) - 127; //// Hidden 24th bit is 1 in mantissa const uint32_t full_mantissa = mantissa | (1 << mantissa_bits); const uint32_t adjustment = mantissa_bits - adjusted_exp; uint32_t integer_component = full_mantissa >> adjustment; print_int_as_string(integer_component); s_printable_buffer[s_buffer_index++] = '.'; //// Top of the fraction uint32_t frac = full_mantissa & ((1 << adjustment) - 1); //// Base of the fraction, must be bigger than frac uint32_t base = 1 << adjustment; int decimal_places = 0; const int max_digits_to_print = 12; const int base_10 = 10; while (frac != 0 && decimal_places++ < max_digits_to_print) { frac *= base_10; print_int_as_string(frac / base); frac %= base; } s_printable_buffer[s_buffer_index++] = '\0'; } void print() { print_colour<console_red>("Sign "); print_colour<console_blue>("Exponent "); print_colour<console_green>("Mantissa "); std::cout << std::endl; print_colour<console_red, sign_bits>(std::bitset<sign_bits>(sign)); print_colour<console_blue, exponent_bits>(std::bitset<exponent_bits>(exponent)); print_colour<console_green, mantissa_bits>(std::bitset<mantissa_bits>(mantissa)); std::cout << std::endl; print_colour<console_purple>("Float: "); print_colour<console_purple>(s_printable_buffer); std::cout << std::endl; } }; template <uint32_t sign, uint32_t exponent, uint32_t mantissa> unsigned int IEEE_754<sign, exponent, mantissa>::s_buffer_index = 0; template <uint32_t sign, uint32_t exponent, uint32_t mantissa> char IEEE_754<sign, exponent, mantissa>::s_printable_buffer[buffer_size] = {0}; template <uint32_t sign> class IEEE_754<sign, 0u, 0> { private: enum colour_codes_e { console_red = 31, console_green = 32, console_blue = 34, console_purple = 35, console_default = 39 }; template <colour_codes_e colour> void print_colour(const char* c_str) { std::cout << "\033[" << colour << "m"; std::cout << c_str; std::cout << "\033[" << console_default << "m"; } template <colour_codes_e colour, size_t bitset_size> void print_colour(std::bitset<bitset_size> bitset) { std::cout << "\033[" << colour << "m"; std::cout << bitset; std::cout << "\033[" << console_default << "m"; } public: void print() { print_colour<console_red>("Sign "); print_colour<console_blue>("Exponent "); print_colour<console_green>("Mantissa "); std::cout << std::endl; print_colour<console_red, sign_bits>(std::bitset<sign_bits>(sign)); print_colour<console_blue, exponent_bits>(std::bitset<exponent_bits>(0)); print_colour<console_green, mantissa_bits>(std::bitset<mantissa_bits>(0)); std::cout << std::endl; if (sign) print_colour<console_purple>("Float: -0"); else print_colour<console_purple>("Float: +0"); std::cout << std::endl; } }; template <uint32_t sign> class IEEE_754<sign, 255u, 0u> { private: enum colour_codes_e { console_red = 31, console_green = 32, console_blue = 34, console_purple = 35, console_default = 39 }; template <colour_codes_e colour> void print_colour(const char* c_str) { std::cout << "\033[" << colour << "m"; std::cout << c_str; std::cout << "\033[" << console_default << "m"; } template <colour_codes_e colour, size_t bitset_size> void print_colour(std::bitset<bitset_size> bitset) { std::cout << "\033[" << colour << "m"; std::cout << bitset; std::cout << "\033[" << console_default << "m"; } public: void print() { print_colour<console_red>("Sign "); print_colour<console_blue>("Exponent "); print_colour<console_green>("Mantissa "); std::cout << std::endl; print_colour<console_red, sign_bits>(std::bitset<sign_bits>(sign)); print_colour<console_blue, exponent_bits>(std::bitset<exponent_bits>(255u)); print_colour<console_green, mantissa_bits>(std::bitset<mantissa_bits>(0u)); std::cout << std::endl; if (sign) print_colour<console_purple>("Float: -INF"); else print_colour<console_purple>("Float: +INF"); std::cout << std::endl; } }; template <uint32_t sign, uint32_t mantissa> class IEEE_754<sign, 255u, mantissa> { private: enum colour_codes_e { console_red = 31, console_green = 32, console_blue = 34, console_purple = 35, console_default = 39 }; template <colour_codes_e colour> void print_colour(const char* c_str) { std::cout << "\033[" << colour << "m"; std::cout << c_str; std::cout << "\033[" << console_default << "m"; } template <colour_codes_e colour, size_t bitset_size> void print_colour(std::bitset<bitset_size> bitset) { std::cout << "\033[" << colour << "m"; std::cout << bitset; std::cout << "\033[" << console_default << "m"; } public: void print() { print_colour<console_red>("Sign "); print_colour<console_blue>("Exponent "); print_colour<console_green>("Mantissa "); std::cout << std::endl; print_colour<console_red, sign_bits>(std::bitset<sign_bits>(sign)); print_colour<console_blue, exponent_bits>(std::bitset<exponent_bits>(255u)); print_colour<console_green, mantissa_bits>(std::bitset<mantissa_bits>(mantissa)); std::cout << std::endl; print_colour<console_purple>("Float: NaN"); std::cout << std::endl; } }; int main() { constexpr const uint32_t float_rep = FLOAT_VAL; // Get sign bit const uint32_t sign = (float_rep & sign_mask) >> (32 - sign_bits); // Get 8 exponents bits const uint32_t exponent = (float_rep & exponent_mask) >> mantissa_bits; // Get 23 mantissa bits const uint32_t mantissa = float_rep & mantissa_mask; // Get 23 mantissa bits // Instantiate print helper class IEEE_754<sign, exponent, mantissa> printer; // Print to stdout at runtime printer.print(); return 0; } <commit_msg>remove code duplication for printing<commit_after>#include <bitset> #include <iomanip> #include <iostream> #ifndef FLOAT_VAL #define FLOAT_VAL 0xc32d3be7 // -173.234 //#define FLOAT_VAL 0x00000000 // +0 //#define FLOAT_VAL 0x80000000 // -0 //#define FLOAT_VAL 0x7f800000 // +inf //#define FLOAT_VAL 0xff800000 // -inf //#define FLOAT_VAL 0xffc20200 // NaN #endif namespace { // anonymous // sign * 2^exponent * mantissa static const uint8_t sign_bits = 1; static const uint8_t exponent_bits = 8; static const uint8_t mantissa_bits = 23; // SEEEEEEE EMMMMMMM MMMMMMMM MMMMMMMM // 00 7F FF FF Mantissa MASK // 80 00 00 00 Sign MASK // 7F 80 00 00 Exponent MASK static const uint32_t sign_mask = 0x80000000; static const uint32_t exponent_mask = 0x7F800000; static const uint32_t mantissa_mask = 0x007FFFFF; static const uint16_t buffer_size = 256; enum colour_codes_e { console_red = 31, console_green = 32, console_blue = 34, console_purple = 35, console_default = 39 }; template <colour_codes_e colour> void print_colour(const char* c_str) { std::cout << "\033[" << colour << "m"; std::cout << c_str; std::cout << "\033[" << console_default << "m"; } template <colour_codes_e colour, size_t bitset_size> void print_colour(std::bitset<bitset_size> bitset) { std::cout << "\033[" << colour << "m"; std::cout << bitset; std::cout << "\033[" << console_default << "m"; } } // end anonymous namespace template <uint32_t sign, uint32_t exponent, uint32_t mantissa> class IEEE_754 { private: void print_int_as_string(uint32_t x) const { while (x != 0) { int rem = x % 10; s_printable_buffer[s_buffer_index++] = (rem > 9) ? (rem - 10) + 'a' : rem + '0'; x = x / 10; } } static char s_printable_buffer[buffer_size]; static unsigned int s_buffer_index; public: constexpr IEEE_754() { if (sign) s_printable_buffer[s_buffer_index++] = '-'; // Exponent is a 2's complement number // exponent has a bias of 127, which we must subtract const int32_t adjusted_exp = static_cast<int32_t>(exponent) - 127; //// Hidden 24th bit is 1 in mantissa const uint32_t full_mantissa = mantissa | (1 << mantissa_bits); const uint32_t adjustment = mantissa_bits - adjusted_exp; uint32_t integer_component = full_mantissa >> adjustment; print_int_as_string(integer_component); s_printable_buffer[s_buffer_index++] = '.'; //// Top of the fraction uint32_t frac = full_mantissa & ((1 << adjustment) - 1); //// Base of the fraction, must be bigger than frac uint32_t base = 1 << adjustment; int decimal_places = 0; const int max_digits_to_print = 12; const int base_10 = 10; while (frac != 0 && decimal_places++ < max_digits_to_print) { frac *= base_10; print_int_as_string(frac / base); frac %= base; } s_printable_buffer[s_buffer_index++] = '\0'; } void print() { print_colour<console_red>("Sign "); print_colour<console_blue>("Exponent "); print_colour<console_green>("Mantissa "); std::cout << std::endl; print_colour<console_red, sign_bits>(std::bitset<sign_bits>(sign)); print_colour<console_blue, exponent_bits>(std::bitset<exponent_bits>(exponent)); print_colour<console_green, mantissa_bits>(std::bitset<mantissa_bits>(mantissa)); std::cout << std::endl; print_colour<console_purple>("Float: "); print_colour<console_purple>(s_printable_buffer); std::cout << std::endl; } }; template <uint32_t sign, uint32_t exponent, uint32_t mantissa> unsigned int IEEE_754<sign, exponent, mantissa>::s_buffer_index = 0; template <uint32_t sign, uint32_t exponent, uint32_t mantissa> char IEEE_754<sign, exponent, mantissa>::s_printable_buffer[buffer_size] = {0}; template <uint32_t sign> struct IEEE_754<sign, 0u, 0> { void print() { print_colour<console_red>("Sign "); print_colour<console_blue>("Exponent "); print_colour<console_green>("Mantissa "); std::cout << std::endl; print_colour<console_red, sign_bits>(std::bitset<sign_bits>(sign)); print_colour<console_blue, exponent_bits>(std::bitset<exponent_bits>(0)); print_colour<console_green, mantissa_bits>(std::bitset<mantissa_bits>(0)); std::cout << std::endl; if (sign) print_colour<console_purple>("Float: -0"); else print_colour<console_purple>("Float: +0"); std::cout << std::endl; } }; template <uint32_t sign> struct IEEE_754<sign, 255u, 0u> { void print() { print_colour<console_red>("Sign "); print_colour<console_blue>("Exponent "); print_colour<console_green>("Mantissa "); std::cout << std::endl; print_colour<console_red, sign_bits>(std::bitset<sign_bits>(sign)); print_colour<console_blue, exponent_bits>(std::bitset<exponent_bits>(255u)); print_colour<console_green, mantissa_bits>(std::bitset<mantissa_bits>(0u)); std::cout << std::endl; if (sign) print_colour<console_purple>("Float: -INF"); else print_colour<console_purple>("Float: +INF"); std::cout << std::endl; } }; template <uint32_t sign, uint32_t mantissa> struct IEEE_754<sign, 255u, mantissa> { void print() { print_colour<console_red>("Sign "); print_colour<console_blue>("Exponent "); print_colour<console_green>("Mantissa "); std::cout << std::endl; print_colour<console_red, sign_bits>(std::bitset<sign_bits>(sign)); print_colour<console_blue, exponent_bits>(std::bitset<exponent_bits>(255u)); print_colour<console_green, mantissa_bits>(std::bitset<mantissa_bits>(mantissa)); std::cout << std::endl; print_colour<console_purple>("Float: NaN"); std::cout << std::endl; } }; int main() { constexpr const uint32_t float_rep = FLOAT_VAL; // Get sign bit const uint32_t sign = (float_rep & sign_mask) >> (32 - sign_bits); // Get 8 exponents bits const uint32_t exponent = (float_rep & exponent_mask) >> mantissa_bits; // Get 23 mantissa bits const uint32_t mantissa = float_rep & mantissa_mask; // Get 23 mantissa bits // Instantiate print helper class IEEE_754<sign, exponent, mantissa> printer; // Print to stdout at runtime printer.print(); return 0; } <|endoftext|>
<commit_before>d629739e-327f-11e5-881a-9cf387a8033e<commit_msg>d62fb721-327f-11e5-90cf-9cf387a8033e<commit_after>d62fb721-327f-11e5-90cf-9cf387a8033e<|endoftext|>
<commit_before>2fe7af28-2f67-11e5-98a5-6c40088e03e4<commit_msg>2fee5670-2f67-11e5-b5b9-6c40088e03e4<commit_after>2fee5670-2f67-11e5-b5b9-6c40088e03e4<|endoftext|>
<commit_before>31e642d4-2d3f-11e5-901c-c82a142b6f9b<commit_msg>324e0b1c-2d3f-11e5-b27d-c82a142b6f9b<commit_after>324e0b1c-2d3f-11e5-b27d-c82a142b6f9b<|endoftext|>
<commit_before>809e92b6-2d15-11e5-af21-0401358ea401<commit_msg>809e92b7-2d15-11e5-af21-0401358ea401<commit_after>809e92b7-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>6d8a3761-2e4f-11e5-8202-28cfe91dbc4b<commit_msg>6d90eca3-2e4f-11e5-901e-28cfe91dbc4b<commit_after>6d90eca3-2e4f-11e5-901e-28cfe91dbc4b<|endoftext|>
<commit_before>597f6da1-2e4f-11e5-b268-28cfe91dbc4b<commit_msg>59866ee8-2e4f-11e5-a70d-28cfe91dbc4b<commit_after>59866ee8-2e4f-11e5-a70d-28cfe91dbc4b<|endoftext|>
<commit_before>0c46c38a-2f67-11e5-86b8-6c40088e03e4<commit_msg>0c4d70c2-2f67-11e5-b7c6-6c40088e03e4<commit_after>0c4d70c2-2f67-11e5-b7c6-6c40088e03e4<|endoftext|>
<commit_before>8b332598-2d14-11e5-af21-0401358ea401<commit_msg>8b332599-2d14-11e5-af21-0401358ea401<commit_after>8b332599-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>ab160bc6-35ca-11e5-b373-6c40088e03e4<commit_msg>ab1cb300-35ca-11e5-9656-6c40088e03e4<commit_after>ab1cb300-35ca-11e5-9656-6c40088e03e4<|endoftext|>
<commit_before>b98ad542-ad5b-11e7-9f0a-ac87a332f658<commit_msg>bug fix<commit_after>ba3b3b3a-ad5b-11e7-a1df-ac87a332f658<|endoftext|>
<commit_before>ac6d7db8-35ca-11e5-92f1-6c40088e03e4<commit_msg>ac745bba-35ca-11e5-bcec-6c40088e03e4<commit_after>ac745bba-35ca-11e5-bcec-6c40088e03e4<|endoftext|>
<commit_before>66eb7052-5216-11e5-9fa6-6c40088e03e4<commit_msg>66f57ed0-5216-11e5-86c4-6c40088e03e4<commit_after>66f57ed0-5216-11e5-86c4-6c40088e03e4<|endoftext|>
<commit_before>d4f56482-585a-11e5-bc26-6c40088e03e4<commit_msg>d4fe69e2-585a-11e5-9ea7-6c40088e03e4<commit_after>d4fe69e2-585a-11e5-9ea7-6c40088e03e4<|endoftext|>
<commit_before>8431fc1d-2d15-11e5-af21-0401358ea401<commit_msg>8431fc1e-2d15-11e5-af21-0401358ea401<commit_after>8431fc1e-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>62918a00-2d3d-11e5-9828-c82a142b6f9b<commit_msg>6302862b-2d3d-11e5-91e1-c82a142b6f9b<commit_after>6302862b-2d3d-11e5-91e1-c82a142b6f9b<|endoftext|>
<commit_before>0d7cf408-585b-11e5-a023-6c40088e03e4<commit_msg>0d843558-585b-11e5-a222-6c40088e03e4<commit_after>0d843558-585b-11e5-a222-6c40088e03e4<|endoftext|>
<commit_before>#include <iostream> #include <linux/i2c-dev.h> #include <fcntl.h> #include <sys/ioctl.h> #include <unistd.h> #include <string.h> #define CMD 0x80 #define DATA 0x40 using namespace std; const char* i2c_bus; int i2c_bus_handle; uint8_t oled_address; bool configured = false; bool i2c_write_byte(uint8_t reg, uint8_t data) { char buf[2]; buf[0] = reg; buf[1] = data; if(write(i2c_bus_handle, buf, 2) != 2) { cout << "Write to device failed\n"; return false; } return true; } bool i2c_write_bytes(uint8_t reg, const char* data) { int len = sizeof(reg) + strlen(data); void *buf = calloc(1, len); memcpy(buf, &reg, 1); strcat((char*)buf, data); if(write(i2c_bus_handle, buf, len) != len) { cout << "Write to device failed\n"; free(buf); return false; } free(buf); return true; } bool configure_display(const char* bus, uint8_t address) { i2c_bus = bus; oled_address = address; if((i2c_bus_handle = open(i2c_bus, O_RDWR)) < 0) { return false; } else { cout << "Bus access OK\n"; } if (ioctl(i2c_bus_handle, I2C_SLAVE, oled_address) < 0) { return false; } else { cout << "Device access OK\n"; } configured = true; return configured; } bool init_display() { i2c_write_byte(CMD, 0x2a); // **** Set "RE"=1<--->00101010B i2c_write_byte(CMD, 0x71); i2c_write_byte(CMD, 0x5c); i2c_write_byte(CMD, 0x28); i2c_write_byte(CMD, 0x08); i2c_write_byte(CMD, 0x2a); i2c_write_byte(CMD, 0x79); i2c_write_byte(CMD, 0xd5); i2c_write_byte(CMD, 0x70); i2c_write_byte(CMD, 0x78); i2c_write_byte(CMD, 0x08); i2c_write_byte(CMD, 0x06); i2c_write_byte(CMD, 0x2a); i2c_write_byte(CMD, 0x79); i2c_write_byte(CMD, 0x72); i2c_write_byte(CMD, 0x00); i2c_write_byte(CMD, 0xda); i2c_write_byte(CMD, 0x10); i2c_write_byte(CMD, 0x81); // set contrast i2c_write_byte(CMD, 0x50); // contrast level i2c_write_byte(CMD, 0xdb); i2c_write_byte(CMD, 0x30); i2c_write_byte(CMD, 0xdc); i2c_write_byte(CMD, 0x03); i2c_write_byte(CMD, 0x78); i2c_write_byte(CMD, 0x28); i2c_write_byte(CMD, 0x2a); i2c_write_byte(CMD, 0x06); i2c_write_byte(CMD, 0x08); i2c_write_byte(CMD, 0x28); i2c_write_byte(CMD, 0x01); i2c_write_byte(CMD, 0x80); i2c_write_byte(CMD, 0x0c); } int main() { configure_display("/dev/i2c-1", 0x3c); init_display(); i2c_write_bytes(DATA, "Heisann hoppsan!"); return 0; }<commit_msg>Set cursor position<commit_after>#include <iostream> #include <linux/i2c-dev.h> #include <fcntl.h> #include <sys/ioctl.h> #include <unistd.h> #include <string.h> #define CMD 0x80 #define DATA 0x40 using namespace std; const char* i2c_bus; int i2c_bus_handle; uint8_t oled_address; bool configured = false; bool i2c_write_byte(uint8_t reg, uint8_t data) { char buf[2]; buf[0] = reg; buf[1] = data; if(write(i2c_bus_handle, buf, 2) != 2) { cout << "Write to device failed\n"; return false; } return true; } bool i2c_write_bytes(uint8_t reg, const char* data) { int len = sizeof(reg) + strlen(data); void *buf = calloc(1, len); memcpy(buf, &reg, 1); strcat((char*)buf, data); if(write(i2c_bus_handle, buf, len) != len) { cout << "Write to device failed\n"; free(buf); return false; } free(buf); return true; } bool set_cursor_position(uint8_t col, uint8_t row) { int line_offsets[] = { 0x00, // start of line 1 0x20, 0x40, 0x60 // start of line 4 }; return i2c_write_byte(CMD, 0x80 | (col + line_offsets[row])); } bool configure_display(const char* bus, uint8_t address) { i2c_bus = bus; oled_address = address; if((i2c_bus_handle = open(i2c_bus, O_RDWR)) < 0) { return false; } else { cout << "Bus access OK\n"; } if (ioctl(i2c_bus_handle, I2C_SLAVE, oled_address) < 0) { return false; } else { cout << "Device access OK\n"; } configured = true; return configured; } bool init_display() { i2c_write_byte(CMD, 0x2a); // **** Set "RE"=1<--->00101010B i2c_write_byte(CMD, 0x71); i2c_write_byte(CMD, 0x5c); i2c_write_byte(CMD, 0x28); i2c_write_byte(CMD, 0x08); // display off i2c_write_byte(CMD, 0x2a); i2c_write_byte(CMD, 0x79); i2c_write_byte(CMD, 0xd5); i2c_write_byte(CMD, 0x70); i2c_write_byte(CMD, 0x78); i2c_write_byte(CMD, 0x09); i2c_write_byte(CMD, 0x06); i2c_write_byte(CMD, 0x72); i2c_write_byte(DATA, 0x00); i2c_write_byte(CMD, 0x2a); i2c_write_byte(CMD, 0x79); i2c_write_byte(CMD, 0xda); i2c_write_byte(CMD, 0x10); i2c_write_byte(CMD, 0xdc); i2c_write_byte(CMD, 0x00); i2c_write_byte(CMD, 0x81); // set contrast i2c_write_byte(CMD, 0x50); // contrast level i2c_write_byte(CMD, 0xdb); i2c_write_byte(CMD, 0x30); i2c_write_byte(CMD, 0xdc); i2c_write_byte(CMD, 0x03); i2c_write_byte(CMD, 0x78); i2c_write_byte(CMD, 0x28); i2c_write_byte(CMD, 0x2a); i2c_write_byte(CMD, 0x06); i2c_write_byte(CMD, 0x28); i2c_write_byte(CMD, 0x01); i2c_write_byte(CMD, 0x80); i2c_write_byte(CMD, 0x0c); } int main() { configure_display("/dev/i2c-1", 0x3c); init_display(); set_cursor_position(4, 2); i2c_write_bytes(DATA, "Heisann hoppsan!"); return 0; }<|endoftext|>
<commit_before>aaacc97a-ad58-11e7-a25a-ac87a332f658<commit_msg>The previous fix has been fixed<commit_after>ab288c6b-ad58-11e7-b51d-ac87a332f658<|endoftext|>
<commit_before>2181e69a-2e3a-11e5-89c4-c03896053bdd<commit_msg>2198a736-2e3a-11e5-9a1d-c03896053bdd<commit_after>2198a736-2e3a-11e5-9a1d-c03896053bdd<|endoftext|>
<commit_before>6337e558-5216-11e5-b1aa-6c40088e03e4<commit_msg>633ef4c6-5216-11e5-9811-6c40088e03e4<commit_after>633ef4c6-5216-11e5-9811-6c40088e03e4<|endoftext|>
<commit_before>e658f628-2d3d-11e5-9c1e-c82a142b6f9b<commit_msg>e6e8f57a-2d3d-11e5-98d8-c82a142b6f9b<commit_after>e6e8f57a-2d3d-11e5-98d8-c82a142b6f9b<|endoftext|>
<commit_before>9bf5067d-2e4f-11e5-8d08-28cfe91dbc4b<commit_msg>9bfc0723-2e4f-11e5-a365-28cfe91dbc4b<commit_after>9bfc0723-2e4f-11e5-a365-28cfe91dbc4b<|endoftext|>
<commit_before>f9bd4b87-2d3d-11e5-972f-c82a142b6f9b<commit_msg>fa34961e-2d3d-11e5-bc90-c82a142b6f9b<commit_after>fa34961e-2d3d-11e5-bc90-c82a142b6f9b<|endoftext|>
<commit_before>85627901-2d15-11e5-af21-0401358ea401<commit_msg>85627902-2d15-11e5-af21-0401358ea401<commit_after>85627902-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>5f894927-2d16-11e5-af21-0401358ea401<commit_msg>5f894928-2d16-11e5-af21-0401358ea401<commit_after>5f894928-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>25293036-2f67-11e5-94b9-6c40088e03e4<commit_msg>252fe1a6-2f67-11e5-b72e-6c40088e03e4<commit_after>252fe1a6-2f67-11e5-b72e-6c40088e03e4<|endoftext|>
<commit_before>83000e63-2d15-11e5-af21-0401358ea401<commit_msg>83000e64-2d15-11e5-af21-0401358ea401<commit_after>83000e64-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>77070222-2d53-11e5-baeb-247703a38240<commit_msg>77077f86-2d53-11e5-baeb-247703a38240<commit_after>77077f86-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>d2c06573-2747-11e6-af27-e0f84713e7b8<commit_msg>Gapjgjchguagdmg<commit_after>d2cab1b5-2747-11e6-8a85-e0f84713e7b8<|endoftext|>
<commit_before>/* * Copyright 2013 gtalent2@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string.h> #include "core/core.hpp" #include "models/enginemodels.hpp" #include "tests.hpp" using namespace models; using namespace wombat; int main(int argc, const char **args) { if (core::init(false) != 0) { return 1; } core::Drawer *test = 0; if (argc > 0 && !strcmp(args[1], "test")) { std::vector<std::string> vargs; for (int i = 0; i < argc; i++) { vargs.push_back(args[i]); } tests::test(vargs); } bool running = true; core::addEventListener([&running](core::Event e) { if (e.type == core::Quit) { running = false; } }); while (running) { // draw core::pollEvents(); core::draw(); core::sleep(16); } if (test) delete test; return 0; } <commit_msg>Fixed crashing when run without any arguments.<commit_after>/* * Copyright 2013 gtalent2@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string.h> #include "core/core.hpp" #include "models/enginemodels.hpp" #include "tests.hpp" using namespace models; using namespace wombat; int main(int argc, const char **args) { if (core::init(false) != 0) { return 1; } core::Drawer *test = 0; if (argc > 1 && !strcmp(args[1], "test")) { std::vector<std::string> vargs; for (int i = 0; i < argc; i++) { vargs.push_back(args[i]); } tests::test(vargs); } bool running = true; core::addEventListener([&running](core::Event e) { if (e.type == core::Quit) { running = false; } }); while (running) { // draw core::pollEvents(); core::draw(); core::sleep(16); } if (test) delete test; return 0; } <|endoftext|>
<commit_before>#include <iostream> <commit_msg>main.cpp<commit_after>#include <iostream> using namespace std; int main() { return 0; } <|endoftext|>
<commit_before>58186411-2e4f-11e5-b04a-28cfe91dbc4b<commit_msg>581fe6b0-2e4f-11e5-92c2-28cfe91dbc4b<commit_after>581fe6b0-2e4f-11e5-92c2-28cfe91dbc4b<|endoftext|>
<commit_before>#include <algorithm> #include <cstring> #include <functional> #include <iostream> #include <iterator> #include <string> #include <vector> #include <curl/curl.h> #include "command.h" #include "config.h" #include "dbo_project.h" #include "flags.h" #include "main.h" #include "store_file.h" #include "util.h" static const std::string VERSION = "0.2.0-SNAPSHOT"; static const int INSTALL_DIALOG_LINE_LENGTH = 80; static const int HELP_INDENT_SIZE = 10; Command* const CMD_STORE = new Command("store", "[location]", "Gets or sets the current store location.", &handleStoreCmd); Command* const CMD_INSTALL = new Command("install", "<projects>...", "Installs or upgrades the specified projects to the current store.", &handleInstallCmd); Command* const CMD_UPGRADE = new Command("upgrade", "", "Attempts to upgrade all projects installed to the current store.", &handleUpgradeCmd); Command* const CMD_REMOVE = new Command("remove", "<projects>...", "Removes the specified projects from the current store.", &handleRemoveCmd); Command* const CMD_HELP = new Command("help", "[command]", "Displays help for one or all commands.", &handleHelpCmd); Command* const CMD_MOO = new Command("moo", "", "Have you mooed today?", &handleMooCmd, false); Command* const CMDS[] = {CMD_STORE, CMD_INSTALL, CMD_REMOVE, CMD_UPGRADE, CMD_HELP, CMD_MOO}; static std::vector<RemoteProject*>* const EMPTY_RPP_VEC = new std::vector<RemoteProject*>(0); static std::vector<std::string>* params; int main(int argc, char* argv[]) { if (argc < 2) { err("Too few args!"); print(" Usage: dbo_get <command>"); return 1; } parseParamsAndFlags(argc, argv); char* cmd = argv[1]; for (auto it = std::begin(CMDS); it != std::end(CMDS); ++it) { if (matchCmd(cmd, (*it)->getLabel())) { return (*it)->getHandler()(argc, argv); } } err("Invalid command, try `dbo-get help`."); return 1; } void parseParamsAndFlags(int argc, char* argv[]) { int paramCount = 0; int flagCount = 0; for (int i = 2; i < argc; i++) { if (argv[i][0] == '-') { flagCount += argv[i][1] == '-' ? 1 : std::strlen(argv[i]) - 1; } else { paramCount++; } } params = new std::vector<std::string>(paramCount); std::vector<Flag>* flags = new std::vector<Flag>(flagCount); int p = 0; int f = 0; for (int i = 2; i < argc; i++) { if (argv[i][0] == '-') { if (argv[i][1] == '-') { std::string name = std::string(argv[i] + 2); const Flag* flag = matchFlag(name); if (flag == NULL) { invalidFlag(name); exit(1); } else { (*flags)[f++] = *flag; } } else { for (size_t j = 1; j < std::strlen(argv[i]); j++) { const Flag* flag = matchFlag(argv[i][j]); if (flag == NULL) { invalidFlag(argv[i][j]); exit(1); } else { (*flags)[f++] = *flag; } } } } else { (*params)[p++] = argv[i]; } } setFlags(flags); if (testFlag(Flag::kQuiet) && testFlag(Flag::kVerbose)) { err("Quiet and verbose flags cannot be used in conjunction."); exit(1); } } int handleStoreCmd(int argc, char* argv[]) { if (argc < 3) { std::string* loc = Config::getInstance().get(Config::KEY_STORE); printQ("Current store location: " + (loc == NULL ? "NOT SET" : *loc)); return 0; } std::string path = ""; for (size_t i = 0; i < params->size(); i++) { path += (*params)[i]; if (i < params->size() - 1) { path += " "; } } delete(params); std::replace(path.begin(), path.end(), '\\', '/'); Config::getInstance().set(Config::KEY_STORE, path); makePath(path); printQ("Successfully set store location as \"" + path + "\"."); return 0; } std::vector<RemoteProject*>* resolve(std::vector<std::string>* projects, bool ignoreFail) { printQ("Resolving projects..."); std::vector<RemoteProject*>* vec = new std::vector<RemoteProject*>(projects->size()); bool fail = false; bool empty = true; curl_global_init(CURL_GLOBAL_ALL); bool forceUpdate = testFlag(Flag::kUpdate); for (size_t i = 0; i < projects->size(); i++) { std::string id = (*projects)[i]; print("Resolving project " + id + "..."); RemoteProject* remote = new RemoteProject(id); if (!remote->resolve() && !ignoreFail) { err("Failed to resolve " + id + "."); fail = true; return NULL; } LocalProject* local = StoreFile::getInstance().getProject(id); if (local == NULL || forceUpdate || remote->getVersion() > local->getVersion()) { (*vec)[i] = remote; empty = false; } print("Done resolving " + id + "."); } curl_global_cleanup(); return fail ? NULL : (!empty ? vec : EMPTY_RPP_VEC); } static void printDialogListing(std::vector<std::string> projects) { std::string line = " "; for (size_t i = 0; i < projects.size(); i++) { if (projects[i] == "") { break; } std::string newLine = line + projects[i]; if (line.length() + 1 > INSTALL_DIALOG_LINE_LENGTH) { printQ(line); line = " " + projects[i]; } else { line = newLine + " "; } } printQ(line); } int handleInstallCmd(int argc, char* argv[]) { if (argc < 3) { tooFewArgs(CMD_INSTALL->getLabel(), CMD_INSTALL->getUsage()); return 1; } return install(params, false); } int handleUpgradeCmd(int argc, char* argv[]) { if (argc >= 3) { tooFewArgs(CMD_UPGRADE->getLabel(), CMD_UPGRADE->getUsage()); return 1; } std::vector<std::string>* projects = StoreFile::getInstance().getProjectIds(); return install(projects, true); } int handleRemoveCmd(int argc, char* argv[]) { if (argc < 3) { tooFewArgs(CMD_REMOVE->getLabel(), CMD_REMOVE->getUsage()); return 1; } return remove(params); } int handleHelpCmd(int argc, char* argv[]) { if (argc == 2) { printInfoHeader(); for (auto it = std::begin(CMDS); it != std::end(CMDS); ++it) { if ((*it)->isDocumented()) { printHelp(*it); } } return 0; } else if (argc == 3) { for (auto it = std::begin(CMDS); it != std::end(CMDS); ++it) { if (matchCmd(argv[2], (*it)->getLabel())) { if (!(*it)->isDocumented()) { break; } printHelp(*it); return 0; } } err("Cannot display help: invalid command specified."); return 1; } else { tooManyArgs(CMD_HELP->getLabel(), CMD_HELP->getUsage()); return 1; } } void printInfoHeader() { printQ("dbo-get v" + VERSION + "."); printQ("Copyright (c) 2016 Max Roncace."); printQ(""); printQ("dbo-get is a utility for installing and managing projects hosted by BukkitDev,"); printQ("the premier hosting service for Bukkit software."); printQ(""); printQ("Commands:"); } void printHelp(Command* cmd) { std::string indent = ""; for (int i = cmd->getLabel().length(); i < HELP_INDENT_SIZE; i++) { indent += " "; } printQ(" " + cmd->getLabel() + indent + cmd->getDescription()); std::string indent2 = indent; for (size_t i = 0; i < cmd->getLabel().length() + 4; i++) { indent2 += " "; } printQ(indent2 + "Usage: dbo-get " + cmd->getLabel() + " " + cmd->getUsage()); } int handleMooCmd(int argc, char* argv[]) { int vs = testFlagi(Flag::kVerbose); switch (vs) { case 0: printQ("Yes, you're very clever."); break; case 1: printQ("Hey, what are you doing?"); break; case 2: printQ("Mhm, I get it, haha. Funny."); break; case 3: printQ("You really want this, don't you?"); break; case 4: printQ("Alright, very well."); break; case 5: printArt(); break; case 50: printQ("Someone's been rummaging through the source, mm?"); break; default: printQ("Happy?"); break; } return 0; } int install(std::vector<std::string>* projects, bool ignoreFail) { std::string* loc = Config::getInstance().get(Config::KEY_STORE); if (loc == NULL) { err("Store location is not set; please run store command first."); return 1; } makePath(*loc); std::vector<RemoteProject*>* resolved = resolve(projects, ignoreFail); delete(projects); if (resolved == NULL) { err("No projects specified for installation."); return 1; } if (resolved->empty()) { printQ("Already up-to-date."); return 0; } printInstallDialog(resolved); printQ("Installing projects..."); for (size_t i = 0; i < resolved->size(); i++) { RemoteProject* proj = (*resolved)[i]; if (proj == NULL) { continue; } LocalProject* local = StoreFile::getInstance().getProject(proj->getId()); if (local != NULL) { print("Upgrading project " + proj->getId() + " (#" + std::to_string(local->getVersion()) + " -> #" + std::to_string(proj->getVersion()) + ")."); if (!local->remove() || !proj->install()) { //TODO: this shit ain't atomic return 1; } } else { print("Installing project " + proj->getId() + "..."); if (!proj->install()) { return 1; } } print("Done installing " + proj->getId() + "."); } printQ("Done."); StoreFile::getInstance().save(); return 0; } int remove(std::vector<std::string>* projects) { std::string* loc = Config::getInstance().get(Config::KEY_STORE); if (loc == NULL) { err("Store location is not set; please run store command first."); return 1; } makePath(*loc); printQ("Resolving projects..."); bool fail = false; std::vector<LocalProject> resolved = std::vector<LocalProject>(projects->size()); for (size_t i = 0; i < projects->size(); i++) { std::string id = (*projects)[i]; print("Resolving project " + id + "..."); LocalProject* proj = StoreFile::getInstance().getProject(id); if (proj != NULL) { if (!fail) { resolved[i] = *proj; print("Done resolving " + id + "."); } } else { err("No project with ID " + id + " is currently installed."); fail = true; } } delete(projects); if (fail) { err("No projects specified for removal."); return 1; } printRemoveDialog(&resolved); printQ("Removing projects..."); for (size_t i = 0; i < resolved.size(); i++) { LocalProject proj = resolved[i]; print("Removing project " + proj.getId() + "..."); proj.remove(); print("Done removing " + proj.getId() + "."); } printQ("Done."); StoreFile::getInstance().save(); return 0; } static void printInstallDialog(std::vector<RemoteProject*>* projects) { std::vector<std::string> upgradeList = std::vector<std::string>(projects->size()); std::vector<std::string> installList = std::vector<std::string>(projects->size()); int ui = 0; int ii = 0; int nu = 0; for (size_t i = 0; i < projects->size(); i++) { RemoteProject* remote = (*projects)[i]; if (remote == NULL) { nu++; continue; } LocalProject* local = StoreFile::getInstance().getProject(remote->getId()); if (local != NULL) { upgradeList[ui++] = remote->getId(); } else { installList[ii++] = remote->getId(); } } if (ui > 0) { printQ("The following projects will be upgraded:"); printDialogListing(upgradeList); } if (ii > 0) { printQ("The following projects will be newly installed:"); printDialogListing(installList); } printQ(std::to_string(ui) + " upgraded, " + std::to_string(ii) + " newly installed, 0 to remove, " + std::to_string(nu) + " not upgraded."); } static void printRemoveDialog(std::vector<LocalProject>* projects) { std::vector<std::string> removeList = std::vector<std::string>(projects->size()); for (size_t i = 0; i < projects->size(); i++) { removeList[i] = (*projects)[i].getId(); } printDialogListing(removeList); printQ("0 upgraded, 0 newly installed, " + std::to_string(projects->size()) + " to remove, 0 not upgraded."); } <commit_msg>Add flags to help dialog<commit_after>#include <algorithm> #include <cstring> #include <functional> #include <iostream> #include <iterator> #include <string> #include <vector> #include <curl/curl.h> #include "command.h" #include "config.h" #include "dbo_project.h" #include "flags.h" #include "main.h" #include "store_file.h" #include "util.h" static const std::string VERSION = "0.2.0-SNAPSHOT"; static const int INSTALL_DIALOG_LINE_LENGTH = 80; static const int HELP_CMD_INDENT_SIZE = 10; static const int HELP_FLAG_INDENT_SIZE = 18; Command* const CMD_STORE = new Command("store", "[location]", "Gets or sets the current store location.", &handleStoreCmd); Command* const CMD_INSTALL = new Command("install", "<projects>...", "Installs or upgrades the specified projects to the current store.", &handleInstallCmd); Command* const CMD_UPGRADE = new Command("upgrade", "", "Attempts to upgrade all projects installed to the current store.", &handleUpgradeCmd); Command* const CMD_REMOVE = new Command("remove", "<projects>...", "Removes the specified projects from the current store.", &handleRemoveCmd); Command* const CMD_HELP = new Command("help", "[command]", "Displays help for one or all commands.", &handleHelpCmd); Command* const CMD_MOO = new Command("moo", "", "Have you mooed today?", &handleMooCmd, false); Command* const CMDS[] = {CMD_STORE, CMD_INSTALL, CMD_REMOVE, CMD_UPGRADE, CMD_HELP, CMD_MOO}; static std::vector<RemoteProject*>* const EMPTY_RPP_VEC = new std::vector<RemoteProject*>(0); static std::vector<std::string>* params; int main(int argc, char* argv[]) { if (argc < 2) { err("Too few args!"); print(" Usage: dbo_get <command>"); return 1; } parseParamsAndFlags(argc, argv); char* cmd = argv[1]; for (auto it = std::begin(CMDS); it != std::end(CMDS); ++it) { if (matchCmd(cmd, (*it)->getLabel())) { return (*it)->getHandler()(argc, argv); } } err("Invalid command, try `dbo-get help`."); return 1; } void parseParamsAndFlags(int argc, char* argv[]) { int paramCount = 0; int flagCount = 0; for (int i = 2; i < argc; i++) { if (argv[i][0] == '-') { flagCount += argv[i][1] == '-' ? 1 : std::strlen(argv[i]) - 1; } else { paramCount++; } } params = new std::vector<std::string>(paramCount); std::vector<Flag>* flags = new std::vector<Flag>(flagCount); int p = 0; int f = 0; for (int i = 2; i < argc; i++) { if (argv[i][0] == '-') { if (argv[i][1] == '-') { std::string name = std::string(argv[i] + 2); const Flag* flag = matchFlag(name); if (flag == NULL) { invalidFlag(name); exit(1); } else { (*flags)[f++] = *flag; } } else { for (size_t j = 1; j < std::strlen(argv[i]); j++) { const Flag* flag = matchFlag(argv[i][j]); if (flag == NULL) { invalidFlag(argv[i][j]); exit(1); } else { (*flags)[f++] = *flag; } } } } else { (*params)[p++] = argv[i]; } } setFlags(flags); if (testFlag(Flag::kQuiet) && testFlag(Flag::kVerbose)) { err("Quiet and verbose flags cannot be used in conjunction."); exit(1); } } int handleStoreCmd(int argc, char* argv[]) { if (argc < 3) { std::string* loc = Config::getInstance().get(Config::KEY_STORE); printQ("Current store location: " + (loc == NULL ? "NOT SET" : *loc)); return 0; } std::string path = ""; for (size_t i = 0; i < params->size(); i++) { path += (*params)[i]; if (i < params->size() - 1) { path += " "; } } delete(params); std::replace(path.begin(), path.end(), '\\', '/'); Config::getInstance().set(Config::KEY_STORE, path); makePath(path); printQ("Successfully set store location as \"" + path + "\"."); return 0; } std::vector<RemoteProject*>* resolve(std::vector<std::string>* projects, bool ignoreFail) { printQ("Resolving projects..."); std::vector<RemoteProject*>* vec = new std::vector<RemoteProject*>(projects->size()); bool fail = false; bool empty = true; curl_global_init(CURL_GLOBAL_ALL); bool forceUpdate = testFlag(Flag::kUpdate); for (size_t i = 0; i < projects->size(); i++) { std::string id = (*projects)[i]; print("Resolving project " + id + "..."); RemoteProject* remote = new RemoteProject(id); if (!remote->resolve() && !ignoreFail) { err("Failed to resolve " + id + "."); fail = true; return NULL; } LocalProject* local = StoreFile::getInstance().getProject(id); if (local == NULL || forceUpdate || remote->getVersion() > local->getVersion()) { (*vec)[i] = remote; empty = false; } print("Done resolving " + id + "."); } curl_global_cleanup(); return fail ? NULL : (!empty ? vec : EMPTY_RPP_VEC); } static void printDialogListing(std::vector<std::string> projects) { std::string line = " "; for (size_t i = 0; i < projects.size(); i++) { if (projects[i] == "") { break; } std::string newLine = line + projects[i]; if (line.length() + 1 > INSTALL_DIALOG_LINE_LENGTH) { printQ(line); line = " " + projects[i]; } else { line = newLine + " "; } } printQ(line); } int handleInstallCmd(int argc, char* argv[]) { if (argc < 3) { tooFewArgs(CMD_INSTALL->getLabel(), CMD_INSTALL->getUsage()); return 1; } return install(params, false); } int handleUpgradeCmd(int argc, char* argv[]) { if (argc >= 3) { tooFewArgs(CMD_UPGRADE->getLabel(), CMD_UPGRADE->getUsage()); return 1; } std::vector<std::string>* projects = StoreFile::getInstance().getProjectIds(); return install(projects, true); } int handleRemoveCmd(int argc, char* argv[]) { if (argc < 3) { tooFewArgs(CMD_REMOVE->getLabel(), CMD_REMOVE->getUsage()); return 1; } return remove(params); } void printFlag(std::string name, char shorthand, std::string description) { std::string start = " -" + std::string(&shorthand, 1) + ", --" + name; std::string indent = ""; for (int i = start.length(); i < HELP_FLAG_INDENT_SIZE; i++) { indent += " "; } printQ(start + indent + description); } int handleHelpCmd(int argc, char* argv[]) { if (argc == 2) { printInfoHeader(); printQ("Flags:"); printFlag("force", 'f', "Forces dbo-get to upgrade packages without comparing versions at all."); printFlag("quiet", 'q', "Enables quiet logging and suppresses much of the normal output."); printFlag("verbose", 'v', "Enables verbose logging."); printQ("Commands:"); for (auto it = std::begin(CMDS); it != std::end(CMDS); ++it) { if ((*it)->isDocumented()) { printHelp(*it); } } return 0; } else if (argc == 3) { for (auto it = std::begin(CMDS); it != std::end(CMDS); ++it) { if (matchCmd(argv[2], (*it)->getLabel())) { if (!(*it)->isDocumented()) { break; } printHelp(*it); return 0; } } err("Cannot display help: invalid command specified."); return 1; } else { tooManyArgs(CMD_HELP->getLabel(), CMD_HELP->getUsage()); return 1; } } void printInfoHeader() { printQ("dbo-get v" + VERSION + "."); printQ("Copyright (c) 2016 Max Roncace."); printQ(""); printQ("dbo-get is a utility for installing and managing projects hosted by BukkitDev,"); printQ("the premier hosting service for Bukkit software."); printQ(""); } void printHelp(Command* cmd) { std::string indent = ""; for (int i = cmd->getLabel().length(); i < HELP_CMD_INDENT_SIZE; i++) { indent += " "; } printQ(" " + cmd->getLabel() + indent + cmd->getDescription()); std::string indent2 = indent; for (size_t i = 0; i < cmd->getLabel().length() + 4; i++) { indent2 += " "; } printQ(indent2 + "Usage: dbo-get " + cmd->getLabel() + " " + cmd->getUsage()); } int handleMooCmd(int argc, char* argv[]) { int vs = testFlagi(Flag::kVerbose); switch (vs) { case 0: printQ("Yes, you're very clever."); break; case 1: printQ("Hey, what are you doing?"); break; case 2: printQ("Mhm, I get it, haha. Funny."); break; case 3: printQ("You really want this, don't you?"); break; case 4: printQ("Alright, very well."); break; case 5: printArt(); break; case 50: printQ("Someone's been rummaging through the source, mm?"); break; default: printQ("Happy?"); break; } return 0; } int install(std::vector<std::string>* projects, bool ignoreFail) { std::string* loc = Config::getInstance().get(Config::KEY_STORE); if (loc == NULL) { err("Store location is not set; please run store command first."); return 1; } makePath(*loc); std::vector<RemoteProject*>* resolved = resolve(projects, ignoreFail); delete(projects); if (resolved == NULL) { err("No projects specified for installation."); return 1; } if (resolved->empty()) { printQ("Already up-to-date."); return 0; } printInstallDialog(resolved); printQ("Installing projects..."); for (size_t i = 0; i < resolved->size(); i++) { RemoteProject* proj = (*resolved)[i]; if (proj == NULL) { continue; } LocalProject* local = StoreFile::getInstance().getProject(proj->getId()); if (local != NULL) { print("Upgrading project " + proj->getId() + " (#" + std::to_string(local->getVersion()) + " -> #" + std::to_string(proj->getVersion()) + ")."); if (!local->remove() || !proj->install()) { //TODO: this shit ain't atomic return 1; } } else { print("Installing project " + proj->getId() + "..."); if (!proj->install()) { return 1; } } print("Done installing " + proj->getId() + "."); } printQ("Done."); StoreFile::getInstance().save(); return 0; } int remove(std::vector<std::string>* projects) { std::string* loc = Config::getInstance().get(Config::KEY_STORE); if (loc == NULL) { err("Store location is not set; please run store command first."); return 1; } makePath(*loc); printQ("Resolving projects..."); bool fail = false; std::vector<LocalProject> resolved = std::vector<LocalProject>(projects->size()); for (size_t i = 0; i < projects->size(); i++) { std::string id = (*projects)[i]; print("Resolving project " + id + "..."); LocalProject* proj = StoreFile::getInstance().getProject(id); if (proj != NULL) { if (!fail) { resolved[i] = *proj; print("Done resolving " + id + "."); } } else { err("No project with ID " + id + " is currently installed."); fail = true; } } delete(projects); if (fail) { err("No projects specified for removal."); return 1; } printRemoveDialog(&resolved); printQ("Removing projects..."); for (size_t i = 0; i < resolved.size(); i++) { LocalProject proj = resolved[i]; print("Removing project " + proj.getId() + "..."); proj.remove(); print("Done removing " + proj.getId() + "."); } printQ("Done."); StoreFile::getInstance().save(); return 0; } static void printInstallDialog(std::vector<RemoteProject*>* projects) { std::vector<std::string> upgradeList = std::vector<std::string>(projects->size()); std::vector<std::string> installList = std::vector<std::string>(projects->size()); int ui = 0; int ii = 0; int nu = 0; for (size_t i = 0; i < projects->size(); i++) { RemoteProject* remote = (*projects)[i]; if (remote == NULL) { nu++; continue; } LocalProject* local = StoreFile::getInstance().getProject(remote->getId()); if (local != NULL) { upgradeList[ui++] = remote->getId(); } else { installList[ii++] = remote->getId(); } } if (ui > 0) { printQ("The following projects will be upgraded:"); printDialogListing(upgradeList); } if (ii > 0) { printQ("The following projects will be newly installed:"); printDialogListing(installList); } printQ(std::to_string(ui) + " upgraded, " + std::to_string(ii) + " newly installed, 0 to remove, " + std::to_string(nu) + " not upgraded."); } static void printRemoveDialog(std::vector<LocalProject>* projects) { std::vector<std::string> removeList = std::vector<std::string>(projects->size()); for (size_t i = 0; i < projects->size(); i++) { removeList[i] = (*projects)[i].getId(); } printDialogListing(removeList); printQ("0 upgraded, 0 newly installed, " + std::to_string(projects->size()) + " to remove, 0 not upgraded."); } <|endoftext|>
<commit_before>c3706685-327f-11e5-9d9e-9cf387a8033e<commit_msg>c376454c-327f-11e5-8f30-9cf387a8033e<commit_after>c376454c-327f-11e5-8f30-9cf387a8033e<|endoftext|>
<commit_before>cba4a7a3-327f-11e5-90da-9cf387a8033e<commit_msg>cbae0f38-327f-11e5-8ee7-9cf387a8033e<commit_after>cbae0f38-327f-11e5-8ee7-9cf387a8033e<|endoftext|>
<commit_before>809e9249-2d15-11e5-af21-0401358ea401<commit_msg>809e924a-2d15-11e5-af21-0401358ea401<commit_after>809e924a-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>c97d3a10-35ca-11e5-a1b1-6c40088e03e4<commit_msg>c983b228-35ca-11e5-9d34-6c40088e03e4<commit_after>c983b228-35ca-11e5-9d34-6c40088e03e4<|endoftext|>
<commit_before>ba41a8de-327f-11e5-8448-9cf387a8033e<commit_msg>ba4757ae-327f-11e5-a6a8-9cf387a8033e<commit_after>ba4757ae-327f-11e5-a6a8-9cf387a8033e<|endoftext|>
<commit_before>31513ef6-5216-11e5-93d9-6c40088e03e4<commit_msg>3157ec86-5216-11e5-a374-6c40088e03e4<commit_after>3157ec86-5216-11e5-a374-6c40088e03e4<|endoftext|>
<commit_before>38dfba8c-2e4f-11e5-ac8f-28cfe91dbc4b<commit_msg>38e6c78c-2e4f-11e5-af1f-28cfe91dbc4b<commit_after>38e6c78c-2e4f-11e5-af1f-28cfe91dbc4b<|endoftext|>
<commit_before>7ac70a64-5216-11e5-b2c1-6c40088e03e4<commit_msg>7acda838-5216-11e5-ac56-6c40088e03e4<commit_after>7acda838-5216-11e5-ac56-6c40088e03e4<|endoftext|>
<commit_before>f34f93ae-327f-11e5-9c58-9cf387a8033e<commit_msg>f35563cf-327f-11e5-a396-9cf387a8033e<commit_after>f35563cf-327f-11e5-a396-9cf387a8033e<|endoftext|>
<commit_before>5d2865b6-2d16-11e5-af21-0401358ea401<commit_msg>5d2865b7-2d16-11e5-af21-0401358ea401<commit_after>5d2865b7-2d16-11e5-af21-0401358ea401<|endoftext|>