text
stringlengths
54
60.6k
<commit_before>/************************************************************************* * * $RCSfile: tolayoutanchoredobjectposition.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-03-08 14:02:28 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _TOLAYOUTANCHOREDOBJECTPOSITION_HXX #include <tolayoutanchoredobjectposition.hxx> #endif #ifndef _FRAME_HXX #include <frame.hxx> #endif #ifndef _FLYFRMS_HXX #include <flyfrms.hxx> #endif #ifndef _PAGEFRM_HXX #include <pagefrm.hxx> #endif #ifndef _SVX_SVDOBJ_HXX #include <svx/svdobj.hxx> #endif #ifndef _FRMFMT_HXX #include <frmfmt.hxx> #endif #ifndef _FMTANCHR_HXX #include <fmtanchr.hxx> #endif #ifndef _FMTORNT_HXX #include <fmtornt.hxx> #endif #ifndef _FMTSRND_HXX #include <fmtsrnd.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _FRMATR_HXX #include <frmatr.hxx> #endif #ifndef _SVX_LRSPITEM_HXX #include <svx/lrspitem.hxx> #endif #ifndef _SVX_ULSPITEM_HXX #include <svx/ulspitem.hxx> #endif using namespace objectpositioning; SwToLayoutAnchoredObjectPosition::SwToLayoutAnchoredObjectPosition( SdrObject& _rDrawObj ) : SwAnchoredObjectPosition( _rDrawObj ), maRelPos ( Point() ) {} SwToLayoutAnchoredObjectPosition::~SwToLayoutAnchoredObjectPosition() {} SwFlyLayFrm* SwToLayoutAnchoredObjectPosition::GetFlyLayFrmOfObj() const { ASSERT( !IsObjFly() || ( GetFrmOfObj() && GetFrmOfObj()->ISA(SwFlyLayFrm) ), "SwToLayoutAnchoredObjectPosition::GetFlyLayFrmOfObj() - missing frame for object or wrong frame type" ); SwFlyLayFrm* pRetFlyLayFrm = const_cast<SwFlyLayFrm*>(static_cast<const SwFlyLayFrm*>(GetFrmOfObj())); return pRetFlyLayFrm; } /** calculate position for object position type TO_LAYOUT @author OD */ void SwToLayoutAnchoredObjectPosition::CalcPosition() { const SwRect aObjBoundRect( GetObject().GetCurrentBoundRect() ); SWRECTFN( (&GetAnchorFrm()) ); const SwFrmFmt& rFrmFmt = GetFrmFmt(); const SvxLRSpaceItem &rLR = rFrmFmt.GetLRSpace(); const SvxULSpaceItem &rUL = rFrmFmt.GetULSpace(); const bool bFlyAtFly = FLY_AT_FLY == rFrmFmt.GetAnchor().GetAnchorId(); // determine position. // 'vertical' and 'horizontal' position are calculated separately Point aRelPos; // calculate 'vertical' position SwFmtVertOrient aVert( rFrmFmt.GetVertOrient() ); bool bVertChgd = false; { // to-frame anchored objects are *only* vertical positioned centered or // bottom, if its wrap mode is 'throught' and its anchor frame has fixed // size. Otherwise, it's positioned top. SwVertOrient eVertOrient = aVert.GetVertOrient(); if ( ( bFlyAtFly && ( eVertOrient == VERT_CENTER || eVertOrient == VERT_BOTTOM ) && SURROUND_THROUGHT != rFrmFmt.GetSurround().GetSurround() && !GetAnchorFrm().HasFixSize() ) ) { eVertOrient = VERT_TOP; } SwTwips nRelPosY = _GetVertRelPos( GetAnchorFrm(), GetAnchorFrm(), eVertOrient, aVert.GetRelationOrient(), aVert.GetPos(), rLR, rUL ); // ??? Why saving calculated relative position // keep the calculated relative vertical position if ( aVert.GetVertOrient() == VERT_NONE && aVert.GetPos() != nRelPosY ) { aVert.SetPos( nRelPosY ); bVertChgd = true; } // determine absolute 'vertical' position, depending on layout-direction if( bVert ) { ASSERT( !bRev, "<SwToLayoutAnchoredObjectPosition::CalcPosition()> - reverse layout set." ); aRelPos.X() = -nRelPosY - aObjBoundRect.Width(); } else { aRelPos.Y() = nRelPosY; } // if in online-layout the bottom of to-page anchored object is beyond // the page bottom, the page frame has to grow by growing its body frame. if ( !bFlyAtFly && GetAnchorFrm().IsPageFrm() && rFrmFmt.GetDoc()->IsBrowseMode() ) { const long nAnchorBottom = GetAnchorFrm().Frm().Bottom(); const long nBottom = GetAnchorFrm().Frm().Top() + aRelPos.Y() + aObjBoundRect.Height(); if ( nAnchorBottom < nBottom ) { static_cast<SwPageFrm&>(GetAnchorFrm()). FindBodyCont()->Grow( nBottom - nAnchorBottom ); } } } // end of determination of vertical position // calculate 'horizontal' position SwFmtHoriOrient aHori( rFrmFmt.GetHoriOrient() ); bool bHoriChgd = false; { // consider toggle of horizontal position for even pages. const bool bToggle = aHori.IsPosToggle() && !GetAnchorFrm().FindPageFrm()->OnRightPage(); SwHoriOrient eHoriOrient = aHori.GetHoriOrient(); SwRelationOrient eRelOrient = aHori.GetRelationOrient(); // toggle orientation _ToggleHoriOrientAndAlign( bToggle, eHoriOrient, eRelOrient ); // determine alignment values: // <nWidth>: 'width' of the alignment area // <nOffset>: offset of alignment area, relative to 'left' of anchor frame SwTwips nWidth, nOffset; { bool bDummy; // in this context irrelevant output parameter _GetHoriAlignmentValues( GetAnchorFrm(), GetAnchorFrm(), eRelOrient, false, nWidth, nOffset, bDummy ); } SwTwips nObjWidth = (aObjBoundRect.*fnRect->fnGetWidth)(); // determine relative horizontal position SwTwips nRelPosX; if ( HORI_NONE == eHoriOrient ) { if( bToggle || ( !aHori.IsPosToggle() && GetAnchorFrm().IsRightToLeft() ) ) { nRelPosX = nWidth - nObjWidth - aHori.GetPos(); } else { nRelPosX = aHori.GetPos(); } } else if ( HORI_CENTER == eHoriOrient ) nRelPosX = (nWidth / 2) - (nObjWidth / 2); else if ( HORI_RIGHT == eHoriOrient ) nRelPosX = nWidth - ( nObjWidth + ( bVert ? rUL.GetLower() : rLR.GetRight() ) ); else nRelPosX = bVert ? rUL.GetUpper() : rLR.GetLeft(); nRelPosX += nOffset; // no 'negative' relative horizontal position // OD 06.11.2003 #FollowTextFlowAtFrame# - negative positions allow for // to frame anchored objects. if ( !bFlyAtFly && nRelPosX < 0 ) { nRelPosX = 0; } // determine absolute 'horizontal' position, depending on layout-direction if( bVert ) aRelPos.Y() = nRelPosX; else aRelPos.X() = nRelPosX; // ??? Why saving calculated relative position // keep the calculated relative horizontal position if ( HORI_NONE != aHori.GetHoriOrient() && aHori.GetPos() != nRelPosX ) { aHori.SetPos( nRelPosX ); bHoriChgd = true; } } // end of determination of horizontal position // keep calculate relative position maRelPos = aRelPos; // ??? Why saving calculated relative position // update attributes, if changed { const_cast<SwFrmFmt&>(rFrmFmt).LockModify(); if ( bVertChgd ) const_cast<SwFrmFmt&>(rFrmFmt).SetAttr( aVert ); if ( bHoriChgd ) const_cast<SwFrmFmt&>(rFrmFmt).SetAttr( aHori ); const_cast<SwFrmFmt&>(rFrmFmt).UnlockModify(); } } /** calculated relative position for object position @author OD */ Point SwToLayoutAnchoredObjectPosition::GetRelPos() const { return maRelPos; } <commit_msg>INTEGRATION: CWS qwizards1 (1.2.80); FILE MERGED 2004/04/14 13:54:35 tv 1.2.80.1: Correction - ::CalcPosition() - save new vertical relative position, if vertical position is automatic (TOP, CENTER, BOTTOM) Submitted by: OD<commit_after>/************************************************************************* * * $RCSfile: tolayoutanchoredobjectposition.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2004-05-19 13:35:35 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _TOLAYOUTANCHOREDOBJECTPOSITION_HXX #include <tolayoutanchoredobjectposition.hxx> #endif #ifndef _FRAME_HXX #include <frame.hxx> #endif #ifndef _FLYFRMS_HXX #include <flyfrms.hxx> #endif #ifndef _PAGEFRM_HXX #include <pagefrm.hxx> #endif #ifndef _SVX_SVDOBJ_HXX #include <svx/svdobj.hxx> #endif #ifndef _FRMFMT_HXX #include <frmfmt.hxx> #endif #ifndef _FMTANCHR_HXX #include <fmtanchr.hxx> #endif #ifndef _FMTORNT_HXX #include <fmtornt.hxx> #endif #ifndef _FMTSRND_HXX #include <fmtsrnd.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _FRMATR_HXX #include <frmatr.hxx> #endif #ifndef _SVX_LRSPITEM_HXX #include <svx/lrspitem.hxx> #endif #ifndef _SVX_ULSPITEM_HXX #include <svx/ulspitem.hxx> #endif using namespace objectpositioning; SwToLayoutAnchoredObjectPosition::SwToLayoutAnchoredObjectPosition( SdrObject& _rDrawObj ) : SwAnchoredObjectPosition( _rDrawObj ), maRelPos ( Point() ) {} SwToLayoutAnchoredObjectPosition::~SwToLayoutAnchoredObjectPosition() {} SwFlyLayFrm* SwToLayoutAnchoredObjectPosition::GetFlyLayFrmOfObj() const { ASSERT( !IsObjFly() || ( GetFrmOfObj() && GetFrmOfObj()->ISA(SwFlyLayFrm) ), "SwToLayoutAnchoredObjectPosition::GetFlyLayFrmOfObj() - missing frame for object or wrong frame type" ); SwFlyLayFrm* pRetFlyLayFrm = const_cast<SwFlyLayFrm*>(static_cast<const SwFlyLayFrm*>(GetFrmOfObj())); return pRetFlyLayFrm; } /** calculate position for object position type TO_LAYOUT @author OD */ void SwToLayoutAnchoredObjectPosition::CalcPosition() { const SwRect aObjBoundRect( GetObject().GetCurrentBoundRect() ); SWRECTFN( (&GetAnchorFrm()) ); const SwFrmFmt& rFrmFmt = GetFrmFmt(); const SvxLRSpaceItem &rLR = rFrmFmt.GetLRSpace(); const SvxULSpaceItem &rUL = rFrmFmt.GetULSpace(); const bool bFlyAtFly = FLY_AT_FLY == rFrmFmt.GetAnchor().GetAnchorId(); // determine position. // 'vertical' and 'horizontal' position are calculated separately Point aRelPos; // calculate 'vertical' position SwFmtVertOrient aVert( rFrmFmt.GetVertOrient() ); bool bVertChgd = false; { // to-frame anchored objects are *only* vertical positioned centered or // bottom, if its wrap mode is 'throught' and its anchor frame has fixed // size. Otherwise, it's positioned top. SwVertOrient eVertOrient = aVert.GetVertOrient(); if ( ( bFlyAtFly && ( eVertOrient == VERT_CENTER || eVertOrient == VERT_BOTTOM ) && SURROUND_THROUGHT != rFrmFmt.GetSurround().GetSurround() && !GetAnchorFrm().HasFixSize() ) ) { eVertOrient = VERT_TOP; } SwTwips nRelPosY = _GetVertRelPos( GetAnchorFrm(), GetAnchorFrm(), eVertOrient, aVert.GetRelationOrient(), aVert.GetPos(), rLR, rUL ); // ??? Why saving calculated relative position // keep the calculated relative vertical position if ( aVert.GetVertOrient() != VERT_NONE && aVert.GetPos() != nRelPosY ) { aVert.SetPos( nRelPosY ); bVertChgd = true; } // determine absolute 'vertical' position, depending on layout-direction if( bVert ) { ASSERT( !bRev, "<SwToLayoutAnchoredObjectPosition::CalcPosition()> - reverse layout set." ); aRelPos.X() = -nRelPosY - aObjBoundRect.Width(); } else { aRelPos.Y() = nRelPosY; } // if in online-layout the bottom of to-page anchored object is beyond // the page bottom, the page frame has to grow by growing its body frame. if ( !bFlyAtFly && GetAnchorFrm().IsPageFrm() && rFrmFmt.GetDoc()->IsBrowseMode() ) { const long nAnchorBottom = GetAnchorFrm().Frm().Bottom(); const long nBottom = GetAnchorFrm().Frm().Top() + aRelPos.Y() + aObjBoundRect.Height(); if ( nAnchorBottom < nBottom ) { static_cast<SwPageFrm&>(GetAnchorFrm()). FindBodyCont()->Grow( nBottom - nAnchorBottom ); } } } // end of determination of vertical position // calculate 'horizontal' position SwFmtHoriOrient aHori( rFrmFmt.GetHoriOrient() ); bool bHoriChgd = false; { // consider toggle of horizontal position for even pages. const bool bToggle = aHori.IsPosToggle() && !GetAnchorFrm().FindPageFrm()->OnRightPage(); SwHoriOrient eHoriOrient = aHori.GetHoriOrient(); SwRelationOrient eRelOrient = aHori.GetRelationOrient(); // toggle orientation _ToggleHoriOrientAndAlign( bToggle, eHoriOrient, eRelOrient ); // determine alignment values: // <nWidth>: 'width' of the alignment area // <nOffset>: offset of alignment area, relative to 'left' of anchor frame SwTwips nWidth, nOffset; { bool bDummy; // in this context irrelevant output parameter _GetHoriAlignmentValues( GetAnchorFrm(), GetAnchorFrm(), eRelOrient, false, nWidth, nOffset, bDummy ); } SwTwips nObjWidth = (aObjBoundRect.*fnRect->fnGetWidth)(); // determine relative horizontal position SwTwips nRelPosX; if ( HORI_NONE == eHoriOrient ) { if( bToggle || ( !aHori.IsPosToggle() && GetAnchorFrm().IsRightToLeft() ) ) { nRelPosX = nWidth - nObjWidth - aHori.GetPos(); } else { nRelPosX = aHori.GetPos(); } } else if ( HORI_CENTER == eHoriOrient ) nRelPosX = (nWidth / 2) - (nObjWidth / 2); else if ( HORI_RIGHT == eHoriOrient ) nRelPosX = nWidth - ( nObjWidth + ( bVert ? rUL.GetLower() : rLR.GetRight() ) ); else nRelPosX = bVert ? rUL.GetUpper() : rLR.GetLeft(); nRelPosX += nOffset; // no 'negative' relative horizontal position // OD 06.11.2003 #FollowTextFlowAtFrame# - negative positions allow for // to frame anchored objects. if ( !bFlyAtFly && nRelPosX < 0 ) { nRelPosX = 0; } // determine absolute 'horizontal' position, depending on layout-direction if( bVert ) aRelPos.Y() = nRelPosX; else aRelPos.X() = nRelPosX; // ??? Why saving calculated relative position // keep the calculated relative horizontal position if ( HORI_NONE != aHori.GetHoriOrient() && aHori.GetPos() != nRelPosX ) { aHori.SetPos( nRelPosX ); bHoriChgd = true; } } // end of determination of horizontal position // keep calculate relative position maRelPos = aRelPos; // ??? Why saving calculated relative position // update attributes, if changed { const_cast<SwFrmFmt&>(rFrmFmt).LockModify(); if ( bVertChgd ) const_cast<SwFrmFmt&>(rFrmFmt).SetAttr( aVert ); if ( bHoriChgd ) const_cast<SwFrmFmt&>(rFrmFmt).SetAttr( aHori ); const_cast<SwFrmFmt&>(rFrmFmt).UnlockModify(); } } /** calculated relative position for object position @author OD */ Point SwToLayoutAnchoredObjectPosition::GetRelPos() const { return maRelPos; } <|endoftext|>
<commit_before>#include "consoleui.h" using namespace std; ConsoleUI::ConsoleUI() { } void ConsoleUI::OnlyTakeOneInput() { cin.clear(); fflush(stdin); } void ConsoleUI::run() { bool run = true; while (run) { cout << " ================================" << endl; cout << " Press 1 to list the scientists" << endl; cout << " Press 2 to sort the scientists" << endl; cout << " Press 3 to add a scientist" << endl; cout << " Press 4 to search the list" << endl; cout << " Press 5 to remove a scientist" << endl; cout << " Press 6 to exit" << endl; cout << " ================================" << endl; char input = '0'; cin >> input; OnlyTakeOneInput(); int choice = input - '0'; switch (choice) { case 1: showData(); break; case 2: sortData(); break; case 3: addData(); break; case 4: searchData(); break; case 5: deleteData(); break; case 6: run = false; break; default: cout << "Error! Invalid Input" << endl; } } } void ConsoleUI::addData() { string name; char gender; int birthYear; int deathYear; cout << "Enter name: "; cin >> ws; getline(cin,name); if(!isupper(name[0])) { name[0] = toupper(name[0]); } cout << "Enter gender (M/F): "; cin >> gender; OnlyTakeOneInput(); if(genderCheck(gender) == false) { if(check() == false) { return; } } cout << "Enter birth year: "; cin >> birthYear; OnlyTakeOneInput(); cout << "Enter death year (0 for living person): "; cin >> deathYear; OnlyTakeOneInput(); if(birthChecks(birthYear, deathYear) == false) { check(); // Checks if you want to try to input again. } else { Persons newPerson(name, gender, birthYear, deathYear); serve.add(newPerson); } } bool ConsoleUI::genderCheck(char& gender) { if(gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F') { if(gender == 'm') { gender = 'M'; } if(gender == 'f') { gender = 'F'; } return true; } else { cout << "Wrong input for gender!" << endl; return false; } } bool ConsoleUI::check() { char continuel; cout << "Do you want to try again? (Y for yes and N for No) " ; cin >> continuel; if(continuel == 'Y' || continuel == 'y') { addData(); return true; } else { return false; } } void ConsoleUI::deleteData() { cout << "Enter name of scientist(s) you would like to delete: "; string n = " "; cin >> ws; getline(cin, n); bool d = false; while (!d) { cout << "Are you sure you would like to delete the following scientist(s)? (y/n)\n"; vector<int> v = serve.searchByName(n); int s = v.size(); for (int i = 0; i < s; i++) { cout << serve.list()[v[i]]; } char a = ' '; cin >> a; if (a == 'y' || a == 'Y') { for (int i = s-1; i >= 0; i--) { serve.erase(v[i]); } cout << "Scientist(s) deleted\n"; d = true; } else if (a == 'n' || a == 'N') { cout << "Delete cancelled\n"; d = true; } else { cout << "Invalid input!\n"; } } } bool ConsoleUI::birthChecks(int birthYear, int deathYear) { if(!isdigit(birthYear) && !isdigit(deathYear) && deathYear != 0) { cout << "Please do not input letter" << endl; return false; } if(birthYear < 0 ) { cout << "The scientist can not be born before the year zero." << endl; return false; } if(birthYear > 2016) { cout << "The scientist can not be born after the year 2016" << endl; return false; } if(deathYear < birthYear && deathYear != 0) { cout << "The scientist cannot die before they are born!" << endl; return false; } if(deathYear > 2016 ) { cout << "The scientist is still alive."; return false; } if(deathYear - birthYear > 123) { cout << "That is to old, the oldest woman was 122 years old!" << endl; return false; } return true; } void ConsoleUI::showData() { cout << endl; printLine(); for(size_t i = 0; i < serve.list().size();i++) { cout << serve.list()[i]; } cout << "_____________________________________________________" << endl; } void ConsoleUI::searchData() { bool error = false; do { cout << "How would you like to search the data?" << endl; cout << " =====================================" << endl; cout << " Press 1 to search by name" << endl; cout << " Press 2 to search by birth year" << endl; cout << " Press 3 to search for gender" << endl; cout << " Press 4 to search by birth year range" << endl; cout << " Press 5 to cancel" << endl; cout << " ======================================" << endl; char input = '0'; cin >> input; int choice = input - '0'; switch(choice) { case 1: { string n = " "; cout << "Enter name: "; cin >> ws; getline(cin, n); if(!isupper(n[0])) { n[0] = toupper(n[0]); } vector<int> vN = serve.searchByName(n); if (vN.size() == 0) { cout << "No results found\n"; } else { printLine(); for (unsigned int i = 0; i < vN.size(); i++) { cout << serve.list()[vN[i]]; } } error = false; break; } case 2: { int y = 0; cout << "Enter year: "; cin >> y; vector<int> vY = serve.searchByYear(y); if (vY.size() == 0) { cout << "No results found\n"; } else { printLine(); for (unsigned int i = 0; i < vY.size(); i++) { cout << serve.list()[vY[i]]; } } error = false; break; } case 3: { char gender; cout << "Enter gender (M/F): "; cin >> gender; if(genderCheck(gender) == false) { searchData(); } vector<int> v_g = serve.searchByGender(gender); if (v_g.size() == 0) { cout << "No results found" << endl; } else { printLine(); for (unsigned int i = 0; i < v_g.size(); i++) { cout << serve.list()[v_g[i]]; } } break; } case 4: { int f = 0, l = 0; cout << "Enter first year in range: "; cin >> f; cout << "Enter last year in range: "; cin >> l; vector<int> v_r = serve.searchByRange(f,l); if (v_r.size() == 0) { cout << "No results found" << endl; } else { printLine(); for (unsigned int i = 0; i < v_r.size(); i++) { cout << serve.list()[v_r[i]]; } } break; } case 5: error = false; break; default: { cout << "Error! Invalid input" << endl; error = true; } } } while (error); } void ConsoleUI::sortData() { char input = '0'; int choice = 0; int choice2 = 0; bool error = false; do { cout << "How would you like to sort the list?" << endl; cout << " ================================" << endl; cout << " Press 1 for Name" << endl; cout << " Press 2 for Birth Year" << endl; cout << " Press 3 for Death Year " << endl; cout << " Press 4 for Gender" << endl; cout << " Press 5 to Cancel" << endl; cout << " ================================" << endl; cin >> input; choice = input - '0'; choice2 = 0; input = '1'; switch (choice) { case 1: do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Regular or Reversed sorting?" << endl; cout << " ================================" << endl; cout << "Press 1 for regular sorting" << endl; cout << "Press 2 for reversed sorting" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; } while (input != '1' && input != '2' && input != '3'); choice2 = input - '0'; if (choice2 == 1 || choice2 == 2) { serve.sorting(choice, choice2); error = false; } else { error = true; } break; case 2: do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Regular or Reversed sorting?" << endl; cout << " ================================" << endl; cout << "Press 1 for regular sorting" << endl; cout << "Press 2 for reversed sorting" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; } while (input != '1' && input != '2' && input != '3'); choice2 = input - '0'; if (choice2 == 1 || choice2 == 2) { serve.sorting(choice, choice2); error = false; } else { error = true; } break; case 3: do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Regular or Reversed sorting?" << endl; cout << " ================================" << endl; cout << "Press 1 for regular sorting" << endl; cout << "Press 2 for reversed sorting" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; } while (input != '1' && input != '2' && input != '3'); choice2 = input - '0'; if (choice2 == 1 || choice2 == 2) { serve.sorting(choice, choice2); error = false; } else { error = true; } break; case 4: do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Sort by Males or Females?" << endl; cout << " ================================" << endl; cout << "Press 1 for sorting by females first" << endl; cout << "Press 2 for sorting by males first" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; } while (input != '1' && input != '2' && input != '3'); choice2 = input - '0'; if (choice2 == 1 || choice2 == 2) { serve.sorting(choice, choice2); error = false; } else { error = true; } break; case 5: error = false; break; default: cout << "Error! Invalid input!" << endl; error = true; } } while (error); if (choice != 5) //if you press cancel, you don't want to see the list, do you? { showData(); } } void ConsoleUI::printLine() { cout.width(16); cout << left << "Name"; cout << "\tGender\tBorn\tDied" << endl; cout << "_____________________________________________________" << endl; } <commit_msg>laga aðeins texta i consoleui<commit_after>#include "consoleui.h" using namespace std; ConsoleUI::ConsoleUI() { } void ConsoleUI::OnlyTakeOneInput() { cin.clear(); fflush(stdin); } void ConsoleUI::run() { bool run = true; while (run) { cout << " ================================" << endl; cout << " Press 1 to list the scientists" << endl; cout << " Press 2 to sort the scientists" << endl; cout << " Press 3 to add a scientist" << endl; cout << " Press 4 to search the list" << endl; cout << " Press 5 to remove a scientist" << endl; cout << " Press 6 to exit" << endl; cout << " ================================" << endl; char input = '0'; cin >> input; OnlyTakeOneInput(); int choice = input - '0'; switch (choice) { case 1: showData(); break; case 2: sortData(); break; case 3: addData(); break; case 4: searchData(); break; case 5: deleteData(); break; case 6: run = false; break; default: cout << "Error! Invalid Input" << endl; } } } void ConsoleUI::addData() { string name; char gender; int birthYear; int deathYear; cout << "Enter name: "; cin >> ws; getline(cin,name); if(!isupper(name[0])) { name[0] = toupper(name[0]); } cout << "Enter gender (M/F): "; cin >> gender; OnlyTakeOneInput(); if(genderCheck(gender) == false) { if(check() == false) { return; } } cout << "Enter birth year: "; cin >> birthYear; OnlyTakeOneInput(); cout << "Enter death year (0 for living person): "; cin >> deathYear; OnlyTakeOneInput(); if(birthChecks(birthYear, deathYear) == false) { check(); // Checks if you want to try to input again. } else { Persons newPerson(name, gender, birthYear, deathYear); serve.add(newPerson); } } bool ConsoleUI::genderCheck(char& gender) { if(gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F') { if(gender == 'm') { gender = 'M'; } if(gender == 'f') { gender = 'F'; } return true; } else { cout << "Wrong input for gender!" << endl; return false; } } bool ConsoleUI::check() { char continuel; cout << "Do you want to try again? (Y for yes and N for No) " ; cin >> continuel; if(continuel == 'Y' || continuel == 'y') { addData(); return true; } else { return false; } } void ConsoleUI::deleteData() { cout << "Enter name of scientist(s) you would like to delete: "; string n = " "; cin >> ws; getline(cin, n); bool d = false; while (!d) { cout << "Are you sure you would like to delete the following scientist(s)? (y/n)\n"; vector<int> v = serve.searchByName(n); int s = v.size(); for (int i = 0; i < s; i++) { cout << serve.list()[v[i]]; } char a = ' '; cin >> a; if (a == 'y' || a == 'Y') { for (int i = s-1; i >= 0; i--) { serve.erase(v[i]); } cout << "Scientist(s) deleted\n"; d = true; } else if (a == 'n' || a == 'N') { cout << "Delete cancelled\n"; d = true; } else { cout << "Invalid input!\n"; } } } bool ConsoleUI::birthChecks(int birthYear, int deathYear) { if(!isdigit(birthYear) && !isdigit(deathYear) && deathYear != 0) { cout << "Please do not input letter" << endl; return false; } if(birthYear < 0 ) { cout << "The scientist can not be born before the year zero." << endl; return false; } if(birthYear > 2016) { cout << "The scientist can not be born after the year 2016" << endl; return false; } if(deathYear < birthYear && deathYear != 0) { cout << "The scientist cannot die before they are born!" << endl; return false; } if(deathYear > 2016 ) { cout << "The scientist is still alive."; return false; } if(deathYear - birthYear > 123) { cout << "That is to old, the oldest woman was 122 years old!" << endl; return false; } return true; } void ConsoleUI::showData() { cout << endl; printLine(); for(size_t i = 0; i < serve.list().size();i++) { cout << serve.list()[i]; } cout << "_____________________________________________________" << endl; } void ConsoleUI::searchData() { bool error = false; do { cout << "How would you like to search the data?" << endl; cout << " =====================================" << endl; cout << " Press 1 to search by name" << endl; cout << " Press 2 to search by birth year" << endl; cout << " Press 3 to search for gender" << endl; cout << " Press 4 to search by birth year range" << endl; cout << " Press 5 to cancel" << endl; cout << " ======================================" << endl; char input = '0'; cin >> input; int choice = input - '0'; switch(choice) { case 1: { string n = " "; cout << "Enter name: "; cin >> ws; getline(cin, n); if(!isupper(n[0])) { n[0] = toupper(n[0]); } vector<int> vN = serve.searchByName(n); if (vN.size() == 0) { cout << "No results found\n"; } else { printLine(); for (unsigned int i = 0; i < vN.size(); i++) { cout << serve.list()[vN[i]]; } } error = false; break; } case 2: { int y = 0; cout << "Enter year: "; cin >> y; vector<int> vY = serve.searchByYear(y); if (vY.size() == 0) { cout << "No results found\n"; } else { printLine(); for (unsigned int i = 0; i < vY.size(); i++) { cout << serve.list()[vY[i]]; } } error = false; break; } case 3: { char gender; cout << "Enter gender (M/F): "; cin >> gender; if(genderCheck(gender) == false) { searchData(); } vector<int> v_g = serve.searchByGender(gender); if (v_g.size() == 0) { cout << "No results found" << endl; } else { printLine(); for (unsigned int i = 0; i < v_g.size(); i++) { cout << serve.list()[v_g[i]]; } } break; } case 4: { int f = 0, l = 0; cout << "Enter first year in range: "; cin >> f; cout << "Enter last year in range: "; cin >> l; vector<int> v_r = serve.searchByRange(f,l); if (v_r.size() == 0) { cout << "No results found" << endl; } else { printLine(); for (unsigned int i = 0; i < v_r.size(); i++) { cout << serve.list()[v_r[i]]; } } break; } case 5: error = false; break; default: { cout << "Error! Invalid input" << endl; error = true; } } } while (error); } void ConsoleUI::sortData() { char input = '0'; int choice = 0; int choice2 = 0; bool error = false; do { cout << "How would you like to sort the list?" << endl; cout << " ================================" << endl; cout << " Press 1 for Name" << endl; cout << " Press 2 for Birth Year" << endl; cout << " Press 3 for Death Year " << endl; cout << " Press 4 for Gender" << endl; cout << " Press 5 to Cancel" << endl; cout << " ================================" << endl; cin >> input; choice = input - '0'; choice2 = 0; input = '1'; switch (choice) { case 1: do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Regular or Reversed sorting?" << endl; cout << " ================================" << endl; cout << "Press 1 for regular sorting" << endl; cout << "Press 2 for reversed sorting" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; } while (input != '1' && input != '2' && input != '3'); choice2 = input - '0'; if (choice2 == 1 || choice2 == 2) { serve.sorting(choice, choice2); error = false; } else { error = true; } break; case 2: do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Ascended or Descended sorting?" << endl; cout << " ================================" << endl; cout << "Press 1 to sort by ascending order" << endl; cout << "Press 2 to sort by descending order" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; } while (input != '1' && input != '2' && input != '3'); choice2 = input - '0'; if (choice2 == 1 || choice2 == 2) { serve.sorting(choice, choice2); error = false; } else { error = true; } break; case 3: do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Ascended or Descended sorting?" << endl; cout << " ================================" << endl; cout << "Press 1 to sort by ascending order" << endl; cout << "Press 2 to sort by descending order" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; } while (input != '1' && input != '2' && input != '3'); choice2 = input - '0'; if (choice2 == 1 || choice2 == 2) { serve.sorting(choice, choice2); error = false; } else { error = true; } break; case 4: do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Sort by Males or Females?" << endl; cout << " ================================" << endl; cout << "Press 1 to sort by females first" << endl; cout << "Press 2 to sort by males first" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; } while (input != '1' && input != '2' && input != '3'); choice2 = input - '0'; if (choice2 == 1 || choice2 == 2) { serve.sorting(choice, choice2); error = false; } else { error = true; } break; case 5: error = false; break; default: cout << "Error! Invalid input!" << endl; error = true; } } while (error); if (choice != 5) //if you press cancel, you don't want to see the list, do you? { showData(); } } void ConsoleUI::printLine() { cout.width(16); cout << left << "Name"; cout << "\tGender\tBorn\tDied" << endl; cout << "_____________________________________________________" << endl; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include "consoleui.h" #include "performer.h" using namespace std; ConsoleUI::ConsoleUI() { } // Should not contain logic for individual commands, that should be in separate functions! void ConsoleUI::run() { cout << "Please enter one of the following commands:" << endl; cout << "list - This will list all performers in the system" << endl; cout << "add - This will add a new performer" << endl; cout << "delete - Removes an entry" << endl; cout << "update - Updates an entry" << endl; cout << "search - Searches for a given performer" << endl; string command; cin >> command; if (command == "list") { displayListOfPerformers(); } else if (command == "add") { string name; int age; cin >> name; cin >> age; Performer newPerformer(name, age); // TODO: //_service.addPerformer(newPerformer); } else if (command == "search") { // TODO } else { } } void ConsoleUI::displayListOfPerformers() { vector<Performer> performers = _service.getPerformers(); cout << "Performer name:" << endl; cout << "===============" << endl; for (size_t i = 0; i< performers.size(); ++i) { cout << performers[i].getName() << endl; } } <commit_msg>Testing<commit_after>#include <iostream> #include <string> #include "consoleui.h" #include "performer.h" using namespace std; ConsoleUI::ConsoleUI() { } // Should not contain logic for individual commands, that should be in separate functions! void ConsoleUI::run() { cout << "Please enter one of the following commands:" << endl; cout << "list - This will list all performers in the system" << endl; cout << "add - This will add a new performer" << endl; cout << "delete - This removes an entry" << endl; cout << "update - Updates an entry" << endl; cout << "search - Searches for a given performer" << endl; string command; cin >> command; if (command == "list") { displayListOfPerformers(); } else if (command == "add") { string name; int age; cin >> name; cin >> age; Performer newPerformer(name, age); // TODO: //_service.addPerformer(newPerformer); } else if (command == "search") { // TODO } else { } } void ConsoleUI::displayListOfPerformers() { vector<Performer> performers = _service.getPerformers(); cout << "Performer name:" << endl; cout << "===============" << endl; for (size_t i = 0; i< performers.size(); ++i) { cout << performers[i].getName() << endl; } } <|endoftext|>
<commit_before>#include "controller.h" // Constructor // Allows for Verbose Debugging Mode // @param bool debug_flag, true will enable verbose debugging // @warn assert will end program prematurely // @note axis is rendered in debugging mode Controller::Controller(const int window_width, const int window_height, const bool debug_flag) : // Object construction renderer_(Renderer(debug_flag)), shaders_(renderer_.shaders()), camera_(Camera(shaders_, window_width, window_height)), sun_(Sun(camera(), debug_flag)), light_controller_(new LightController()), collision_controller_(CollisionController()), terrain_(new Terrain(shaders_->LightMappedGeneric)), road_sign_(RoadSign(shaders_, terrain_)), car_(AddObject(shaders_->LightMappedGeneric, "models/Pick-up_Truck/pickup_wind_alpha.obj")), // State and var defaults game_state_(kAutoDrive), light_pos_(glm::vec4(0,0,0,0)), frames_past_(0), frames_count_(0), delta_time_(16), is_debugging_(debug_flag) { is_key_pressed_hash_.reserve(256); is_key_pressed_hash_.resize(256); playSound = 1; rain_ = new Rain(shaders_->RainGeneric, debug_flag); water_ = new Water(shaders_->WaterGeneric); skybox_ = new Skybox(shaders_->SkyboxGeneric); // Add starting models // AddModel(shaders_->LightMappedGeneric, "models/Pick-up_Truck/pickup.obj", true); // AddModel(shaders_->LightMappedGeneric, "models/Car/car-n.obj", true); // AddModel(shaders_->LightMappedGeneric, "models/Signs_OBJ/working/curve_left.obj"); // AddModel(shaders_->LightMappedGeneric, "models/Signs_OBJ/working/curve_right.obj"); // AddModel(shaders_->LightMappedGeneric, "models/Signs_OBJ/working/60.obj"); } // Adds a model to the member vector // @param shader, a shader class holding shader to use and uniforms // @param model_filename, a string containing the path of the .obj file // @warn the model is created on the heap and memory must be freed afterwards Object * Controller::AddObject(const Shader &shader, const std::string &model_filename) { Object * object = new Model(shader, model_filename, glm::vec3(1.12f, 0.55f, 35.0f), // Translation move behind first tile (i.e. start on 2nd tile) glm::vec3(0.0f, 20.0f, 0.0f), // Rotation glm::vec3(0.4f, 0.4f*1.6f, 0.4f), // Scale 60, false); // starting speed and debugging mode return object; } // Renders all models in the vector member // Should be called in the render loop void Controller::Draw() { // Draw to shadow buffer glBindFramebuffer(GL_FRAMEBUFFER, renderer_.fbo()->FrameBufferShadows); glClear(GL_DEPTH_BUFFER_BIT); glViewport(0, 0, renderer_.fbo()->textureX, renderer_.fbo()->textureY); // Car with physics renderer_.RenderDepthBuffer(car_, sun_); // Road-signs const std::vector<Object*> signs = road_sign_.signs(); const std::vector<int> active_signs = road_sign_.active_signs(); // Unfortunately this does not work // for (unsigned int x = 0; x < signs.size(); ++x) { // // if (active_signs[x] >= 0) // no point // renderer_.RenderDepthBuffer(signs[x], sun_); // } // Terrain renderer_.RenderDepthBuffer(terrain_, sun_); // Draw to screen glBindFramebuffer(GL_FRAMEBUFFER, 0); // Bind shadow map texture glBindTexture(GL_TEXTURE_2D, renderer_.fbo()->DepthTexture); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport(0, 0, camera_.width(), camera_.height()); // Ordering of renderering is very important due to transparency renderer_.RenderSkybox(skybox_, camera_); // Water renderer_.RenderWater(water_, car_, skybox_, camera_); // Terrain renderer_.Render(terrain_, camera_, sun_); // Road-signs for (unsigned int x = 0; x < signs.size(); ++x) { // if (active_signs[x] >= 0) // no point renderer_.Render(signs[x], camera_, sun_); } if (camera_.state() == Camera::kFirstPerson) { // Rain (particles) if (sun_.time_of_day() != 12) rain_->Render(camera_, car_, skybox_); // Car with physics renderer_.Render(car_, camera_, sun_); } else { // Car with physics renderer_.Render(car_, camera_, sun_); // Rain (particles) if (sun_.time_of_day() != 12) rain_->Render(camera_, car_, skybox_); } // Axis only renders in debugging mode renderer_.RenderAxis(camera_); } // Assumes SetupLighting() has been called, only updates essential light properties void Controller::PositionLights() { glm::mat4 view_matrix = camera_.view_matrix(); glm::mat4 car_mv_matrix = view_matrix * car_->model_matrix(); // glm::mat3 norm_matrix = glm::mat3(view_matrix); DirectionalLight dirLight; dirLight.DiffuseIntensity = glm::vec3(1.00f, 1.00f, 1.00f); dirLight.AmbientIntensity = glm::vec3(0.50f, 0.50f, 0.50f); dirLight.SpecularIntensity = glm::vec3(0.35f, 0.35f, 0.40f); dirLight.DiffuseIntensity *= sun_.LightIntensityMultiplier(); dirLight.AmbientIntensity *= sun_.LightIntensityMultiplier(); // dirLight.SpecularIntensity *= 1.0f - sun_.LightIntensityMultiplier(); // if (!sun_.IsDay()) { // dirLight.SpecularIntensity.x *= 1.0f - sun_.LightIntensityMultiplier(); // dirLight.SpecularIntensity.y *= 1.0f - sun_.LightIntensityMultiplier(); // } dirLight.Direction = sun_.sun_direction(); // Point lights std::vector<PointLight> pointLights; // Main car brake lights for (unsigned int i = 0; i < 2; i++) { glm::mat4 brakeLightTranslation = glm::translate(glm::mat4(1.0f), glm::vec3(-0.85f + i * 1.7f, 0.0f, -3.3f)); PointLight brakeLight; brakeLight.DiffuseIntensity = glm::vec3(1.0f, 0.0f, 0.0f); brakeLight.Position = glm::vec3(car_mv_matrix * brakeLightTranslation * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)); brakeLight.Attenuation.Constant = 0.001f; brakeLight.Attenuation.Linear = 2.0f; brakeLight.Attenuation.Exp = 3.0f; if (is_key_pressed_hash_.at('s')) { brakeLight.Attenuation.Constant = 0.00001f; brakeLight.Attenuation.Linear = 0.5f; brakeLight.Attenuation.Exp = 3.0f; } pointLights.push_back(brakeLight); } // Spot lights std::vector<SpotLight> spotLights; // Main car headlights for (unsigned int i = 0; i < 2; i++) { glm::mat4 headlightTranslation = glm::translate(glm::mat4(1.0f), glm::vec3(-0.5f + i * 1.0f, 0.0f, 1.45f)); glm::mat3 headlightNormMatrix = glm::mat3(car_mv_matrix); SpotLight headlight; headlight.DiffuseIntensity = glm::vec3(1.0f, 1.0f, 1.0f); headlight.SpecularIntensity = glm::vec3(0.1f, 0.1f, 0.1f); headlight.Position = glm::vec3(car_mv_matrix * headlightTranslation * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)); headlight.Direction = headlightNormMatrix * glm::vec3(0.0f, -0.3f, 1.0f); headlight.CosineCutoff = cos(DEG2RAD(30.0f)); headlight.Attenuation.Constant = 0.3f; headlight.Attenuation.Linear = 0.01f; headlight.Attenuation.Exp = 0.01f; if (is_key_pressed_hash_.at('r')) { headlight.DiffuseIntensity = glm::vec3(0.0f, 0.0f, 0.0f); headlight.SpecularIntensity = glm::vec3(0.0f, 0.0f, 0.0f); } spotLights.push_back(headlight); } light_controller_->SetDirectionalLight(car_->shader()->Id, dirLight); light_controller_->SetSpotLights(water_->shader().Id, spotLights.size(), &spotLights[0]); light_controller_->SetDirectionalLight(water_->shader().Id, dirLight); light_controller_->SetPointLights(car_->shader()->Id, pointLights.size(), &pointLights[0]); light_controller_->SetSpotLights(car_->shader()->Id, spotLights.size(), &spotLights[0]); } // The main control tick // Controls everything: camera, inputs, physics, collisions void Controller::UpdateGame() { // Lights need to be transformed with view/normal matrix PositionLights(); // Update the position of the rain rain_->UpdatePosition(); // FPS counter - also determine delta time long long current_frame = glutGet(GLUT_ELAPSED_TIME); frames_count_ += 1; if ((current_frame - frames_past_) > 1000) { const int fps = frames_count_ * 1000.0f / (current_frame - frames_past_); std::cout << "FPS: " << frames_count_ << std::endl; frames_count_ = 0; frames_past_ = current_frame; // Work out average miliseconds per tick const GLfloat delta_time = 1.0f/fps * 1000.0f; if (abs(delta_time_ - delta_time) < 5) delta_time_ = delta_time; // printf("dt = %f\n",delta_time_); } // Update Sun/Moon position sun_.Update(); // Send time for water water_->SendTime(current_frame); terrain_->GenerationTick(); // printf("mid = (%f,%f,%f)\n",left_lane_midpoint_.x,left_lane_midpoint_.y,left_lane_midpoint_.z); // printf("car = (%f,%f,%f)\n",car_->translation().x,car_->translation().y,car_->translation().z); if (!collision_controller_.is_collision()) { UpdatePhysics(); game_state_ = collision_controller_.UpdateCollisions(car_, terrain_, &camera_, &road_sign_, game_state_); } else { // TODO add car off road shaking } car_->UpdateModelMatrix(); UpdateCamera(); if (game_state_ == kCrashingFall) { // delta_time_ /= 5; //slowmo if(playSound) system("aplay ./sounds/metal_crash.wav -q &"); playSound = 0; game_state_ = collision_controller_.CrashAnimationFall(&camera_, terrain_, car_, delta_time_, is_key_pressed_hash_); return; } if (game_state_ == kCrashingCliff) { // delta_time_ /= 5; //slowmo if(playSound) system("aplay ./sounds/metal_crash.wav -q &"); playSound = 0; game_state_ = collision_controller_.CrashAnimationCliff(&camera_, terrain_, car_, delta_time_, is_key_pressed_hash_); return; } if (is_key_pressed_hash_.at('w') || is_key_pressed_hash_.at('s') || is_key_pressed_hash_.at('a') || is_key_pressed_hash_.at('d')) { game_state_ = kStart; playSound = 1; } } // The controllers camera update tick // Uses car position (for chase and 1st person view) // and checks keypresses for freeview // @warn should be called before car movement void Controller::UpdateCamera() { // CAMERA CONTROLS // Freeview movement camera_.Movement(delta_time_, is_key_pressed_hash_); // Point at car camera_.UpdateCarTick(car_); // Update camera lookAt camera_.UpdateCamera(); } // The controllers physics update tick // Checks keypresses and calculates acceleration void Controller::UpdatePhysics() { if (game_state_ == kStart) { // Sets variables required for camera // i.e. camera has access to car in UpdateCarTick(car_) car_->ControllerMovementTick(delta_time_, is_key_pressed_hash_); } if (game_state_ == kAutoDrive) { collision_controller_.AutoDrive(car_, delta_time_); } } <commit_msg>tweaked car start pos<commit_after>#include "controller.h" // Constructor // Allows for Verbose Debugging Mode // @param bool debug_flag, true will enable verbose debugging // @warn assert will end program prematurely // @note axis is rendered in debugging mode Controller::Controller(const int window_width, const int window_height, const bool debug_flag) : // Object construction renderer_(Renderer(debug_flag)), shaders_(renderer_.shaders()), camera_(Camera(shaders_, window_width, window_height)), sun_(Sun(camera(), debug_flag)), light_controller_(new LightController()), collision_controller_(CollisionController()), terrain_(new Terrain(shaders_->LightMappedGeneric)), road_sign_(RoadSign(shaders_, terrain_)), car_(AddObject(shaders_->LightMappedGeneric, "models/Pick-up_Truck/pickup_wind_alpha.obj")), // State and var defaults game_state_(kAutoDrive), light_pos_(glm::vec4(0,0,0,0)), frames_past_(0), frames_count_(0), delta_time_(16), is_debugging_(debug_flag) { is_key_pressed_hash_.reserve(256); is_key_pressed_hash_.resize(256); playSound = 1; rain_ = new Rain(shaders_->RainGeneric, debug_flag); water_ = new Water(shaders_->WaterGeneric); skybox_ = new Skybox(shaders_->SkyboxGeneric); // Add starting models // AddModel(shaders_->LightMappedGeneric, "models/Pick-up_Truck/pickup.obj", true); // AddModel(shaders_->LightMappedGeneric, "models/Car/car-n.obj", true); // AddModel(shaders_->LightMappedGeneric, "models/Signs_OBJ/working/curve_left.obj"); // AddModel(shaders_->LightMappedGeneric, "models/Signs_OBJ/working/curve_right.obj"); // AddModel(shaders_->LightMappedGeneric, "models/Signs_OBJ/working/60.obj"); } // Adds a model to the member vector // @param shader, a shader class holding shader to use and uniforms // @param model_filename, a string containing the path of the .obj file // @warn the model is created on the heap and memory must be freed afterwards Object * Controller::AddObject(const Shader &shader, const std::string &model_filename) { Object * object = new Model(shader, model_filename, glm::vec3(0.95f, 0.55f, 35.0f), // Translation move behind first tile (i.e. start on 2nd tile) glm::vec3(0.0f, 20.0f, 0.0f), // Rotation glm::vec3(0.4f, 0.4f*1.6f, 0.4f), // Scale 60, false); // starting speed and debugging mode return object; } // Renders all models in the vector member // Should be called in the render loop void Controller::Draw() { // Draw to shadow buffer glBindFramebuffer(GL_FRAMEBUFFER, renderer_.fbo()->FrameBufferShadows); glClear(GL_DEPTH_BUFFER_BIT); glViewport(0, 0, renderer_.fbo()->textureX, renderer_.fbo()->textureY); // Car with physics renderer_.RenderDepthBuffer(car_, sun_); // Road-signs const std::vector<Object*> signs = road_sign_.signs(); const std::vector<int> active_signs = road_sign_.active_signs(); // Unfortunately this does not work // for (unsigned int x = 0; x < signs.size(); ++x) { // // if (active_signs[x] >= 0) // no point // renderer_.RenderDepthBuffer(signs[x], sun_); // } // Terrain renderer_.RenderDepthBuffer(terrain_, sun_); // Draw to screen glBindFramebuffer(GL_FRAMEBUFFER, 0); // Bind shadow map texture glBindTexture(GL_TEXTURE_2D, renderer_.fbo()->DepthTexture); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport(0, 0, camera_.width(), camera_.height()); // Ordering of renderering is very important due to transparency renderer_.RenderSkybox(skybox_, camera_); // Water renderer_.RenderWater(water_, car_, skybox_, camera_); // Terrain renderer_.Render(terrain_, camera_, sun_); // Road-signs for (unsigned int x = 0; x < signs.size(); ++x) { // if (active_signs[x] >= 0) // no point renderer_.Render(signs[x], camera_, sun_); } if (camera_.state() == Camera::kFirstPerson) { // Rain (particles) if (sun_.time_of_day() != 12) rain_->Render(camera_, car_, skybox_); // Car with physics renderer_.Render(car_, camera_, sun_); } else { // Car with physics renderer_.Render(car_, camera_, sun_); // Rain (particles) if (sun_.time_of_day() != 12) rain_->Render(camera_, car_, skybox_); } // Axis only renders in debugging mode renderer_.RenderAxis(camera_); } // Assumes SetupLighting() has been called, only updates essential light properties void Controller::PositionLights() { glm::mat4 view_matrix = camera_.view_matrix(); glm::mat4 car_mv_matrix = view_matrix * car_->model_matrix(); // glm::mat3 norm_matrix = glm::mat3(view_matrix); DirectionalLight dirLight; dirLight.DiffuseIntensity = glm::vec3(1.00f, 1.00f, 1.00f); dirLight.AmbientIntensity = glm::vec3(0.50f, 0.50f, 0.50f); dirLight.SpecularIntensity = glm::vec3(0.35f, 0.35f, 0.40f); dirLight.DiffuseIntensity *= sun_.LightIntensityMultiplier(); dirLight.AmbientIntensity *= sun_.LightIntensityMultiplier(); // dirLight.SpecularIntensity *= 1.0f - sun_.LightIntensityMultiplier(); // if (!sun_.IsDay()) { // dirLight.SpecularIntensity.x *= 1.0f - sun_.LightIntensityMultiplier(); // dirLight.SpecularIntensity.y *= 1.0f - sun_.LightIntensityMultiplier(); // } dirLight.Direction = sun_.sun_direction(); // Point lights std::vector<PointLight> pointLights; // Main car brake lights for (unsigned int i = 0; i < 2; i++) { glm::mat4 brakeLightTranslation = glm::translate(glm::mat4(1.0f), glm::vec3(-0.85f + i * 1.7f, 0.0f, -3.3f)); PointLight brakeLight; brakeLight.DiffuseIntensity = glm::vec3(1.0f, 0.0f, 0.0f); brakeLight.Position = glm::vec3(car_mv_matrix * brakeLightTranslation * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)); brakeLight.Attenuation.Constant = 0.001f; brakeLight.Attenuation.Linear = 2.0f; brakeLight.Attenuation.Exp = 3.0f; if (is_key_pressed_hash_.at('s')) { brakeLight.Attenuation.Constant = 0.00001f; brakeLight.Attenuation.Linear = 0.5f; brakeLight.Attenuation.Exp = 3.0f; } pointLights.push_back(brakeLight); } // Spot lights std::vector<SpotLight> spotLights; // Main car headlights for (unsigned int i = 0; i < 2; i++) { glm::mat4 headlightTranslation = glm::translate(glm::mat4(1.0f), glm::vec3(-0.5f + i * 1.0f, 0.0f, 1.45f)); glm::mat3 headlightNormMatrix = glm::mat3(car_mv_matrix); SpotLight headlight; headlight.DiffuseIntensity = glm::vec3(1.0f, 1.0f, 1.0f); headlight.SpecularIntensity = glm::vec3(0.1f, 0.1f, 0.1f); headlight.Position = glm::vec3(car_mv_matrix * headlightTranslation * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)); headlight.Direction = headlightNormMatrix * glm::vec3(0.0f, -0.3f, 1.0f); headlight.CosineCutoff = cos(DEG2RAD(30.0f)); headlight.Attenuation.Constant = 0.3f; headlight.Attenuation.Linear = 0.01f; headlight.Attenuation.Exp = 0.01f; if (is_key_pressed_hash_.at('r')) { headlight.DiffuseIntensity = glm::vec3(0.0f, 0.0f, 0.0f); headlight.SpecularIntensity = glm::vec3(0.0f, 0.0f, 0.0f); } spotLights.push_back(headlight); } light_controller_->SetDirectionalLight(car_->shader()->Id, dirLight); light_controller_->SetSpotLights(water_->shader().Id, spotLights.size(), &spotLights[0]); light_controller_->SetDirectionalLight(water_->shader().Id, dirLight); light_controller_->SetPointLights(car_->shader()->Id, pointLights.size(), &pointLights[0]); light_controller_->SetSpotLights(car_->shader()->Id, spotLights.size(), &spotLights[0]); } // The main control tick // Controls everything: camera, inputs, physics, collisions void Controller::UpdateGame() { // Lights need to be transformed with view/normal matrix PositionLights(); // Update the position of the rain rain_->UpdatePosition(); // FPS counter - also determine delta time long long current_frame = glutGet(GLUT_ELAPSED_TIME); frames_count_ += 1; if ((current_frame - frames_past_) > 1000) { const int fps = frames_count_ * 1000.0f / (current_frame - frames_past_); std::cout << "FPS: " << frames_count_ << std::endl; frames_count_ = 0; frames_past_ = current_frame; // Work out average miliseconds per tick const GLfloat delta_time = 1.0f/fps * 1000.0f; if (abs(delta_time_ - delta_time) < 5) delta_time_ = delta_time; // printf("dt = %f\n",delta_time_); } // Update Sun/Moon position sun_.Update(); // Send time for water water_->SendTime(current_frame); terrain_->GenerationTick(); // printf("mid = (%f,%f,%f)\n",left_lane_midpoint_.x,left_lane_midpoint_.y,left_lane_midpoint_.z); // printf("car = (%f,%f,%f)\n",car_->translation().x,car_->translation().y,car_->translation().z); if (!collision_controller_.is_collision()) { UpdatePhysics(); game_state_ = collision_controller_.UpdateCollisions(car_, terrain_, &camera_, &road_sign_, game_state_); } else { // TODO add car off road shaking } car_->UpdateModelMatrix(); UpdateCamera(); if (game_state_ == kCrashingFall) { // delta_time_ /= 5; //slowmo if(playSound) system("aplay ./sounds/metal_crash.wav -q &"); playSound = 0; game_state_ = collision_controller_.CrashAnimationFall(&camera_, terrain_, car_, delta_time_, is_key_pressed_hash_); return; } if (game_state_ == kCrashingCliff) { // delta_time_ /= 5; //slowmo if(playSound) system("aplay ./sounds/metal_crash.wav -q &"); playSound = 0; game_state_ = collision_controller_.CrashAnimationCliff(&camera_, terrain_, car_, delta_time_, is_key_pressed_hash_); return; } if (is_key_pressed_hash_.at('w') || is_key_pressed_hash_.at('s') || is_key_pressed_hash_.at('a') || is_key_pressed_hash_.at('d')) { game_state_ = kStart; playSound = 1; } } // The controllers camera update tick // Uses car position (for chase and 1st person view) // and checks keypresses for freeview // @warn should be called before car movement void Controller::UpdateCamera() { // CAMERA CONTROLS // Freeview movement camera_.Movement(delta_time_, is_key_pressed_hash_); // Point at car camera_.UpdateCarTick(car_); // Update camera lookAt camera_.UpdateCamera(); } // The controllers physics update tick // Checks keypresses and calculates acceleration void Controller::UpdatePhysics() { if (game_state_ == kStart) { // Sets variables required for camera // i.e. camera has access to car in UpdateCarTick(car_) car_->ControllerMovementTick(delta_time_, is_key_pressed_hash_); } if (game_state_ == kAutoDrive) { collision_controller_.AutoDrive(car_, delta_time_); } } <|endoftext|>
<commit_before>#include "iconnconfigmain.h" #include <QApplication> #include <QCommandLineParser> #include <QLibraryInfo> #include <QLocale> #include <QSettings> #include <QTranslator> int main(int argc, char *argv[]) { QApplication app(argc, argv); QCoreApplication::setOrganizationName("punkt-k"); QCoreApplication::setOrganizationDomain("www.punkt-k.de"); QCoreApplication::setApplicationName("iConnConfig"); QCoreApplication::setApplicationVersion("0.1.5-alpha"); QTranslator mioConfigTranslator; QTranslator qtTranslator; QString l = "iconnconfig_" + QLocale::system().name(); if (mioConfigTranslator.load(QLocale(), QLatin1String("iconnconfig"), QLatin1String("_"), QLatin1String(":/translations/tr"))) { app.installTranslator(&mioConfigTranslator); qtTranslator.load(QLocale(), QLatin1String("qt"), QLatin1String("_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); app.installTranslator(&qtTranslator); } QCommandLineParser *parser = new QCommandLineParser(); parser->setApplicationDescription("Mio Config"); parser->addHelpOption(); parser->addVersionOption(); // A boolean option with multiple names (-f, --filename) QCommandLineOption filenameOption( QStringList() << "f" << "filename", QCoreApplication::translate("main", "filename to read settings from."), "filename"); parser->addOption(filenameOption); // Process the actual command line arguments given by the user parser->process(app); MioMain w(parser); w.show(); return app.exec(); } <commit_msg>Remove unused variable<commit_after>#include "iconnconfigmain.h" #include <QApplication> #include <QCommandLineParser> #include <QLibraryInfo> #include <QLocale> #include <QSettings> #include <QTranslator> int main(int argc, char *argv[]) { QApplication app(argc, argv); QCoreApplication::setOrganizationName("punkt-k"); QCoreApplication::setOrganizationDomain("www.punkt-k.de"); QCoreApplication::setApplicationName("iConnConfig"); QCoreApplication::setApplicationVersion("0.1.5-alpha"); QTranslator mioConfigTranslator; QTranslator qtTranslator; if (mioConfigTranslator.load(QLocale(), QLatin1String("iconnconfig"), QLatin1String("_"), QLatin1String(":/translations/tr"))) { app.installTranslator(&mioConfigTranslator); qtTranslator.load( QLocale(), QLatin1String("qt"), QLatin1String("_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); app.installTranslator(&qtTranslator); } QCommandLineParser *parser = new QCommandLineParser(); parser->setApplicationDescription("Mio Config"); parser->addHelpOption(); parser->addVersionOption(); // A boolean option with multiple names (-f, --filename) QCommandLineOption filenameOption( QStringList() << "f" << "filename", QCoreApplication::translate("main", "filename to read settings from."), "filename"); parser->addOption(filenameOption); // Process the actual command line arguments given by the user parser->process(app); MioMain w(parser); w.show(); return app.exec(); } <|endoftext|>
<commit_before>#include "common.h" #include "x86_helpers.h" xed_reg_enum_t GetUnusedRegister(xed_reg_enum_t used_register, int operand_width) { switch (operand_width) { case 16: if (used_register == XED_REG_AX) return XED_REG_CX; return XED_REG_AX; case 32: if (used_register == XED_REG_EAX) return XED_REG_ECX; return XED_REG_EAX; case 64: if (used_register == XED_REG_RAX) return XED_REG_RCX; return XED_REG_RAX; default: FATAL("Unexpected operand width"); } } xed_reg_enum_t GetFullSizeRegister(xed_reg_enum_t r, int child_ptr_size) { if (child_ptr_size == 8) { return xed_get_largest_enclosing_register(r); } else { return xed_get_largest_enclosing_register32(r); } } xed_reg_enum_t Get8BitRegister(xed_reg_enum_t r) { switch (r) { case XED_REG_AX: case XED_REG_EAX: case XED_REG_RAX: return XED_REG_AL; case XED_REG_CX: case XED_REG_ECX: case XED_REG_RCX: return XED_REG_CL; case XED_REG_DX: case XED_REG_EDX: case XED_REG_RDX: return XED_REG_DL; case XED_REG_BX: case XED_REG_EBX: case XED_REG_RBX: return XED_REG_BL; case XED_REG_SP: case XED_REG_ESP: case XED_REG_RSP: return XED_REG_SPL; case XED_REG_BP: case XED_REG_EBP: case XED_REG_RBP: return XED_REG_BPL; case XED_REG_SI: case XED_REG_ESI: case XED_REG_RSI: return XED_REG_SIL; case XED_REG_DI: case XED_REG_EDI: case XED_REG_RDI: return XED_REG_DIL; case XED_REG_R8W: case XED_REG_R8D: case XED_REG_R8: return XED_REG_R8B; case XED_REG_R9W: case XED_REG_R9D: case XED_REG_R9: return XED_REG_R9B; case XED_REG_R10W: case XED_REG_R10D: case XED_REG_R10: return XED_REG_R10B; case XED_REG_R11W: case XED_REG_R11D: case XED_REG_R11: return XED_REG_R11B; case XED_REG_R12W: case XED_REG_R12D: case XED_REG_R12: return XED_REG_R12B; case XED_REG_R13W: case XED_REG_R13D: case XED_REG_R13: return XED_REG_R13B; case XED_REG_R14W: case XED_REG_R14D: case XED_REG_R14: return XED_REG_R14B; case XED_REG_R15W: case XED_REG_R15D: case XED_REG_R15: return XED_REG_R15B; default: FATAL("Unknown register"); } } uint32_t Push(xed_state_t *dstate, xed_reg_enum_t r, unsigned char *encoded, size_t encoded_size) { uint32_t olen; xed_error_enum_t xed_error; // push destination register xed_encoder_request_t push; xed_encoder_request_zero_set_mode(&push, dstate); xed_encoder_request_set_iclass(&push, XED_ICLASS_PUSH); xed_encoder_request_set_effective_operand_width(&push, dstate->stack_addr_width * 8); xed_encoder_request_set_effective_address_size(&push, dstate->stack_addr_width * 8); xed_encoder_request_set_reg(&push, XED_OPERAND_REG0, GetFullSizeRegister(r, dstate->stack_addr_width)); xed_encoder_request_set_operand_order(&push, 0, XED_OPERAND_REG0); xed_error = xed_encode(&push, encoded, encoded_size, &olen); if (xed_error != XED_ERROR_NONE) { FATAL("Error encoding instruction"); } return olen; } uint32_t Pop(xed_state_t *dstate, xed_reg_enum_t r, unsigned char *encoded, size_t encoded_size) { uint32_t olen; xed_error_enum_t xed_error; // push destination register xed_encoder_request_t pop; xed_encoder_request_zero_set_mode(&pop, dstate); xed_encoder_request_set_iclass(&pop, XED_ICLASS_POP); xed_encoder_request_set_effective_operand_width(&pop, dstate->stack_addr_width * 8); xed_encoder_request_set_effective_address_size(&pop, dstate->stack_addr_width * 8); xed_encoder_request_set_reg(&pop, XED_OPERAND_REG0, GetFullSizeRegister(r, dstate->stack_addr_width)); xed_encoder_request_set_operand_order(&pop, 0, XED_OPERAND_REG0); xed_error = xed_encode(&pop, encoded, encoded_size, &olen); if (xed_error != XED_ERROR_NONE) { FATAL("Error encoding instruction"); } return olen; } void CopyOperandFromInstruction(xed_decoded_inst_t *src, xed_encoder_request_t *dest, xed_operand_enum_t src_operand_name, xed_operand_enum_t dest_operand_name, int dest_operand_index, size_t stack_offset) { if ((src_operand_name >= XED_OPERAND_REG0) && (src_operand_name <= XED_OPERAND_REG8) && (dest_operand_name >= XED_OPERAND_REG0) && (dest_operand_name <= XED_OPERAND_REG8)) { xed_reg_enum_t r = xed_decoded_inst_get_reg(src, src_operand_name); xed_encoder_request_set_reg(dest, dest_operand_name, r); } else if (src_operand_name == XED_OPERAND_MEM0 && dest_operand_name == XED_OPERAND_MEM0) { xed_encoder_request_set_mem0(dest); xed_reg_enum_t base_reg = xed_decoded_inst_get_base_reg(src, 0); xed_encoder_request_set_base0(dest, base_reg); xed_encoder_request_set_seg0(dest, xed_decoded_inst_get_seg_reg(src, 0)); xed_encoder_request_set_index(dest, xed_decoded_inst_get_index_reg(src, 0)); xed_encoder_request_set_scale(dest, xed_decoded_inst_get_scale(src, 0)); // in case where base is rsp, disp needs fixing if ((base_reg == XED_REG_SP) || (base_reg == XED_REG_ESP) || (base_reg == XED_REG_RSP)) { int64_t disp = xed_decoded_inst_get_memory_displacement(src, 0) + stack_offset; // always use disp width 4 in this case xed_encoder_request_set_memory_displacement(dest, disp, 4); } else { xed_encoder_request_set_memory_displacement(dest, xed_decoded_inst_get_memory_displacement(src, 0), xed_decoded_inst_get_memory_displacement_width(src, 0)); } // int length = xed_decoded_inst_get_memory_operand_length(xedd, 0); xed_encoder_request_set_memory_operand_length(dest, xed_decoded_inst_get_memory_operand_length(src, 0)); } else if (src_operand_name == XED_OPERAND_IMM0 && dest_operand_name == XED_OPERAND_IMM0) { uint64_t imm = xed_decoded_inst_get_unsigned_immediate(src); uint32_t width = xed_decoded_inst_get_immediate_width(src); xed_encoder_request_set_uimm0(dest, imm, width); } else if (src_operand_name == XED_OPERAND_IMM0SIGNED && dest_operand_name == XED_OPERAND_IMM0SIGNED) { int32_t imm = xed_decoded_inst_get_signed_immediate(src); uint32_t width = xed_decoded_inst_get_immediate_width(src); xed_encoder_request_set_simm(dest, imm, width); } else { FATAL("Unsupported param"); } xed_encoder_request_set_operand_order(dest, dest_operand_index, dest_operand_name); } uint32_t Mov(xed_state_t *dstate, uint32_t operand_width, xed_reg_enum_t base_reg, int32_t displacement, xed_reg_enum_t r2, unsigned char *encoded, size_t encoded_size) { uint32_t olen; xed_error_enum_t xed_error; xed_encoder_request_t mov; xed_encoder_request_zero_set_mode(&mov, dstate); xed_encoder_request_set_iclass(&mov, XED_ICLASS_MOV); xed_encoder_request_set_effective_operand_width(&mov, operand_width); xed_encoder_request_set_effective_address_size(&mov, dstate->stack_addr_width * 8); xed_encoder_request_set_mem0(&mov); xed_encoder_request_set_base0(&mov, base_reg); xed_encoder_request_set_memory_displacement(&mov, displacement, 4); // int length = xed_decoded_inst_get_memory_operand_length(xedd, 0); xed_encoder_request_set_memory_operand_length(&mov, operand_width / 8); xed_encoder_request_set_operand_order(&mov, 0, XED_OPERAND_MEM0); xed_encoder_request_set_reg(&mov, XED_OPERAND_REG0, r2); xed_encoder_request_set_operand_order(&mov, 1, XED_OPERAND_REG0); xed_error = xed_encode(&mov, encoded, encoded_size, &olen); if (xed_error != XED_ERROR_NONE) { FATAL("Error encoding instruction"); } return olen; } uint32_t Lzcnt(xed_state_t *dstate, uint32_t operand_width, xed_reg_enum_t dest_reg, xed_reg_enum_t src_reg, unsigned char *encoded, size_t encoded_size) { uint32_t olen; xed_error_enum_t xed_error; xed_encoder_request_t lzcnt; xed_encoder_request_zero_set_mode(&lzcnt, dstate); xed_encoder_request_set_iclass(&lzcnt, XED_ICLASS_LZCNT); xed_encoder_request_set_effective_operand_width(&lzcnt, operand_width); //xed_encoder_request_set_effective_address_size(&lzcnt, operand_width); xed_encoder_request_set_reg(&lzcnt, XED_OPERAND_REG0, dest_reg); xed_encoder_request_set_operand_order(&lzcnt, 0, XED_OPERAND_REG0); xed_encoder_request_set_reg(&lzcnt, XED_OPERAND_REG1, src_reg); xed_encoder_request_set_operand_order(&lzcnt, 1, XED_OPERAND_REG1); xed_error = xed_encode(&lzcnt, encoded, encoded_size, &olen); if (xed_error != XED_ERROR_NONE) { FATAL("Error encoding instruction"); } return olen; } uint32_t CmpImm8(xed_state_t *dstate, uint32_t operand_width, xed_reg_enum_t dest_reg, uint64_t imm, unsigned char *encoded, size_t encoded_size) { uint32_t olen; xed_error_enum_t xed_error; xed_encoder_request_t lzcnt; xed_encoder_request_zero_set_mode(&lzcnt, dstate); xed_encoder_request_set_iclass(&lzcnt, XED_ICLASS_CMP); xed_encoder_request_set_effective_operand_width(&lzcnt, operand_width); // xed_encoder_request_set_effective_address_size(&lzcnt, operand_width); xed_encoder_request_set_reg(&lzcnt, XED_OPERAND_REG0, dest_reg); xed_encoder_request_set_operand_order(&lzcnt, 0, XED_OPERAND_REG0); xed_encoder_request_set_uimm0_bits(&lzcnt, imm, 8); xed_encoder_request_set_operand_order(&lzcnt, 1, XED_OPERAND_IMM0); xed_error = xed_encode(&lzcnt, encoded, encoded_size, &olen); if (xed_error != XED_ERROR_NONE) { FATAL("Error encoding instruction"); } return olen; } uint32_t GetInstructionLength(xed_encoder_request_t *inst) { unsigned int olen; unsigned char tmp[15]; xed_error_enum_t xed_error; xed_error = xed_encode(inst, tmp, sizeof(tmp), &olen); if (xed_error != XED_ERROR_NONE) { FATAL("Error encoding instruction"); } return olen; } void FixRipDisplacement(xed_encoder_request_t *inst, size_t mem_address, size_t fixed_instruction_address) { // fake displacement, just to get length xed_encoder_request_set_memory_displacement(inst, 0x7777777, 4); uint32_t inst_length = GetInstructionLength(inst); size_t instruction_end_addr = fixed_instruction_address + inst_length; int64_t fixed_disp = (int64_t)(mem_address) - (int64_t)(instruction_end_addr); if (llabs(fixed_disp) > 0x7FFFFFFF) FATAL("Offset larger than 2G"); xed_encoder_request_set_memory_displacement(inst, fixed_disp, 4); } <commit_msg>Fix warnings with encoded_size<commit_after>#include "common.h" #include "x86_helpers.h" xed_reg_enum_t GetUnusedRegister(xed_reg_enum_t used_register, int operand_width) { switch (operand_width) { case 16: if (used_register == XED_REG_AX) return XED_REG_CX; return XED_REG_AX; case 32: if (used_register == XED_REG_EAX) return XED_REG_ECX; return XED_REG_EAX; case 64: if (used_register == XED_REG_RAX) return XED_REG_RCX; return XED_REG_RAX; default: FATAL("Unexpected operand width"); } } xed_reg_enum_t GetFullSizeRegister(xed_reg_enum_t r, int child_ptr_size) { if (child_ptr_size == 8) { return xed_get_largest_enclosing_register(r); } else { return xed_get_largest_enclosing_register32(r); } } xed_reg_enum_t Get8BitRegister(xed_reg_enum_t r) { switch (r) { case XED_REG_AX: case XED_REG_EAX: case XED_REG_RAX: return XED_REG_AL; case XED_REG_CX: case XED_REG_ECX: case XED_REG_RCX: return XED_REG_CL; case XED_REG_DX: case XED_REG_EDX: case XED_REG_RDX: return XED_REG_DL; case XED_REG_BX: case XED_REG_EBX: case XED_REG_RBX: return XED_REG_BL; case XED_REG_SP: case XED_REG_ESP: case XED_REG_RSP: return XED_REG_SPL; case XED_REG_BP: case XED_REG_EBP: case XED_REG_RBP: return XED_REG_BPL; case XED_REG_SI: case XED_REG_ESI: case XED_REG_RSI: return XED_REG_SIL; case XED_REG_DI: case XED_REG_EDI: case XED_REG_RDI: return XED_REG_DIL; case XED_REG_R8W: case XED_REG_R8D: case XED_REG_R8: return XED_REG_R8B; case XED_REG_R9W: case XED_REG_R9D: case XED_REG_R9: return XED_REG_R9B; case XED_REG_R10W: case XED_REG_R10D: case XED_REG_R10: return XED_REG_R10B; case XED_REG_R11W: case XED_REG_R11D: case XED_REG_R11: return XED_REG_R11B; case XED_REG_R12W: case XED_REG_R12D: case XED_REG_R12: return XED_REG_R12B; case XED_REG_R13W: case XED_REG_R13D: case XED_REG_R13: return XED_REG_R13B; case XED_REG_R14W: case XED_REG_R14D: case XED_REG_R14: return XED_REG_R14B; case XED_REG_R15W: case XED_REG_R15D: case XED_REG_R15: return XED_REG_R15B; default: FATAL("Unknown register"); } } uint32_t Push(xed_state_t *dstate, xed_reg_enum_t r, unsigned char *encoded, size_t encoded_size) { uint32_t olen; xed_error_enum_t xed_error; // push destination register xed_encoder_request_t push; xed_encoder_request_zero_set_mode(&push, dstate); xed_encoder_request_set_iclass(&push, XED_ICLASS_PUSH); xed_encoder_request_set_effective_operand_width(&push, dstate->stack_addr_width * 8); xed_encoder_request_set_effective_address_size(&push, dstate->stack_addr_width * 8); xed_encoder_request_set_reg(&push, XED_OPERAND_REG0, GetFullSizeRegister(r, dstate->stack_addr_width)); xed_encoder_request_set_operand_order(&push, 0, XED_OPERAND_REG0); xed_error = xed_encode(&push, encoded, (unsigned int)encoded_size, &olen); if (xed_error != XED_ERROR_NONE) { FATAL("Error encoding instruction"); } return olen; } uint32_t Pop(xed_state_t *dstate, xed_reg_enum_t r, unsigned char *encoded, size_t encoded_size) { uint32_t olen; xed_error_enum_t xed_error; // push destination register xed_encoder_request_t pop; xed_encoder_request_zero_set_mode(&pop, dstate); xed_encoder_request_set_iclass(&pop, XED_ICLASS_POP); xed_encoder_request_set_effective_operand_width(&pop, dstate->stack_addr_width * 8); xed_encoder_request_set_effective_address_size(&pop, dstate->stack_addr_width * 8); xed_encoder_request_set_reg(&pop, XED_OPERAND_REG0, GetFullSizeRegister(r, dstate->stack_addr_width)); xed_encoder_request_set_operand_order(&pop, 0, XED_OPERAND_REG0); xed_error = xed_encode(&pop, encoded, (unsigned int)encoded_size, &olen); if (xed_error != XED_ERROR_NONE) { FATAL("Error encoding instruction"); } return olen; } void CopyOperandFromInstruction(xed_decoded_inst_t *src, xed_encoder_request_t *dest, xed_operand_enum_t src_operand_name, xed_operand_enum_t dest_operand_name, int dest_operand_index, size_t stack_offset) { if ((src_operand_name >= XED_OPERAND_REG0) && (src_operand_name <= XED_OPERAND_REG8) && (dest_operand_name >= XED_OPERAND_REG0) && (dest_operand_name <= XED_OPERAND_REG8)) { xed_reg_enum_t r = xed_decoded_inst_get_reg(src, src_operand_name); xed_encoder_request_set_reg(dest, dest_operand_name, r); } else if (src_operand_name == XED_OPERAND_MEM0 && dest_operand_name == XED_OPERAND_MEM0) { xed_encoder_request_set_mem0(dest); xed_reg_enum_t base_reg = xed_decoded_inst_get_base_reg(src, 0); xed_encoder_request_set_base0(dest, base_reg); xed_encoder_request_set_seg0(dest, xed_decoded_inst_get_seg_reg(src, 0)); xed_encoder_request_set_index(dest, xed_decoded_inst_get_index_reg(src, 0)); xed_encoder_request_set_scale(dest, xed_decoded_inst_get_scale(src, 0)); // in case where base is rsp, disp needs fixing if ((base_reg == XED_REG_SP) || (base_reg == XED_REG_ESP) || (base_reg == XED_REG_RSP)) { int64_t disp = xed_decoded_inst_get_memory_displacement(src, 0) + stack_offset; // always use disp width 4 in this case xed_encoder_request_set_memory_displacement(dest, disp, 4); } else { xed_encoder_request_set_memory_displacement(dest, xed_decoded_inst_get_memory_displacement(src, 0), xed_decoded_inst_get_memory_displacement_width(src, 0)); } // int length = xed_decoded_inst_get_memory_operand_length(xedd, 0); xed_encoder_request_set_memory_operand_length(dest, xed_decoded_inst_get_memory_operand_length(src, 0)); } else if (src_operand_name == XED_OPERAND_IMM0 && dest_operand_name == XED_OPERAND_IMM0) { uint64_t imm = xed_decoded_inst_get_unsigned_immediate(src); uint32_t width = xed_decoded_inst_get_immediate_width(src); xed_encoder_request_set_uimm0(dest, imm, width); } else if (src_operand_name == XED_OPERAND_IMM0SIGNED && dest_operand_name == XED_OPERAND_IMM0SIGNED) { int32_t imm = xed_decoded_inst_get_signed_immediate(src); uint32_t width = xed_decoded_inst_get_immediate_width(src); xed_encoder_request_set_simm(dest, imm, width); } else { FATAL("Unsupported param"); } xed_encoder_request_set_operand_order(dest, dest_operand_index, dest_operand_name); } uint32_t Mov(xed_state_t *dstate, uint32_t operand_width, xed_reg_enum_t base_reg, int32_t displacement, xed_reg_enum_t r2, unsigned char *encoded, size_t encoded_size) { uint32_t olen; xed_error_enum_t xed_error; xed_encoder_request_t mov; xed_encoder_request_zero_set_mode(&mov, dstate); xed_encoder_request_set_iclass(&mov, XED_ICLASS_MOV); xed_encoder_request_set_effective_operand_width(&mov, operand_width); xed_encoder_request_set_effective_address_size(&mov, dstate->stack_addr_width * 8); xed_encoder_request_set_mem0(&mov); xed_encoder_request_set_base0(&mov, base_reg); xed_encoder_request_set_memory_displacement(&mov, displacement, 4); // int length = xed_decoded_inst_get_memory_operand_length(xedd, 0); xed_encoder_request_set_memory_operand_length(&mov, operand_width / 8); xed_encoder_request_set_operand_order(&mov, 0, XED_OPERAND_MEM0); xed_encoder_request_set_reg(&mov, XED_OPERAND_REG0, r2); xed_encoder_request_set_operand_order(&mov, 1, XED_OPERAND_REG0); xed_error = xed_encode(&mov, encoded, (unsigned int)encoded_size, &olen); if (xed_error != XED_ERROR_NONE) { FATAL("Error encoding instruction"); } return olen; } uint32_t Lzcnt(xed_state_t *dstate, uint32_t operand_width, xed_reg_enum_t dest_reg, xed_reg_enum_t src_reg, unsigned char *encoded, size_t encoded_size) { uint32_t olen; xed_error_enum_t xed_error; xed_encoder_request_t lzcnt; xed_encoder_request_zero_set_mode(&lzcnt, dstate); xed_encoder_request_set_iclass(&lzcnt, XED_ICLASS_LZCNT); xed_encoder_request_set_effective_operand_width(&lzcnt, operand_width); //xed_encoder_request_set_effective_address_size(&lzcnt, operand_width); xed_encoder_request_set_reg(&lzcnt, XED_OPERAND_REG0, dest_reg); xed_encoder_request_set_operand_order(&lzcnt, 0, XED_OPERAND_REG0); xed_encoder_request_set_reg(&lzcnt, XED_OPERAND_REG1, src_reg); xed_encoder_request_set_operand_order(&lzcnt, 1, XED_OPERAND_REG1); xed_error = xed_encode(&lzcnt, encoded, (unsigned int)encoded_size, &olen); if (xed_error != XED_ERROR_NONE) { FATAL("Error encoding instruction"); } return olen; } uint32_t CmpImm8(xed_state_t *dstate, uint32_t operand_width, xed_reg_enum_t dest_reg, uint64_t imm, unsigned char *encoded, size_t encoded_size) { uint32_t olen; xed_error_enum_t xed_error; xed_encoder_request_t lzcnt; xed_encoder_request_zero_set_mode(&lzcnt, dstate); xed_encoder_request_set_iclass(&lzcnt, XED_ICLASS_CMP); xed_encoder_request_set_effective_operand_width(&lzcnt, operand_width); // xed_encoder_request_set_effective_address_size(&lzcnt, operand_width); xed_encoder_request_set_reg(&lzcnt, XED_OPERAND_REG0, dest_reg); xed_encoder_request_set_operand_order(&lzcnt, 0, XED_OPERAND_REG0); xed_encoder_request_set_uimm0_bits(&lzcnt, imm, 8); xed_encoder_request_set_operand_order(&lzcnt, 1, XED_OPERAND_IMM0); xed_error = xed_encode(&lzcnt, encoded, (unsigned int)encoded_size, &olen); if (xed_error != XED_ERROR_NONE) { FATAL("Error encoding instruction"); } return olen; } uint32_t GetInstructionLength(xed_encoder_request_t *inst) { unsigned int olen; unsigned char tmp[15]; xed_error_enum_t xed_error; xed_error = xed_encode(inst, tmp, sizeof(tmp), &olen); if (xed_error != XED_ERROR_NONE) { FATAL("Error encoding instruction"); } return olen; } void FixRipDisplacement(xed_encoder_request_t *inst, size_t mem_address, size_t fixed_instruction_address) { // fake displacement, just to get length xed_encoder_request_set_memory_displacement(inst, 0x7777777, 4); uint32_t inst_length = GetInstructionLength(inst); size_t instruction_end_addr = fixed_instruction_address + inst_length; int64_t fixed_disp = (int64_t)(mem_address) - (int64_t)(instruction_end_addr); if (llabs(fixed_disp) > 0x7FFFFFFF) FATAL("Offset larger than 2G"); xed_encoder_request_set_memory_displacement(inst, fixed_disp, 4); } <|endoftext|>
<commit_before>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <array> #include <utility> namespace polymorphic { namespace detail { template <typename T> using ptr = T*; template <typename T, typename Signature> struct function_entry; template <typename T, typename Return, typename Method, typename... Parameters> struct function_entry<T, Return(Method, Parameters...)> { static Return poly_call(Method method, void* t, Parameters... parameters) { return poly_extend(method, *static_cast<T*>(t), parameters...); } }; template <typename T, typename Return, typename Method, typename... Parameters> struct function_entry<T, Return(Method, Parameters...)const> { static Return poly_call(Method method, const void* t, Parameters... parameters) { return poly_extend(method, *static_cast<const T*>(t), parameters...); } }; template <typename T, typename... Signatures> inline const auto vtable = std::array{ reinterpret_cast<ptr<void()>>(function_entry<T, Signatures>::poly_call)...}; template <size_t Index, typename Signature> struct vtable_caller; template <size_t Index, typename Return, typename Method, typename... Parameters> struct vtable_caller<Index, Return(Method, Parameters...)> { static Return call_vtable(Method method, ptr<const ptr<void()>> table, void* t, Parameters... parameters) { return reinterpret_cast<ptr<Return(Method, void*, Parameters...)>>( table[Index])(method, t, parameters...); } constexpr static std::size_t get_index(ptr<Return(Method, Parameters...)>) { return Index; } using is_const = std::false_type; }; template <size_t Index, typename Signature> struct vtable_caller; template <size_t Index, typename Return, typename Method, typename... Parameters> struct vtable_caller<Index, Return(Method, Parameters...)const> { static Return call_vtable(Method method, ptr<const ptr<void()>> table, const void* t, Parameters... parameters) { return reinterpret_cast<ptr<Return(Method, const void*, Parameters...)>>( table[Index])(method, t, parameters...); } constexpr static std::size_t get_index(ptr<Return(Method, Parameters...)>) { return Index; } using is_const = std::true_type; }; template<typename T> using is_const_t = typename T::is_const; template <typename... implementations> struct overload_call_vtable : implementations... { using implementations::call_vtable...; using implementations::get_index...; static constexpr bool all_const = std::conjunction_v<is_const_t<implementations>...>; }; template <typename IntPack, typename... Signatures> struct polymorphic_caller_implementation; template <size_t... I, typename... Signatures> struct polymorphic_caller_implementation<std::index_sequence<I...>, Signatures...> : overload_call_vtable<vtable_caller<I, Signatures>...> {}; } // namespace detail template <typename... Signatures> class polymorphic_view; template <typename T> struct is_polymorphic_view { static constexpr bool value = false; }; template <typename... Signatures> struct is_polymorphic_view<polymorphic_view<Signatures...>> { static constexpr bool value = true; }; template <typename... Signatures> class polymorphic_view : private detail::polymorphic_caller_implementation< std::make_index_sequence<sizeof...(Signatures)>, Signatures...> { const std::array<detail::ptr<void()>, sizeof...(Signatures)>* vptr_ = nullptr; std::conditional_t<polymorphic_view::all_const,const void*, void*> t_ = nullptr; template <typename... OtherSignatures> static auto get_vtable(const polymorphic_view<OtherSignatures...>& other) { static const std::array<detail::ptr<void()>, sizeof...(Signatures)> vtable{ other.template get_entry<Signatures>()...}; return &vtable; } template <typename Signature> detail::ptr<void()> get_entry() const { return (*vptr_)[this->get_index(detail::ptr<Signature>{})]; } template <typename... OtherSignatures> friend class polymorphic_view; public: template <typename T, typename = std::enable_if_t< !is_polymorphic_view<std::decay_t<T>>::value>> explicit polymorphic_view(T& t) : vptr_(&detail::vtable<std::decay_t<T>, Signatures...>), t_(&t) {} template <typename... OtherSignatures> explicit polymorphic_view(const polymorphic_view<OtherSignatures...>& other) : vptr_(get_vtable(other)), t_(other.t_) {} explicit operator bool() const { return t_ != nullptr; } template <typename Method, typename... Parameters> decltype(auto) call(Parameters&&... parameters) { return this->call_vtable(Method{}, vptr_->data(), t_, std::forward<Parameters>(parameters)...); } }; } // namespace polymorphic #include <iostream> #include <string> struct draw {}; struct another {}; template <typename T> void poly_extend(draw, const T& t) { std::cout << t << "\n"; } template <typename T> void poly_extend(another, T& t) { t = t + t; } int main() { int i = 5; using poly = polymorphic::polymorphic_view<void(draw), void(another)>; using poly_const = polymorphic::polymorphic_view<void(draw) const>; const int ic = 7; poly_const pc1{ ic }; pc1.call<draw>(); poly p1{i}; p1.call<draw>(); auto p2 = p1; p2.call<draw>(); std::string s("hello world"); p2 = poly{s}; p2.call<another>(); p2.call<draw>(); polymorphic::polymorphic_view<void(draw)> p3{p2}; p3.call<draw>(); } <commit_msg>Add initial polymorphic_object<commit_after>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <array> #include <utility> namespace polymorphic { namespace detail { template <typename T> using ptr = T*; template <typename T, typename Signature> struct function_entry; template <typename T, typename Return, typename Method, typename... Parameters> struct function_entry<T, Return(Method, Parameters...)> { static Return poly_call(Method method, void* t, Parameters... parameters) { return poly_extend(method, *static_cast<T*>(t), parameters...); } }; template <typename T, typename Return, typename Method, typename... Parameters> struct function_entry<T, Return(Method, Parameters...) const> { static Return poly_call(Method method, const void* t, Parameters... parameters) { return poly_extend(method, *static_cast<const T*>(t), parameters...); } }; template <typename T> struct type {}; template <typename T, typename... Signatures> inline const auto vtable = std::array{ reinterpret_cast<ptr<void()>>(function_entry<T, Signatures>::poly_call)...}; template <size_t Index, typename Signature> struct vtable_caller; template <size_t Index, typename Return, typename Method, typename... Parameters> struct vtable_caller<Index, Return(Method, Parameters...)> { static Return call_vtable(Method method, ptr<const ptr<void()>> table, void* t, Parameters... parameters) { return reinterpret_cast<ptr<Return(Method, void*, Parameters...)>>( table[Index])(method, t, parameters...); } constexpr static std::size_t get_index(type<Return(Method, Parameters...)>) { return Index; } constexpr static bool is_const = false; }; template <size_t Index, typename Signature> struct vtable_caller; template <size_t Index, typename Return, typename Method, typename... Parameters> struct vtable_caller<Index, Return(Method, Parameters...) const> { static Return call_vtable(Method method, ptr<const ptr<void()>> table, const void* t, Parameters... parameters) { return reinterpret_cast<ptr<Return(Method, const void*, Parameters...)>>( table[Index])(method, t, parameters...); } constexpr static std::size_t get_index( type<Return(Method, Parameters...) const>) { return Index; } constexpr static bool is_const = true; }; template <typename T> using is_const_t = typename T::is_const; template <typename... implementations> struct overload_call_vtable : implementations... { using implementations::call_vtable...; using implementations::get_index...; static constexpr bool all_const = (implementations::is_const && ...); }; template <typename IntPack, typename... Signatures> struct polymorphic_caller_implementation; template <size_t... I, typename... Signatures> struct polymorphic_caller_implementation<std::index_sequence<I...>, Signatures...> : overload_call_vtable<vtable_caller<I, Signatures>...> {}; } // namespace detail template <typename... Signatures> class polymorphic_view; template <typename... Signatures> class polymorphic_object; template <typename T> struct is_polymorphic{ static constexpr bool value = false; }; template <typename... Signatures> struct is_polymorphic<polymorphic_view<Signatures...>> { static constexpr bool value = true; }; template <typename... Signatures> struct is_polymorphic<polymorphic_object<Signatures...>> { static constexpr bool value = true; }; using object_ptr = std::unique_ptr<void, detail::ptr<void(void*)>>; template <typename T> object_ptr make_object_ptr(const T& t) { return object_ptr(new T(t), +[](void* v) { delete static_cast<T*>(v); }); } namespace detail { struct clone {}; template <typename T> object_ptr poly_extend(clone, const T& t) { return make_object_ptr(t); } template<typename T> auto get_ptr(T* t){return t;} template<typename T> auto get_ptr(T& t){return t.get();} } // namespace detail template <typename... Signatures> class polymorphic_object : private detail::polymorphic_caller_implementation< std::make_index_sequence<sizeof...(Signatures) + 1>, Signatures..., object_ptr(detail::clone) const> { const std::array<detail::ptr<void()>, sizeof...(Signatures) + 1>* vptr_ = nullptr; object_ptr t_; template <typename Signature> detail::ptr<void()> get_entry() const { return (*vptr_)[this->get_index(detail::type<Signature>{})]; } template <typename... OtherSignatures> friend class polymorphic_view; public: template <typename T, typename = std::enable_if_t< !is_polymorphic<std::decay_t<T>>::value>> explicit polymorphic_object(T& t) : vptr_(&detail::vtable<std::decay_t<T>, Signatures..., object_ptr(detail::clone)>), t_(make_object_ptr(t)) {} polymorphic_object(const polymorphic_object& other) : vptr_(other.vptr_), t_(other.call<detail::clone>()) {} polymorphic_object(polymorphic_object&&) = default; polymorphic_object& operator=(polymorphic_object&&) = default; polymorphic_object& operator=(const polymorphic_object& other) { (*this) = polymorphic_view(other); } explicit operator bool() const { return t_ != nullptr; } template <typename Method, typename... Parameters> decltype(auto) call(Parameters&&... parameters) { return this->call_vtable(Method{}, vptr_->data(), t_.get(), std::forward<Parameters>(parameters)...); } template <typename Method, typename... Parameters> decltype(auto) call(Parameters&&... parameters) const { return this->call_vtable(Method{}, vptr_->data(), t_.get(), std::forward<Parameters>(parameters)...); } }; template <typename... Signatures> class polymorphic_view : private detail::polymorphic_caller_implementation< std::make_index_sequence<sizeof...(Signatures)>, Signatures...> { const std::array<detail::ptr<void()>, sizeof...(Signatures)>* vptr_ = nullptr; std::conditional_t<polymorphic_view::all_const, const void*, void*> t_ = nullptr; template <typename Poly> static auto get_vtable(const Poly& other) { static const std::array<detail::ptr<void()>, sizeof...(Signatures)> vtable{ other.template get_entry<Signatures>()...}; return &vtable; } template <typename Signature> detail::ptr<void()> get_entry() const { return (*vptr_)[this->get_index(detail::type<Signature>{})]; } template <typename... OtherSignatures> friend class polymorphic_view; public: template <typename T, typename = std::enable_if_t< !is_polymorphic<std::decay_t<T>>::value>> explicit polymorphic_view(T& t) : vptr_(&detail::vtable<std::decay_t<T>, Signatures...>), t_(&t) {} template <typename Poly, typename = std::enable_if_t< is_polymorphic<std::decay_t<Poly>>::value>> explicit polymorphic_view(const Poly& other) : vptr_(get_vtable(other)), t_(detail::get_ptr(other.t_)) {} explicit operator bool() const { return t_ != nullptr; } template <typename Method, typename... Parameters> decltype(auto) call(Parameters&&... parameters) { return this->call_vtable(Method{}, vptr_->data(), t_, std::forward<Parameters>(parameters)...); } }; } // namespace polymorphic #include <iostream> #include <string> struct draw {}; struct another {}; template <typename T> void poly_extend(draw, const T& t) { std::cout << t << "\n"; } template <typename T> void poly_extend(another, T& t) { t = t + t; } int main() { int i = 5; using poly = polymorphic::polymorphic_view<void(draw) const, void(another)>; using poly_object = polymorphic::polymorphic_object<void(draw) const, void(another)>; poly_object po{i}; auto po1 = po; po.call<another>(); po1.call<draw>(); po.call<draw>(); poly a{po}; a.call<draw>(); using poly_const = polymorphic::polymorphic_view<void(draw) const>; const int ic = 7; poly_const pc1{ic}; pc1.call<draw>(); poly p1{i}; p1.call<draw>(); auto p2 = p1; p2.call<draw>(); std::string s("hello world"); p2 = poly{s}; p2.call<another>(); p2.call<draw>(); polymorphic::polymorphic_view<void(draw) const> p3{p2}; p3.call<draw>(); }<|endoftext|>
<commit_before>// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2010, 2012 Alessandro Tasora // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // /////////////////////////////////////////////////// // // ChShaftsBody.cpp // // ------------------------------------------------ // www.deltaknowledge.com // ------------------------------------------------ /////////////////////////////////////////////////// #include "physics/ChShaftsBody.h" #include "physics/ChGlobal.h" #include "core/ChMemory.h" // must be last include (memory leak debugger). In .cpp only. namespace chrono { // Register into the object factory, to enable run-time // dynamic creation and persistence ChClassRegister<ChShaftsBody> a_registration_ChShaftsBody; ////////////////////////////////////// ////////////////////////////////////// ChShaftsBody::ChShaftsBody () { this->torque_react= 0; this->cache_li_speed =0.f; this->cache_li_pos = 0.f; this->shaft = 0; this->body = 0; this->shaft_dir = VECT_Z; SetIdentifier(CHGLOBALS().GetUniqueIntID()); // mark with unique ID } ChShaftsBody::~ChShaftsBody () { } void ChShaftsBody::Copy(ChShaftsBody* source) { // copy the parent class data... ChPhysicsItem::Copy(source); // copy class data torque_react = source->torque_react; cache_li_speed = source->cache_li_speed; cache_li_pos = source->cache_li_pos; this->shaft_dir = source->shaft_dir; this->shaft = 0; this->body = 0; } int ChShaftsBody::Initialize(ChSharedPtr<ChShaft> mshaft, ChSharedPtr<ChBodyFrame> mbody, ChVector<>& mdir) { ChShaft* mm1 = mshaft.get_ptr(); ChBodyFrame* mm2 = mbody.get_ptr(); assert(mm1 && mm2); assert(mm1->GetSystem() == mm2->GetSystem()); this->shaft = mm1; this->body = mm2; this->shaft_dir = Vnorm(mdir); this->constraint.SetVariables(&mm1->Variables(), &mm2->Variables()); this->SetSystem(this->shaft->GetSystem()); return true; } void ChShaftsBody::Update (double mytime) { // Inherit time changes of parent class ChPhysicsItem::Update(mytime); // update class data // ... } ////////// LCP INTERFACES //// void ChShaftsBody::InjectConstraints(ChLcpSystemDescriptor& mdescriptor) { //if (!this->IsActive()) // return; mdescriptor.InsertConstraint(&constraint); } void ChShaftsBody::ConstraintsBiReset() { constraint.Set_b_i(0.); } void ChShaftsBody::ConstraintsBiLoad_C(double factor, double recovery_clamp, bool do_clamp) { //if (!this->IsActive()) // return; double res = 0; // no residual constraint.Set_b_i(constraint.Get_b_i() + factor * res); } void ChShaftsBody::ConstraintsBiLoad_Ct(double factor) { //if (!this->IsActive()) // return; // nothing } void ChShaftsBody::ConstraintsLoadJacobians() { // compute jacobians //ChVector<> jacw = this->body->TrasformDirectionParentToLocal(shaft_dir); ChVector<> jacw = shaft_dir; this->constraint.Get_Cq_a()->ElementN(0)=-1; this->constraint.Get_Cq_b()->ElementN(0)=0; this->constraint.Get_Cq_b()->ElementN(1)=0; this->constraint.Get_Cq_b()->ElementN(2)=0; this->constraint.Get_Cq_b()->ElementN(3)=(float)jacw.x; this->constraint.Get_Cq_b()->ElementN(4)=(float)jacw.y; this->constraint.Get_Cq_b()->ElementN(5)=(float)jacw.z; } void ChShaftsBody::ConstraintsFetch_react(double factor) { // From constraints to react vector: this->torque_react = constraint.Get_l_i() * factor; } // Following functions are for exploiting the contact persistence void ChShaftsBody::ConstraintsLiLoadSuggestedSpeedSolution() { constraint.Set_l_i(this->cache_li_speed); } void ChShaftsBody::ConstraintsLiLoadSuggestedPositionSolution() { constraint.Set_l_i(this->cache_li_pos); } void ChShaftsBody::ConstraintsLiFetchSuggestedSpeedSolution() { this->cache_li_speed = (float)constraint.Get_l_i(); } void ChShaftsBody::ConstraintsLiFetchSuggestedPositionSolution() { this->cache_li_pos = (float)constraint.Get_l_i(); } //////// FILE I/O void ChShaftsBody::StreamOUT(ChStreamOutBinary& mstream) { // class version number mstream.VersionWrite(1); // serialize parent class too ChPhysicsItem::StreamOUT(mstream); // stream out all member data mstream << this->shaft_dir; } void ChShaftsBody::StreamIN(ChStreamInBinary& mstream) { // class version number int version = mstream.VersionRead(); // deserialize parent class too ChPhysicsItem::StreamIN(mstream); // deserialize class mstream >> this->shaft_dir; } } // END_OF_NAMESPACE____ ///////////////////// <commit_msg>Another assert trouble - removed<commit_after>// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2010, 2012 Alessandro Tasora // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // /////////////////////////////////////////////////// // // ChShaftsBody.cpp // // ------------------------------------------------ // www.deltaknowledge.com // ------------------------------------------------ /////////////////////////////////////////////////// #include "physics/ChShaftsBody.h" #include "physics/ChGlobal.h" #include "core/ChMemory.h" // must be last include (memory leak debugger). In .cpp only. namespace chrono { // Register into the object factory, to enable run-time // dynamic creation and persistence ChClassRegister<ChShaftsBody> a_registration_ChShaftsBody; ////////////////////////////////////// ////////////////////////////////////// ChShaftsBody::ChShaftsBody () { this->torque_react= 0; this->cache_li_speed =0.f; this->cache_li_pos = 0.f; this->shaft = 0; this->body = 0; this->shaft_dir = VECT_Z; SetIdentifier(CHGLOBALS().GetUniqueIntID()); // mark with unique ID } ChShaftsBody::~ChShaftsBody () { } void ChShaftsBody::Copy(ChShaftsBody* source) { // copy the parent class data... ChPhysicsItem::Copy(source); // copy class data torque_react = source->torque_react; cache_li_speed = source->cache_li_speed; cache_li_pos = source->cache_li_pos; this->shaft_dir = source->shaft_dir; this->shaft = 0; this->body = 0; } int ChShaftsBody::Initialize(ChSharedPtr<ChShaft> mshaft, ChSharedPtr<ChBodyFrame> mbody, ChVector<>& mdir) { ChShaft* mm1 = mshaft.get_ptr(); ChBodyFrame* mm2 = mbody.get_ptr(); assert(mm1 && mm2); this->shaft = mm1; this->body = mm2; this->shaft_dir = Vnorm(mdir); this->constraint.SetVariables(&mm1->Variables(), &mm2->Variables()); this->SetSystem(this->shaft->GetSystem()); return true; } void ChShaftsBody::Update (double mytime) { // Inherit time changes of parent class ChPhysicsItem::Update(mytime); // update class data // ... } ////////// LCP INTERFACES //// void ChShaftsBody::InjectConstraints(ChLcpSystemDescriptor& mdescriptor) { //if (!this->IsActive()) // return; mdescriptor.InsertConstraint(&constraint); } void ChShaftsBody::ConstraintsBiReset() { constraint.Set_b_i(0.); } void ChShaftsBody::ConstraintsBiLoad_C(double factor, double recovery_clamp, bool do_clamp) { //if (!this->IsActive()) // return; double res = 0; // no residual constraint.Set_b_i(constraint.Get_b_i() + factor * res); } void ChShaftsBody::ConstraintsBiLoad_Ct(double factor) { //if (!this->IsActive()) // return; // nothing } void ChShaftsBody::ConstraintsLoadJacobians() { // compute jacobians //ChVector<> jacw = this->body->TrasformDirectionParentToLocal(shaft_dir); ChVector<> jacw = shaft_dir; this->constraint.Get_Cq_a()->ElementN(0)=-1; this->constraint.Get_Cq_b()->ElementN(0)=0; this->constraint.Get_Cq_b()->ElementN(1)=0; this->constraint.Get_Cq_b()->ElementN(2)=0; this->constraint.Get_Cq_b()->ElementN(3)=(float)jacw.x; this->constraint.Get_Cq_b()->ElementN(4)=(float)jacw.y; this->constraint.Get_Cq_b()->ElementN(5)=(float)jacw.z; } void ChShaftsBody::ConstraintsFetch_react(double factor) { // From constraints to react vector: this->torque_react = constraint.Get_l_i() * factor; } // Following functions are for exploiting the contact persistence void ChShaftsBody::ConstraintsLiLoadSuggestedSpeedSolution() { constraint.Set_l_i(this->cache_li_speed); } void ChShaftsBody::ConstraintsLiLoadSuggestedPositionSolution() { constraint.Set_l_i(this->cache_li_pos); } void ChShaftsBody::ConstraintsLiFetchSuggestedSpeedSolution() { this->cache_li_speed = (float)constraint.Get_l_i(); } void ChShaftsBody::ConstraintsLiFetchSuggestedPositionSolution() { this->cache_li_pos = (float)constraint.Get_l_i(); } //////// FILE I/O void ChShaftsBody::StreamOUT(ChStreamOutBinary& mstream) { // class version number mstream.VersionWrite(1); // serialize parent class too ChPhysicsItem::StreamOUT(mstream); // stream out all member data mstream << this->shaft_dir; } void ChShaftsBody::StreamIN(ChStreamInBinary& mstream) { // class version number int version = mstream.VersionRead(); // deserialize parent class too ChPhysicsItem::StreamIN(mstream); // deserialize class mstream >> this->shaft_dir; } } // END_OF_NAMESPACE____ ///////////////////// <|endoftext|>
<commit_before>#include<iostream> #include<string.h> #include<string> #include<vector> #include<sys/types.h> #include<sys/wait.h> #include<sys/stat.h> #include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<cstring> #include<algorithm> #include<iterator> #include<sstream> using namespace std; bool run_test(char command[]); bool run_word_test(char command[]); bool test_word(const char command[]); bool test_check_brackets(const char command[]); void parse_line(char c_line[], char *command_line[]); void run_line(char *command_line[]); int main() { string str; string arg = ""; while(1) { str = ""; char userName[100] = ""; if(getlogin_r(userName, sizeof(userName)-1) != 0) //Getting username, and returns null if cant be found { perror("Error getting username"); } cout << '[' << userName << '@'; char hostName[100] = ""; if(gethostname(hostName, sizeof(hostName)-1) != 0) // Getting host name, returns numm if it cannot be found { perror("Error getting hostname"); } cout << hostName << ']'; cout << "$"; getline(cin,str); //Gets a command if(str == "exit") //If the command is exit the program stops { break; } if(str.size() != 0 && str.at(0) == '#') { str = ""; } if(str != "") { for(unsigned i = 0; i < str.size(); i++) { if(str.at(i) == '#') //Removes all part of the command after the comment { str = str.substr(0,i); } } while(str.at(0) == ' ') { str = str.substr(1,str.size()-1); } if(str.at(str.size() - 1 ) == ' ') { str = str.substr(0,str.size()-2); } bool testBool_brac = false; bool testBool = false; char c_line[100]; char *command_line[64]; strcpy(c_line,str.c_str()); c_line[str.size()] = '\0'; testBool_brac = test_check_brackets(c_line); if(testBool_brac) { run_test(c_line); } else if(!testBool_brac) { cout << "Checking test\n"; testBool = test_word(c_line); if(testBool) { cout << "Running test\n"; run_word_test(c_line); } else { parse_line(c_line, command_line); run_line(command_line); } } } } return 0; } void parse_line(char c_line[], char *command_line[]) { while(*c_line != '\0') { while(*c_line == ' ' || *c_line == '\n' || *c_line == '\t') { *c_line++ = '\0'; } *command_line++ = c_line; while(*c_line != '\0' && *c_line != ' ' && *c_line != '\n' && *c_line != '\t') { c_line++; } *command_line = NULL; } return; } bool test_word(const char command[]) { int i = 0; if(command[i] == 't' && command[i + 1] == 'e') { if(command[i + 3] == 't') { return true; } } return false; } bool run_word_test(char command[]) { bool file = false; bool dir = false; bool exist = false; int i = 3; char fix_command[100]; i++; for(; command[i] == ' '; ++i){} // to skip all the spaces between test and the flag if(command[i] == '-' && command[i + 1] == 'f') { file = true; i++; i++; } else if(command[i] == '-' && command[i + 1] == 'd') { dir = true; i++; i++; } else if(command[i] == '-') { exist = true; i++; i++; } for(; command[i] == ' '; ++i){} // skip all spaces between flag and argument if(command[i] != '\0') { int j = 0; for(; command[i] != '\0' && command[i] != ' '; ++i) { fix_command[j] = command[i]; j++; } fix_command[j] = '\0'; } if(exist) { struct stat exist; if(stat(fix_command, &exist) == 0) { cout << "(TRUE)\n"; return true; } else { cout << "(FALSE)\n"; return false; } } else if(file) { struct stat file; stat(fix_command, &file); if(S_ISREG(file.st_mode) != 0) { cout << "(TRUE)\n"; return true; } else { cout << "(FALSE)\n"; return false; } } else if(dir) { struct stat dir; stat(fix_command, &dir); if(S_ISDIR(dir.st_mode) != 0) { cout << "(TRUE)\n"; return true; } else { cout << "(FALSE)\n"; } } return false; } bool test_check_brackets(const char command[]) { cout << "Checking brackets\n"; unsigned i = 0; if(command[i] == '[') { i++; if(command[i] == ' ') { for(; command[i] != '\0'; i++) { if(command[i] == ']') { if(command[i - 1] == ' ') { return true; } else { cout << "Need a space before ]\n"; return false; } } ++i; } } } return false; } bool run_test(char command[]) { } void run_line(char *command_line[]) { pid_t pid; int status; if((pid = fork()) < 0) { perror("forking failed"); } else if(pid == 0) { if(execvp(*command_line,command_line) < 0) { perror("execvp failed"); exit(1); } } else { while(wait(&status) != pid) ; } return; } <commit_msg>finished test for rshell.cpp<commit_after>#include<iostream> #include<string.h> #include<string> #include<vector> #include<sys/types.h> #include<sys/wait.h> #include<sys/stat.h> #include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<cstring> #include<algorithm> #include<iterator> #include<sstream> using namespace std; bool run_test(char command[]); bool run_word_test(char command[]); bool test_word(const char command[]); bool test_check_brackets(const char command[], bool &brackets); void parse_line(char c_line[], char *command_line[]); void run_line(char *command_line[]); int main() { string str; string arg = ""; while(1) { str = ""; char userName[100] = ""; if(getlogin_r(userName, sizeof(userName)-1) != 0) //Getting username, and returns null if cant be found { perror("Error getting username"); } cout << '[' << userName << '@'; char hostName[100] = ""; if(gethostname(hostName, sizeof(hostName)-1) != 0) // Getting host name, returns numm if it cannot be found { perror("Error getting hostname"); } cout << hostName << ']'; cout << "$"; getline(cin,str); //Gets a command if(str == "exit") //If the command is exit the program stops { break; } if(str.size() != 0 && str.at(0) == '#') { str = ""; } if(str != "") { for(unsigned i = 0; i < str.size(); i++) { if(str.at(i) == '#') //Removes all part of the command after the comment { str = str.substr(0,i); } } while(str.at(0) == ' ') { str = str.substr(1,str.size()-1); } if(str.at(str.size() - 1 ) == ' ') { str = str.substr(0,str.size()- 1); } bool extra_brac = false; bool testBool_brac = false; bool testBool = false; char c_line[100]; char *command_line[64]; strcpy(c_line,str.c_str()); c_line[str.size()] = '\0'; testBool_brac = test_check_brackets(c_line, extra_brac); if(testBool_brac && extra_brac) { run_test(c_line); } else if(!testBool_brac && !extra_brac) { testBool = test_word(c_line); if(testBool) { run_word_test(c_line); } else { parse_line(c_line, command_line); run_line(command_line); } } } } return 0; } void parse_line(char c_line[], char *command_line[]) { while(*c_line != '\0') { while(*c_line == ' ' || *c_line == '\n' || *c_line == '\t') { *c_line++ = '\0'; } *command_line++ = c_line; while(*c_line != '\0' && *c_line != ' ' && *c_line != '\n' && *c_line != '\t') { c_line++; } *command_line = NULL; } return; } bool test_word(const char command[]) { int i = 0; if(command[i] == 't' && command[i + 1] == 'e') { if(command[i + 3] == 't') { return true; } } return false; } bool run_word_test(char command[]) { bool file = false; bool dir = false; bool exist = false; int i = 3; char fix_command[100]; i++; for(; command[i] == ' '; ++i){} // to skip all the spaces between test and the flag if(command[i] == '-' && command[i + 1] == 'f') { file = true; i++; i++; } else if(command[i] == '-' && command[i + 1] == 'd') { dir = true; i++; i++; } else if(command[i] == '-' && (command[i + 1] != 'e' && command[i + 1] != ' ')) { cout << "Invalid Flag\n"; return false; } else if(command[i] == '-' && (command[i + 1] == 'e' || command[i + 1] == ' ')) { exist = true; i++; i++; } else { cout << "Error missing Flag\n"; return false; } for(; command[i] == ' '; ++i){} // skip all spaces between flag and argument if(command[i] != '\0') { int j = 0; for(; command[i] != '\0' && command[i] != ' '; ++i) { fix_command[j] = command[i]; j++; } fix_command[j] = '\0'; } if(exist) { struct stat exist; if(stat(fix_command, &exist) == 0) { cout << "(True)\n"; return true; } else { cout << "(False)\n"; return false; } } else if(file) { struct stat file; stat(fix_command, &file); if(S_ISREG(file.st_mode) != 0) { cout << "(True)\n"; return true; } else { cout << "(False)\n"; return false; } } else if(dir) { struct stat dir; stat(fix_command, &dir); if(S_ISDIR(dir.st_mode) != 0) { cout << "(True)\n"; return true; } else { cout << "(False)\n"; return false; } } return false; } bool test_check_brackets(const char command[], bool &brackets) { bool endBracket = true; int i = 0; if(command[i] == '[') { i++; if(command[i] == ' ') { for(; command[i] != '\0'; i++) { if(command[i] == ']') { endBracket = false; if(command[i - 1] == ' ') { brackets = true; return true; } else { brackets = true; cout << "Need a space before ]\n"; return false; } } } if(endBracket) { cout << "Missing ]\n"; brackets = true; return false; } } else { brackets = true; cout << "Need a space after [\n"; return false; } } return false; } bool run_test(char command[]) { bool file = false; bool dir = false; bool exist = false; int i = 1; for(; command[i] == ' '; i++){} // gets rid of spaces between [ and flag if(command[i] == '-') { i++; if(command[i] == 'f') { file = true; i++; } else if(command[i] == 'd') { dir = true; i++; } else if(command[i] == 'e' || command[i] == ' ') { exist = true; i++; } else { cout << "Error, invalid flag\n"; return false; } } else if(command[i] != '-') { cout << "Error, missing flag\n"; return false; } char fix_command[100]; for(; command[i] == ' '; i++){} // to skip all the spaces between the flag and the argument if(command[i] != '\0') { int j = 0; for(; command[i] != '\0' && command[i] != ' '; i++) { fix_command[j] = command[i]; j++; } fix_command[j] = '\0'; } else { cout << "Invalid argument with flag\n"; return false; } if(exist) { struct stat exist; if(stat(fix_command, &exist) == 0) { cout << "(True)\n"; return true; } else { cout << "(False)\n"; return false; } } else if(file) { struct stat file; stat(fix_command, &file); if(S_ISREG(file.st_mode) != 0) { cout << "(True)\n"; return true; } else { cout << "(False)\n"; return false; } } else if(dir) { struct stat dir; stat(fix_command, &dir); if(S_ISDIR(dir.st_mode) != 0) { cout << "(True)\n"; return true; } else { cout << "(False)\n"; return false; } } return false; } void run_line(char *command_line[]) { pid_t pid; int status; if((pid = fork()) < 0) { perror("forking failed"); } else if(pid == 0) { if(execvp(*command_line,command_line) < 0) { perror("execvp failed"); exit(1); } } else { while(wait(&status) != pid) ; } return; } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string> #include <string.h> #include <sys/wait.h> #include <sys/types.h> #include <limits> using namespace std; void displayPrompt(){ char *user = getlogin(); //I assign the login name to a user pointer if(user == NULL){ perror("getlogin"); exit(1); } char hostname[100]; //I allocate space for the hostname if(gethostname(hostname, sizeof(hostname)) == -1){ //checking for errors withostname perror("gethostname"); exit(1); } cout << user << '@' << hostname << '$' << ' '; //here I output the user and hostanme to the screen. } int extractCommands(string &commandLine, char **cmds){ const char* args = commandLine.c_str(); //the user input is converted to a const char* as we need it for execvp char* args_Mutatable = const_cast<char*>(args); //it needs to be mutable for us to tokenize it char *single_command; single_command = strtok(args_Mutatable, " ;&|"); //execute strtok with delimeters int numOfArgs = 0; //when you add one --> argv[1] while(single_command != NULL){ //cout << single_command << endl; cmds[numOfArgs] = strdup(single_command); //this processes each command into the command array for execution cout << "at position " << numOfArgs << ": " << cmds[numOfArgs]; cout << endl; single_command = strtok(NULL, " ;&|"); numOfArgs++; } cmds[numOfArgs] = NULL; return numOfArgs; } int executeCommand(char **args){ int pid = fork(); if(pid == -1){ perror("There was some error with fork()"); exit(1); } else if(pid == 0){ if(-1 == execvp(/*args[0]*/ *args, args)){ perror("There was an error with execvp"); exit(1); } } else if(pid > 0){ if(-1 == wait(0)){ perror("There was an error with wait()"); } } return 0; //if everything goes well, return 0 } void extractConnectors(string commandLine, char **cmds){ vector<string> connectors; for(unsigned int i = 0; i < commandLine.size(); ++i){ if(commandLine.at(i) == ';'){ connectors.push_back(";"); } if((commandLine.at(i) == '&' && commandLine.at(i+1) == '&')){ connectors.push_back("&&"); } if((commandLine.at(i) == '|' && commandLine.at(i+1) == '|')){ connectors.push_back("||"); } } for(unsigned int i = 0; i < connectors.size(); ++i){ if(connectors.at(i) == ";"){ if(executeCommand(cmds) != 0){ cout << "Error in parsing arguments" << endl; } } } } int main(){ string userInput; //command line in string format char *cmds[10000]; do{ displayPrompt(); //displays current user and hostname getline(cin, userInput); //get's input from user and stores it in a string //cout << userInput << endl; //NEED TO DELETE UPON COMPLETETION int numArgs = extractCommands(userInput, cmds); //retrieve number of arguments by parsing the string if(numArgs <= 0){continue;} //if there are no arguments, simply continue to the next iteration /*checks if first argument is exit and quits iff it's the only argument*/ if( (strcmp(cmds[0], "exit") == 0) && (numArgs == 1) ) { break; } //extractConnectors(userInput, cmds); if(executeCommand(cmds) != 0){ cout << "Error in executing commands" << endl; } }while(1); return 0; } <commit_msg>hope i'm making progress..<commit_after>#include <iostream> #include <vector> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string> #include <string.h> #include <sys/wait.h> #include <sys/types.h> #include <limits> using namespace std; void displayPrompt(){ char *user = getlogin(); //I assign the login name to a user pointer if(user == NULL){ perror("getlogin"); exit(1); } char hostname[100]; //I allocate space for the hostname if(gethostname(hostname, sizeof(hostname)) == -1){ //checking for errors withostname perror("gethostname"); exit(1); } cout << user << '@' << hostname << '$' << ' '; //here I output the user and hostanme to the screen. } int extractCommands(string &commandLine, char **cmds){ const char* args = commandLine.c_str(); //the user input is converted to a const char* as we need it for execvp char* args_Mutatable = const_cast<char*>(args); //it needs to be mutable for us to tokenize it char *single_command; single_command = strtok(args_Mutatable, " ;&|"); //execute strtok with delimeters int numOfArgs = 0; //when you add one --> argv[1] while(single_command != NULL){ //cout << single_command << endl; cmds[numOfArgs] = strdup(single_command); //this processes each command into the command array for execution cout << "at position " << numOfArgs << ": " << cmds[numOfArgs]; cout << endl; single_command = strtok(NULL, " ;&|"); numOfArgs++; } cmds[numOfArgs] = NULL; return numOfArgs; } int executeCommand(int pos, char **args){ int pid = fork(); if(pid == -1){ perror("There was some error with fork()"); exit(1); } else if(pid == 0){ if(-1 == execvp(/*args[0]*/ args[pos], args)){ perror("There was an error with execvp"); exit(1); } } else if(pid > 0){ if(-1 == wait(0)){ perror("There was an error with wait()"); } } return 0; //if everything goes well, return 0 } vector<string> extractConnectors(string inputLine){ vector<string> cnctors; for(unsigned int i = 0; i < inputLine.size(); ++i){ if(inputLine.at(i) == ';'){ cnctors.push_back(";"); } if((inputLine.at(i) == '&' && inputLine.at(i+1) == '&')){ cnctors.push_back("&&"); } if((inputLine.at(i) == '|' && inputLine.at(i+1) == '|')){ cnctors.push_back("||"); } } return cnctors; } int main(){ string userInput; //command line in string format char *cmds[10000]; do{ displayPrompt(); //displays current user and hostname getline(cin, userInput); //get's input from user and stores it in a string /*gets all the delimeters and stores into a vector*/ vector<string> connectors = extractConnectors(userInput); cout << "CONNECTORS: "; for(unsigned i = 0; i < connectors.size(); ++i){ cout << connectors.at(i) << ' '; } cout << endl; //cout << userInput << endl; //NEED TO DELETE UPON COMPLETETION int numArgs = extractCommands(userInput, cmds); //retrieve number of arguments by parsing the string if(numArgs <= 0){continue;} //if there are no arguments, simply continue to the next iteration /*checks if first argument is exit and quits iff it's the only argument*/ if( (strcmp(cmds[0], "exit") == 0) && (numArgs == 1) ) { break; } /*if(executeCommand(cmds) != 0){ cout << "Error in executing commands" << endl; }*/ }while(1); return 0; } <|endoftext|>
<commit_before>#include <silicium/async_process.hpp> #include <silicium/http/generate_response.hpp> #include <silicium/http/receive_request.hpp> #include <silicium/asio/tcp_acceptor.hpp> #include <silicium/asio/writing_observable.hpp> #include <silicium/sink/iterator_sink.hpp> #include <silicium/observable/spawn_coroutine.hpp> #include <silicium/absolute_path.hpp> #include <iostream> #include <array> #include <boost/program_options.hpp> namespace { void respond(boost::asio::ip::tcp::socket &client, Si::memory_range status, Si::memory_range status_text, Si::memory_range content, Si::spawn_context &yield) { std::vector<char> response; auto const response_sink = Si::make_container_sink(response); Si::http::generate_status_line(response_sink, "HTTP/1.1", status, status_text); Si::http::generate_header(response_sink, "Content-Length", boost::lexical_cast<Si::noexcept_string>(content.size())); Si::http::generate_header(response_sink, "Content-Type", "text/html"); Si::http::finish_headers(response_sink); Si::append(response_sink, content); boost::system::error_code error = Si::asio::write(client, Si::make_memory_range(response), yield); if (!!error) { std::cerr << "Could not respond to " << client.remote_endpoint() << ": " << error << '\n'; } else { client.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error); if (!!error) { std::cerr << "Could not shutdown connection to " << client.remote_endpoint() << ": " << error << '\n'; } } } bool handle_error(boost::system::error_code error, char const *message) { if (error) { std::cerr << message << ": " << error << '\n'; return true; } return false; } void clone( std::string const &repository, Si::absolute_path const &repository_cache) { Si::async_process_parameters parameters; parameters.executable = *Si::absolute_path::create("/usr/bin/git"); parameters.arguments.emplace_back("clone"); parameters.arguments.emplace_back(repository.c_str()); parameters.arguments.emplace_back(repository_cache.c_str()); parameters.current_path = repository_cache; auto output = Si::make_pipe().get(); auto input = Si::make_pipe().get(); Si::error_or<Si::async_process> maybe_process = Si::launch_process(parameters, input.read.handle, output.write.handle, output.write.handle); if (handle_error(maybe_process.error(), "Could not create git process")) { return; } input.read.close(); output.write.close(); Si::async_process &process = maybe_process.get(); for (;;) { std::array<char, 8192> read_buffer; ssize_t const read_result = read(output.read.handle, read_buffer.data(), read_buffer.size()); if (read_result < 0) { int errno_ = errno; boost::system::error_code error(errno_, boost::system::get_system_category()); std::cerr << "Reading the output of the process failed with " << error << '\n'; break; } if (read_result == 0) { //end of output break; } std::cerr.write(read_buffer.data(), read_result); } int const result = process.wait_for_exit().get(); if (result != 0) { std::cerr << "Git clone failed\n"; return; } } void trigger_build( std::string const &repository, Si::absolute_path const &repository_cache) { if (handle_error(Si::create_directories(repository_cache), "Could not create repository cache directory")) { return; } if (!Si::file_exists(repository_cache / Si::relative_path(".git"))) { std::cerr << "The cache does not exist. Doing an initial clone of " << repository << "\n"; clone(repository, repository_cache); std::cerr << "Created initial clone of the repository\n"; } } } int main(int argc, char **argv) { std::string repository; std::string cache; boost::uint16_t listen_port = 8080; boost::program_options::options_description options("options"); options.add_options() ("help,h", "produce help message") ("repository,r", boost::program_options::value(&repository), "the Git URI to clone from") ("cache,c", boost::program_options::value(&cache), "the directory to use as a cache for the repository") ("port,p", boost::program_options::value(&listen_port), "the port to listen on for HTTP requests") ; boost::program_options::positional_options_description positional; positional.add("repository", 1); positional.add("cache", 1); boost::program_options::variables_map variables; try { boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(options).positional(positional).run(), variables); boost::program_options::notify(variables); } catch (boost::program_options::error const &ex) { std::cerr << options << '\n'; std::cerr << ex.what() << '\n'; return 1; } if (variables.count("help")) { std::cerr << options << '\n'; return 0; } if (repository.empty() || cache.empty()) { std::cerr << options << '\n'; std::cerr << "Missing option\n"; return 1; } Si::absolute_path const absolute_cache = *Si::absolute_path::create(boost::filesystem::absolute(cache)); boost::asio::io_service io; Si::spawn_coroutine([&io, listen_port, &repository, &absolute_cache](Si::spawn_context yield) { auto acceptor = Si::asio::make_tcp_acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), listen_port)); for (;;) { std::shared_ptr<boost::asio::ip::tcp::socket> client = (*yield.get_one(Si::ref(acceptor))).get(); assert(client); Si::spawn_coroutine([client = std::move(client), &repository, &absolute_cache](Si::spawn_context yield) { Si::error_or<Si::optional<Si::http::request>> const received = Si::http::receive_request(*client, yield); if (received.is_error()) { std::cerr << "Error when receiving request from " << client->remote_endpoint() << ": " << received.error() << '\n'; return; } Si::optional<Si::http::request> const &maybe_request = received.get(); if (!maybe_request) { return respond(*client, Si::make_c_str_range("400"), Si::make_c_str_range("Bad Request"), Si::make_c_str_range("the server could not parse the request"), yield); } Si::http::request const &request = *maybe_request; if (request.method != "POST" && request.method != "GET") { return respond(*client, Si::make_c_str_range("405"), Si::make_c_str_range("Method Not Allowed"), Si::make_c_str_range("this HTTP method is not supported by this server"), yield); } if (request.path != "/") { return respond(*client, Si::make_c_str_range("404"), Si::make_c_str_range("Not Found"), Si::make_c_str_range("unknown path"), yield); } if (request.method == "POST") { trigger_build(repository, absolute_cache); } char const * const page = "<html>" "<body>" "<form action=\"/\" method=\"POST\">" "<input type=\"submit\" value=\"Trigger build\"/>" "</form>" "</body>" "</html>"; return respond(*client, Si::make_c_str_range("200"), Si::make_c_str_range("OK"), Si::make_c_str_range(page), yield); }); } }); io.run(); } <commit_msg>split functions and reduce nesting<commit_after>#include <silicium/async_process.hpp> #include <silicium/http/generate_response.hpp> #include <silicium/http/receive_request.hpp> #include <silicium/asio/tcp_acceptor.hpp> #include <silicium/asio/writing_observable.hpp> #include <silicium/sink/iterator_sink.hpp> #include <silicium/observable/spawn_coroutine.hpp> #include <silicium/absolute_path.hpp> #include <iostream> #include <array> #include <boost/program_options.hpp> namespace { void respond(boost::asio::ip::tcp::socket &client, Si::memory_range status, Si::memory_range status_text, Si::memory_range content, Si::spawn_context &yield) { std::vector<char> response; auto const response_sink = Si::make_container_sink(response); Si::http::generate_status_line(response_sink, "HTTP/1.1", status, status_text); Si::http::generate_header(response_sink, "Content-Length", boost::lexical_cast<Si::noexcept_string>(content.size())); Si::http::generate_header(response_sink, "Content-Type", "text/html"); Si::http::finish_headers(response_sink); Si::append(response_sink, content); boost::system::error_code error = Si::asio::write(client, Si::make_memory_range(response), yield); if (!!error) { std::cerr << "Could not respond to " << client.remote_endpoint() << ": " << error << '\n'; return; } client.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error); if (!!error) { std::cerr << "Could not shutdown connection to " << client.remote_endpoint() << ": " << error << '\n'; } } bool handle_error(boost::system::error_code error, char const *message) { if (error) { std::cerr << message << ": " << error << '\n'; return true; } return false; } enum class output_chunk_result { more, finished }; output_chunk_result handle_output_chunk(Si::native_file_descriptor readable_output) { std::array<char, 8192> read_buffer; ssize_t const read_result = read(readable_output, read_buffer.data(), read_buffer.size()); if (read_result < 0) { int errno_ = errno; boost::system::error_code error(errno_, boost::system::get_system_category()); std::cerr << "Reading the output of the process failed with " << error << '\n'; return output_chunk_result::finished; } if (read_result == 0) { //end of output return output_chunk_result::finished; } std::cerr.write(read_buffer.data(), read_result); return output_chunk_result::more; } void clone( std::string const &repository, Si::absolute_path const &repository_cache) { Si::async_process_parameters parameters; parameters.executable = *Si::absolute_path::create("/usr/bin/git"); parameters.arguments.emplace_back("clone"); parameters.arguments.emplace_back(repository.c_str()); parameters.arguments.emplace_back(repository_cache.c_str()); parameters.current_path = repository_cache; auto output = Si::make_pipe().get(); auto input = Si::make_pipe().get(); Si::error_or<Si::async_process> maybe_process = Si::launch_process(parameters, input.read.handle, output.write.handle, output.write.handle); if (handle_error(maybe_process.error(), "Could not create git process")) { return; } input.read.close(); output.write.close(); Si::async_process &process = maybe_process.get(); for (bool more = true; more;) { switch (handle_output_chunk(output.read.handle)) { case output_chunk_result::more: break; case output_chunk_result::finished: more = false; break; } } int const result = process.wait_for_exit().get(); if (result != 0) { std::cerr << "Git clone failed\n"; return; } } void trigger_build( std::string const &repository, Si::absolute_path const &repository_cache) { if (handle_error(Si::create_directories(repository_cache), "Could not create repository cache directory")) { return; } if (!Si::file_exists(repository_cache / Si::relative_path(".git"))) { std::cerr << "The cache does not exist. Doing an initial clone of " << repository << "\n"; clone(repository, repository_cache); std::cerr << "Created initial clone of the repository\n"; } } void serve_web_client( boost::asio::ip::tcp::socket &client, std::string const &repository, Si::absolute_path const &repository_cache, Si::spawn_context &yield) { Si::error_or<Si::optional<Si::http::request>> const received = Si::http::receive_request(client, yield); if (received.is_error()) { std::cerr << "Error when receiving request from " << client.remote_endpoint() << ": " << received.error() << '\n'; return; } Si::optional<Si::http::request> const &maybe_request = received.get(); if (!maybe_request) { return respond(client, Si::make_c_str_range("400"), Si::make_c_str_range("Bad Request"), Si::make_c_str_range("the server could not parse the request"), yield); } Si::http::request const &request = *maybe_request; if (request.method != "POST" && request.method != "GET") { return respond(client, Si::make_c_str_range("405"), Si::make_c_str_range("Method Not Allowed"), Si::make_c_str_range("this HTTP method is not supported by this server"), yield); } if (request.path != "/") { return respond(client, Si::make_c_str_range("404"), Si::make_c_str_range("Not Found"), Si::make_c_str_range("unknown path"), yield); } if (request.method == "POST") { trigger_build(repository, repository_cache); } char const * const page = "<html>" "<body>" "<form action=\"/\" method=\"POST\">" "<input type=\"submit\" value=\"Trigger build\"/>" "</form>" "</body>" "</html>"; return respond(client, Si::make_c_str_range("200"), Si::make_c_str_range("OK"), Si::make_c_str_range(page), yield); } void handle_client( std::shared_ptr<boost::asio::ip::tcp::socket> client, std::string const &repository, Si::absolute_path const &repository_cache) { assert(client); Si::spawn_coroutine([client = std::move(client), &repository, &repository_cache](Si::spawn_context yield) { serve_web_client(*client, repository, repository_cache, yield); }); } } int main(int argc, char **argv) { std::string repository; std::string cache; boost::uint16_t listen_port = 8080; boost::program_options::options_description options("options"); options.add_options() ("help,h", "produce help message") ("repository,r", boost::program_options::value(&repository), "the Git URI to clone from") ("cache,c", boost::program_options::value(&cache), "the directory to use as a cache for the repository") ("port,p", boost::program_options::value(&listen_port), "the port to listen on for HTTP requests") ; boost::program_options::positional_options_description positional; positional.add("repository", 1); positional.add("cache", 1); boost::program_options::variables_map variables; try { boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(options).positional(positional).run(), variables); boost::program_options::notify(variables); } catch (boost::program_options::error const &ex) { std::cerr << options << '\n'; std::cerr << ex.what() << '\n'; return 1; } if (variables.count("help")) { std::cerr << options << '\n'; return 0; } if (repository.empty() || cache.empty()) { std::cerr << options << '\n'; std::cerr << "Missing option\n"; return 1; } Si::absolute_path const absolute_cache = *Si::absolute_path::create(boost::filesystem::absolute(cache)); boost::asio::io_service io; Si::spawn_coroutine([&io, listen_port, &repository, &absolute_cache](Si::spawn_context yield) { auto acceptor = Si::asio::make_tcp_acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), listen_port)); for (;;) { std::shared_ptr<boost::asio::ip::tcp::socket> client = (*yield.get_one(Si::ref(acceptor))).get(); handle_client(std::move(client), repository, absolute_cache); } }); io.run(); } <|endoftext|>
<commit_before>#include <iostream> #include <cstring> #include <cstdio> #include <queue> #include <cstdlib> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <errno.h> #include "rshell.h" using namespace std; //Function which finds all the connectors in a char string and puts //them in a queue queue<char> findConnectors(char cmdCharString[]) { queue<char> connectorQueue; //Create a pointer pointing to the first occurance of a connector char* connectorPointer = strpbrk(cmdCharString, "|;&#"); //Create a bool for keeping track of doubles bool conDoubCatcher = false; bool hashCatcher = false; //Loop to find all connectors and put them in the queue while (connectorPointer != NULL && hashCatcher == false) { //Store the characters for each connector if (!conDoubCatcher) { //Push connector character into command queue if ((*connectorPointer == '&' || *connectorPointer == '|') && (*connectorPointer == *(connectorPointer + 1))) { connectorQueue.push(*connectorPointer); conDoubCatcher = true; } //Do not store single & or | and throw error else if ((*connectorPointer == '&' || *connectorPointer == '|') && (*connectorPointer != *(connectorPointer + 1))) { cout << "ERROR: Invalid connector: " << *connectorPointer << endl; exit(1); } else if (*connectorPointer == '#' && *(connectorPointer - 1) == ' ') { connectorQueue.push(*connectorPointer); hashCatcher = true; } else if (*connectorPointer == ';') connectorQueue.push(*connectorPointer); } else conDoubCatcher = false; //Go to the next occurance of a connector character connectorPointer = strpbrk(connectorPointer + 1, "|;&#"); } //return queue with all found connectors return connectorQueue; } //Read through input until first non whitespace char and if hash then return //true else return false bool firstCharHash(string cmdString) { if (cmdString.find_first_not_of(" \t\r\n") != string::npos && cmdString.at(cmdString.find_first_not_of(" \t\r\n")) == '#') return true; return false; } //Finds the commands and stores them in a queue for later use queue<char*> findCommands(char cmdCharString[]) { queue<char*> commandQueue; //Create pointers for finding commands and connectors char* conPointer = strpbrk(cmdCharString, "|;&#"); char* cmdCharPointer = NULL; //point at commands based on # placement if (conPointer != NULL && *conPointer == '#' && *(conPointer - 1) != ' ') { cmdCharPointer = strtok(cmdCharString, "|;&"); } else { cmdCharPointer = strtok(cmdCharString, "|;&#"); } //Go through command cString and find commands while (cmdCharPointer != NULL) { //Get rid of space in begining of command while (*cmdCharPointer == ' ') cmdCharPointer++; //Add the command to the queue commandQueue.push(cmdCharPointer); //Add commands based on # placement if (conPointer != NULL) { conPointer = strpbrk(conPointer + 1, "|;&#"); if (conPointer != NULL) { if(*conPointer == '#' && *(conPointer - 1) != ' ') cmdCharPointer = strtok(NULL, "|;&"); else cmdCharPointer = strtok(NULL, "|;&#"); } else cmdCharPointer = strtok(NULL, "|;&#"); } else cmdCharPointer = strtok(NULL, "|;&#"); } return commandQueue; } //Checks for starting connector with no previous command void checkForStartingConnectors(char cmdCharString[]) { char* cmdCharPointer = cmdCharString; while (*cmdCharPointer == ' ') cmdCharPointer++; if (cmdCharPointer != NULL && (cmdCharPointer + 1) != NULL && ((*cmdCharPointer == '&' && *(cmdCharPointer + 1) == '&') || (*cmdCharPointer == '|' && *(cmdCharPointer + 1) == '|'))) { cout << "ERROR: syntax error near unexpected token \'" << *cmdCharPointer << *cmdCharPointer << "\'" << endl; exit(1); } if (cmdCharPointer != NULL && *cmdCharPointer == ';') { cout << "ERROR: syntax error near unexpected token \'" << *cmdCharPointer << "\'" << endl; exit(1); } } //Creates a queue with the seperate arguments for a command queue<char*> seperateCommand(char command[]) { queue<char*> sepComQueue; char* cmdCharPointer = strtok(command, " "); while (cmdCharPointer != NULL) { sepComQueue.push(cmdCharPointer); cmdCharPointer = strtok(NULL, " "); } return sepComQueue; } //Fills the 2D array with all arguments for running the command void fillArgsArray(char** args, queue<char*> sepComQueue) { unsigned i; for (i = 0; !sepComQueue.empty(); i++) { args[i] = sepComQueue.front(); sepComQueue.pop(); } args[i] = NULL; } //Runs the command and returns true if success else return false bool runCommand(char** args) { //Create bool to store whether command execution was a success bool ynSuccess = true; pid_t pid; int status; //Run fork and get parent id //If an error while forking occurs then say so and exit if ((pid = fork()) < 0) { cout << "ERROR: forking child process failed" << endl; exit(1); } else if (pid == 0) { //Run the command if(execvp(*args, args) < 0) perror(NULL); } else { //Wait for completion while (wait(&status) != pid); //Tests if command executed properly and if not sets success to false if (WIFEXITED(status)) { if (WEXITSTATUS(status) != 0) { ynSuccess = false; } } else { ynSuccess = false; } } return ynSuccess; } //Function to run the shell void rshell() { while(true) { //Output Command prompt cout << "$ "; //Take in command and store it in a c-string string cmdString; getline(cin, cmdString); char* cmdCharString = new char[cmdString.size() + 1]; strcpy(cmdCharString, cmdString.c_str()); //For making testing with files better looking cout << endl; //Check for bad starting connectors checkForStartingConnectors(cmdCharString); //Catches specific case for Connector followed by # with no command //in between char* findHash = strpbrk(cmdCharString, "#"); if (findHash != NULL && findHash != cmdCharString) { findHash--; while (*findHash == ' ' && findHash != cmdCharString) findHash--; if (*findHash == '&' || *findHash == '|') { cout << "ERROR: Command string ends in " << *findHash << *findHash << " and has no following command" << endl; exit(1); } } //Check for two connectors with no command inbetween char* findDoubleConnectors = strpbrk(cmdCharString, ";&|"); while (findDoubleConnectors != NULL && findDoubleConnectors != cmdCharString) { bool skipChecking = false; char* temp = findDoubleConnectors; if(*temp == ';') temp--; else if((*temp == '|' || *temp == '&') && (*(temp - 1) == *temp)) temp = temp - 2; else if((*temp == '|' || *temp == '&') && (*(temp - 1) != *temp)) skipChecking = true; while (*temp == ' ' && temp != cmdCharString && !skipChecking) temp--; if ((*temp == '&' || *temp == '|') && !skipChecking) { cout << "Syntax error near unexpected token \'" << *temp << *temp << "\'" << endl; exit(1); } else if(*temp == ';' && !skipChecking) { cout << "Syntax error near unexpected token \'" << *temp << "\'" << endl; exit(1); } findDoubleConnectors = strpbrk(findDoubleConnectors + 1, ";&|"); } //Create a queue filled with connectors in order using findConnectors() queue<char> connectorCharQueue = findConnectors(cmdCharString); //Create a queue filled with commands in order using findCommands() queue<char*> commandQueue = findCommands(cmdCharString); //Makes sure the string doesn't end in a '&&' or '||' connector if (commandQueue.size() <= connectorCharQueue.size() && (connectorCharQueue.back() == '|' || connectorCharQueue.back() == '&')) { cout << "ERROR: Command string ends in " << connectorCharQueue.back() << connectorCharQueue.back() << " and has no following command" << endl; exit(1); } //Create a queue of connector* based on the connectorCharQueue queue<connector*> connectorQueue; while (!connectorCharQueue.empty() && connectorCharQueue.front() != '#') { if (connectorCharQueue.front() == '&') { andConnector* p = new andConnector(); connectorQueue.push(p); } else if (connectorCharQueue.front() == '|') { orConnector* p = new orConnector(); connectorQueue.push(p); } else { semiColonConnector* p = new semiColonConnector(); connectorQueue.push(p); } connectorCharQueue.pop(); } //Create bool to store whether command execution was a success bool ynSuccess = true; //Create a bool for checking if the first non space character is a hash bool firstHash = firstCharHash(cmdString); //Run commands until we run out of commands to call //Don't run if first char is a hash while (!commandQueue.empty() && !firstHash) { //Creates a queue with the seperate arguments for a command queue<char*> sepComQueue = seperateCommand(commandQueue.front()); //Take one out of the queue of commands which need to be run commandQueue.pop(); //Create a 2D array and store all arguments for command unsigned argsSize = sepComQueue.size() + 1; char** args = new char*[argsSize]; fillArgsArray(args, sepComQueue); //If command is exit then exit if(strcmp(*args, "exit") == 0) exit(0); //Run the command and store whether it was a success ynSuccess = runCommand(args); //Handles connectors if (!connectorQueue.empty()) { while (!connectorQueue.empty() && !commandQueue.empty() && !(connectorQueue.front()->isGoodOrNot(ynSuccess))) { commandQueue.pop(); connector* p = connectorQueue.front(); delete p; connectorQueue.pop(); } connector* p = connectorQueue.front(); delete p; connectorQueue.pop(); //Special case to check for semi colon followed by # with no command //in between and at the end of command string if (connectorQueue.empty() && connectorCharQueue.front() == '#') { char* sCHashCatcherString = new char[cmdString.size() + 1]; strcpy(sCHashCatcherString, commandQueue.front()); char* semiColonHashCatcher = strtok(sCHashCatcherString, " "); if (semiColonHashCatcher == NULL) { delete[] sCHashCatcherString; exit(0); } delete[] sCHashCatcherString; } } else if (!connectorCharQueue.empty()) { if (connectorCharQueue.front() == '#') exit(0); } delete[] args; } delete[] cmdCharString; } }<commit_msg>Fixed the spacing so the added loop doesn't ruin the 80 character line limit<commit_after>#include <iostream> #include <cstring> #include <cstdio> #include <queue> #include <cstdlib> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <errno.h> #include "rshell.h" using namespace std; //Function which finds all the connectors in a char string and puts //them in a queue queue<char> findConnectors(char cmdCharString[]) { queue<char> connectorQueue; //Create a pointer pointing to the first occurance of a connector char* connectorPointer = strpbrk(cmdCharString, "|;&#"); //Create a bool for keeping track of doubles bool conDoubCatcher = false; bool hashCatcher = false; //Loop to find all connectors and put them in the queue while (connectorPointer != NULL && hashCatcher == false) { //Store the characters for each connector if (!conDoubCatcher) { //Push connector character into command queue if ((*connectorPointer == '&' || *connectorPointer == '|') && (*connectorPointer == *(connectorPointer + 1))) { connectorQueue.push(*connectorPointer); conDoubCatcher = true; } //Do not store single & or | and throw error else if ((*connectorPointer == '&' || *connectorPointer == '|') && (*connectorPointer != *(connectorPointer + 1))) { cout << "ERROR: Invalid connector: " << *connectorPointer << endl; exit(1); } else if (*connectorPointer == '#' && *(connectorPointer - 1) == ' ') { connectorQueue.push(*connectorPointer); hashCatcher = true; } else if (*connectorPointer == ';') connectorQueue.push(*connectorPointer); } else conDoubCatcher = false; //Go to the next occurance of a connector character connectorPointer = strpbrk(connectorPointer + 1, "|;&#"); } //return queue with all found connectors return connectorQueue; } //Read through input until first non whitespace char and if hash then return //true else return false bool firstCharHash(string cmdString) { if (cmdString.find_first_not_of(" \t\r\n") != string::npos && cmdString.at(cmdString.find_first_not_of(" \t\r\n")) == '#') return true; return false; } //Finds the commands and stores them in a queue for later use queue<char*> findCommands(char cmdCharString[]) { queue<char*> commandQueue; //Create pointers for finding commands and connectors char* conPointer = strpbrk(cmdCharString, "|;&#"); char* cmdCharPointer = NULL; //point at commands based on # placement if (conPointer != NULL && *conPointer == '#' && *(conPointer - 1) != ' ') { cmdCharPointer = strtok(cmdCharString, "|;&"); } else { cmdCharPointer = strtok(cmdCharString, "|;&#"); } //Go through command cString and find commands while (cmdCharPointer != NULL) { //Get rid of space in begining of command while (*cmdCharPointer == ' ') cmdCharPointer++; //Add the command to the queue commandQueue.push(cmdCharPointer); //Add commands based on # placement if (conPointer != NULL) { conPointer = strpbrk(conPointer + 1, "|;&#"); if (conPointer != NULL) { if(*conPointer == '#' && *(conPointer - 1) != ' ') cmdCharPointer = strtok(NULL, "|;&"); else cmdCharPointer = strtok(NULL, "|;&#"); } else cmdCharPointer = strtok(NULL, "|;&#"); } else cmdCharPointer = strtok(NULL, "|;&#"); } return commandQueue; } //Checks for starting connector with no previous command void checkForStartingConnectors(char cmdCharString[]) { char* cmdCharPointer = cmdCharString; while (*cmdCharPointer == ' ') cmdCharPointer++; if (cmdCharPointer != NULL && (cmdCharPointer + 1) != NULL && ((*cmdCharPointer == '&' && *(cmdCharPointer + 1) == '&') || (*cmdCharPointer == '|' && *(cmdCharPointer + 1) == '|'))) { cout << "ERROR: syntax error near unexpected token \'" << *cmdCharPointer << *cmdCharPointer << "\'" << endl; exit(1); } if (cmdCharPointer != NULL && *cmdCharPointer == ';') { cout << "ERROR: syntax error near unexpected token \'" << *cmdCharPointer << "\'" << endl; exit(1); } } //Creates a queue with the seperate arguments for a command queue<char*> seperateCommand(char command[]) { queue<char*> sepComQueue; char* cmdCharPointer = strtok(command, " "); while (cmdCharPointer != NULL) { sepComQueue.push(cmdCharPointer); cmdCharPointer = strtok(NULL, " "); } return sepComQueue; } //Fills the 2D array with all arguments for running the command void fillArgsArray(char** args, queue<char*> sepComQueue) { unsigned i; for (i = 0; !sepComQueue.empty(); i++) { args[i] = sepComQueue.front(); sepComQueue.pop(); } args[i] = NULL; } //Runs the command and returns true if success else return false bool runCommand(char** args) { //Create bool to store whether command execution was a success bool ynSuccess = true; pid_t pid; int status; //Run fork and get parent id //If an error while forking occurs then say so and exit if ((pid = fork()) < 0) { cout << "ERROR: forking child process failed" << endl; exit(1); } else if (pid == 0) { //Run the command if(execvp(*args, args) < 0) perror(NULL); } else { //Wait for completion while (wait(&status) != pid); //Tests if command executed properly and if not sets success to false if (WIFEXITED(status)) { if (WEXITSTATUS(status) != 0) { ynSuccess = false; } } else { ynSuccess = false; } } return ynSuccess; } //Function to run the shell void rshell() { while(true) { //Output Command prompt cout << "$ "; //Take in command and store it in a c-string string cmdString; getline(cin, cmdString); char* cmdCharString = new char[cmdString.size() + 1]; strcpy(cmdCharString, cmdString.c_str()); //For making testing with files better looking cout << endl; //Check for bad starting connectors checkForStartingConnectors(cmdCharString); //Catches specific case for Connector followed by # with no command //in between char* findHash = strpbrk(cmdCharString, "#"); if (findHash != NULL && findHash != cmdCharString) { findHash--; while (*findHash == ' ' && findHash != cmdCharString) findHash--; if (*findHash == '&' || *findHash == '|') { cout << "ERROR: Command string ends in " << *findHash << *findHash << " and has no following command" << endl; exit(1); } } //Check for two connectors with no command inbetween char* findDoubleConnectors = strpbrk(cmdCharString, ";&|"); while (findDoubleConnectors != NULL && findDoubleConnectors != cmdCharString) { bool skipChecking = false; char* temp = findDoubleConnectors; if(*temp == ';') temp--; else if((*temp == '|' || *temp == '&') && (*(temp - 1) == *temp)) temp = temp - 2; else if((*temp == '|' || *temp == '&') && (*(temp - 1) != *temp)) skipChecking = true; while (*temp == ' ' && temp != cmdCharString && !skipChecking) temp--; if ((*temp == '&' || *temp == '|') && !skipChecking) { cout << "Syntax error near unexpected token \'" << *temp << *temp << "\'" << endl; exit(1); } else if(*temp == ';' && !skipChecking) { cout << "Syntax error near unexpected token \'" << *temp << "\'" << endl; exit(1); } findDoubleConnectors = strpbrk(findDoubleConnectors + 1, ";&|"); } //Create a queue filled with connectors in order using findConnectors() queue<char> connectorCharQueue = findConnectors(cmdCharString); //Create a queue filled with commands in order using findCommands() queue<char*> commandQueue = findCommands(cmdCharString); //Makes sure the string doesn't end in a '&&' or '||' connector if (commandQueue.size() <= connectorCharQueue.size() && (connectorCharQueue.back() == '|' || connectorCharQueue.back() == '&')) { cout << "ERROR: Command string ends in " << connectorCharQueue.back() << connectorCharQueue.back() << " and has no following command" << endl; exit(1); } //Create a queue of connector* based on the connectorCharQueue queue<connector*> connectorQueue; while (!connectorCharQueue.empty() && connectorCharQueue.front() != '#') { if (connectorCharQueue.front() == '&') { andConnector* p = new andConnector(); connectorQueue.push(p); } else if (connectorCharQueue.front() == '|') { orConnector* p = new orConnector(); connectorQueue.push(p); } else { semiColonConnector* p = new semiColonConnector(); connectorQueue.push(p); } connectorCharQueue.pop(); } //Create bool to store whether command execution was a success bool ynSuccess = true; //Create a bool for checking if the first non space character is a hash bool firstHash = firstCharHash(cmdString); //Run commands until we run out of commands to call //Don't run if first char is a hash while (!commandQueue.empty() && !firstHash) { //Creates a queue with the seperate arguments for a command queue<char*> sepComQueue = seperateCommand(commandQueue.front()); //Take one out of the queue of commands which need to be run commandQueue.pop(); //Create a 2D array and store all arguments for command unsigned argsSize = sepComQueue.size() + 1; char** args = new char*[argsSize]; fillArgsArray(args, sepComQueue); //If command is exit then exit if(strcmp(*args, "exit") == 0) exit(0); //Run the command and store whether it was a success ynSuccess = runCommand(args); //Handles connectors if (!connectorQueue.empty()) { while (!connectorQueue.empty() && !commandQueue.empty() && !(connectorQueue.front()->isGoodOrNot(ynSuccess))) { commandQueue.pop(); connector* p = connectorQueue.front(); delete p; connectorQueue.pop(); } connector* p = connectorQueue.front(); delete p; connectorQueue.pop(); //Special case to check for semi colon followed by # with //no command in between and at the end of command string if (connectorQueue.empty() && connectorCharQueue.front() == '#') { char* sCHashCatcherString = new char[cmdString.size() + 1]; strcpy(sCHashCatcherString, commandQueue.front()); char* semiColonHashCatcher = strtok(sCHashCatcherString, " "); if (semiColonHashCatcher == NULL) { delete[] sCHashCatcherString; exit(0); } delete[] sCHashCatcherString; } } else if (!connectorCharQueue.empty()) { if (connectorCharQueue.front() == '#') exit(0); } delete[] args; } delete[] cmdCharString; } }<|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef IOX_DDS_INTERNAL_GATEWAY_CHANNEL_INL #define IOX_DDS_INTERNAL_GATEWAY_CHANNEL_INL namespace iox { namespace dds { // Typedefs template <typename IceoryxTerminal> using IceoryxTerminalPool = iox::cxx::ObjectPool<IceoryxTerminal, MAX_CHANNEL_NUMBER>; template <typename DDSTerminal> using DDSTerminalPool = iox::cxx::ObjectPool<DDSTerminal, MAX_CHANNEL_NUMBER>; // Statics template <typename IceoryxTerminal, typename DDSTerminal> IceoryxTerminalPool<IceoryxTerminal> Channel<IceoryxTerminal, DDSTerminal>::s_iceoryxTerminals = IceoryxTerminalPool(); template <typename IceoryxTerminal, typename DDSTerminal> DDSTerminalPool<DDSTerminal> Channel<IceoryxTerminal, DDSTerminal>::s_ddsTerminals = DDSTerminalPool(); template <typename IceoryxTerminal, typename DDSTerminal> inline Channel<IceoryxTerminal, DDSTerminal>::Channel(const iox::capro::ServiceDescription& service, const IceoryxTerminalPtr iceoryxTerminal, const DDSTerminalPtr ddsTerminal) noexcept : m_service(service) , m_iceoryxTerminal(iceoryxTerminal) , m_ddsTerminal(ddsTerminal) , m_dataSize(0u) { } template <typename IceoryxTerminal, typename DDSTerminal> inline Channel<IceoryxTerminal, DDSTerminal>::Channel(const iox::capro::ServiceDescription& service, const IceoryxTerminalPtr iceoryxTerminal, const DDSTerminalPtr ddsTerminal, const uint64_t& dataSize) noexcept : m_service(service) , m_iceoryxTerminal(iceoryxTerminal) , m_ddsTerminal(ddsTerminal) , m_dataSize(dataSize) { } template <typename IceoryxTerminal, typename DDSTerminal> constexpr inline bool Channel<IceoryxTerminal, DDSTerminal>::operator==(const Channel<IceoryxTerminal, DDSTerminal>& rhs) const noexcept { return m_service == rhs.getService(); } template <typename IceoryxTerminal, typename DDSTerminal> inline iox::cxx::expected<Channel<IceoryxTerminal, DDSTerminal>, ChannelError> Channel<IceoryxTerminal, DDSTerminal>::create(const iox::capro::ServiceDescription& service) noexcept { return create(service); } template <typename IceoryxTerminal, typename DDSTerminal> inline iox::cxx::expected<Channel<IceoryxTerminal, DDSTerminal>, ChannelError> Channel<IceoryxTerminal, DDSTerminal>::create(const iox::capro::ServiceDescription& service, const uint64_t& dataSize) noexcept { // Create objects in the pool. auto rawIceoryxTerminalPtr = s_iceoryxTerminals.create(std::forward<const iox::capro::ServiceDescription>(service)); if (rawIceoryxTerminalPtr == nullptr) { return iox::cxx::error<ChannelError>(ChannelError::OBJECT_POOL_FULL); } auto rawDDSTerminalPtr = s_ddsTerminals.create(service.getServiceIDString(), service.getInstanceIDString(), service.getEventIDString()); if (rawDDSTerminalPtr == nullptr) { return iox::cxx::error<ChannelError>(ChannelError::OBJECT_POOL_FULL); } // Wrap in smart pointer with custom deleter to ensure automatic cleanup. auto iceoryxTerminalPtr = IceoryxTerminalPtr(rawIceoryxTerminalPtr, [](IceoryxTerminal* const p) { s_iceoryxTerminals.free(p); }); auto ddsTerminalPtr = DDSTerminalPtr(rawDDSTerminalPtr, [](DDSTerminal* const p) { s_ddsTerminals.free(p); }); return iox::cxx::success<Channel>(Channel(service, iceoryxTerminalPtr, ddsTerminalPtr, dataSize)); } template <typename IceoryxTerminal, typename DDSTerminal> inline iox::capro::ServiceDescription Channel<IceoryxTerminal, DDSTerminal>::getServiceDescription() const noexcept { return m_service; } template <typename IceoryxTerminal, typename DDSTerminal> inline std::shared_ptr<IceoryxTerminal> Channel<IceoryxTerminal, DDSTerminal>::getIceoryxTerminal() const noexcept { return m_iceoryxTerminal; } template <typename IceoryxTerminal, typename DDSTerminal> inline std::shared_ptr<DDSTerminal> Channel<IceoryxTerminal, DDSTerminal>::getDDSTerminal() const noexcept { return m_ddsTerminal; } template <typename IceoryxTerminal, typename DDSTerminal> inline iox::cxx::optional<uint64_t> Channel<IceoryxTerminal, DDSTerminal>::getDataSize() const noexcept { if (m_dataSize > 0) { return iox::cxx::make_optional<uint64_t>(m_dataSize); } else { return iox::cxx::nullopt_t(); } } } // namespace dds } // namespace iox #endif <commit_msg>iox-#65 Fix error from merge.<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef IOX_DDS_INTERNAL_GATEWAY_CHANNEL_INL #define IOX_DDS_INTERNAL_GATEWAY_CHANNEL_INL namespace iox { namespace dds { // Typedefs template <typename IceoryxTerminal> using IceoryxTerminalPool = iox::cxx::ObjectPool<IceoryxTerminal, MAX_CHANNEL_NUMBER>; template <typename DDSTerminal> using DDSTerminalPool = iox::cxx::ObjectPool<DDSTerminal, MAX_CHANNEL_NUMBER>; // Statics template <typename IceoryxTerminal, typename DDSTerminal> IceoryxTerminalPool<IceoryxTerminal> Channel<IceoryxTerminal, DDSTerminal>::s_iceoryxTerminals = IceoryxTerminalPool(); template <typename IceoryxTerminal, typename DDSTerminal> DDSTerminalPool<DDSTerminal> Channel<IceoryxTerminal, DDSTerminal>::s_ddsTerminals = DDSTerminalPool(); template <typename IceoryxTerminal, typename DDSTerminal> inline Channel<IceoryxTerminal, DDSTerminal>::Channel(const iox::capro::ServiceDescription& service, const IceoryxTerminalPtr iceoryxTerminal, const DDSTerminalPtr ddsTerminal) noexcept : m_service(service) , m_iceoryxTerminal(iceoryxTerminal) , m_ddsTerminal(ddsTerminal) , m_dataSize(0u) { } template <typename IceoryxTerminal, typename DDSTerminal> inline Channel<IceoryxTerminal, DDSTerminal>::Channel(const iox::capro::ServiceDescription& service, const IceoryxTerminalPtr iceoryxTerminal, const DDSTerminalPtr ddsTerminal, const uint64_t& dataSize) noexcept : m_service(service) , m_iceoryxTerminal(iceoryxTerminal) , m_ddsTerminal(ddsTerminal) , m_dataSize(dataSize) { } template <typename IceoryxTerminal, typename DDSTerminal> constexpr inline bool Channel<IceoryxTerminal, DDSTerminal>::operator==(const Channel<IceoryxTerminal, DDSTerminal>& rhs) const noexcept { return m_service == rhs.getService(); } template <typename IceoryxTerminal, typename DDSTerminal> inline iox::cxx::expected<Channel<IceoryxTerminal, DDSTerminal>, ChannelError> Channel<IceoryxTerminal, DDSTerminal>::create(const iox::capro::ServiceDescription& service) noexcept { return create(service, 0u); } template <typename IceoryxTerminal, typename DDSTerminal> inline iox::cxx::expected<Channel<IceoryxTerminal, DDSTerminal>, ChannelError> Channel<IceoryxTerminal, DDSTerminal>::create(const iox::capro::ServiceDescription& service, const uint64_t& dataSize) noexcept { // Create objects in the pool. auto rawIceoryxTerminalPtr = s_iceoryxTerminals.create(std::forward<const iox::capro::ServiceDescription>(service)); if (rawIceoryxTerminalPtr == nullptr) { return iox::cxx::error<ChannelError>(ChannelError::OBJECT_POOL_FULL); } auto rawDDSTerminalPtr = s_ddsTerminals.create(service.getServiceIDString(), service.getInstanceIDString(), service.getEventIDString()); if (rawDDSTerminalPtr == nullptr) { return iox::cxx::error<ChannelError>(ChannelError::OBJECT_POOL_FULL); } // Wrap in smart pointer with custom deleter to ensure automatic cleanup. auto iceoryxTerminalPtr = IceoryxTerminalPtr(rawIceoryxTerminalPtr, [](IceoryxTerminal* const p) { s_iceoryxTerminals.free(p); }); auto ddsTerminalPtr = DDSTerminalPtr(rawDDSTerminalPtr, [](DDSTerminal* const p) { s_ddsTerminals.free(p); }); return iox::cxx::success<Channel>(Channel(service, iceoryxTerminalPtr, ddsTerminalPtr, dataSize)); } template <typename IceoryxTerminal, typename DDSTerminal> inline iox::capro::ServiceDescription Channel<IceoryxTerminal, DDSTerminal>::getServiceDescription() const noexcept { return m_service; } template <typename IceoryxTerminal, typename DDSTerminal> inline std::shared_ptr<IceoryxTerminal> Channel<IceoryxTerminal, DDSTerminal>::getIceoryxTerminal() const noexcept { return m_iceoryxTerminal; } template <typename IceoryxTerminal, typename DDSTerminal> inline std::shared_ptr<DDSTerminal> Channel<IceoryxTerminal, DDSTerminal>::getDDSTerminal() const noexcept { return m_ddsTerminal; } template <typename IceoryxTerminal, typename DDSTerminal> inline iox::cxx::optional<uint64_t> Channel<IceoryxTerminal, DDSTerminal>::getDataSize() const noexcept { if (m_dataSize > 0) { return iox::cxx::make_optional<uint64_t>(m_dataSize); } else { return iox::cxx::nullopt_t(); } } } // namespace dds } // namespace iox #endif <|endoftext|>
<commit_before>#include <bitcoin/script.hpp> #include <stack> #include <bitcoin/messages.hpp> #include <bitcoin/transaction.hpp> #include <bitcoin/util/elliptic_curve_key.hpp> #include <bitcoin/util/assert.hpp> #include <bitcoin/util/logger.hpp> #include <bitcoin/util/ripemd.hpp> #include <bitcoin/util/sha256.hpp> namespace libbitcoin { void script::join(const script& other) { operations_.insert(operations_.end(), other.operations_.begin(), other.operations_.end()); } void script::push_operation(operation oper) { operations_.push_back(oper); } const operation_stack& script::operations() const { return operations_; } bool script::run(script input_script, const message::transaction& parent_tx, uint32_t input_index) { stack_.clear(); input_script.stack_.clear(); if (!input_script.run(parent_tx, input_index)) return false; stack_ = input_script.stack_; if (!run(parent_tx, input_index)) return false; if (stack_.size() != 0) { // TODO: OP_CHECKSIG actually leaves stuff on stack log_error() << "Script left junk on top of the stack"; return false; } return true; } bool script::run(const message::transaction& parent_tx, uint32_t input_index) { for (const operation oper: operations_) { //log_debug() << "Run: " << opcode_to_string(oper.code); if (!run_operation(oper, parent_tx, input_index)) return false; if (oper.data.size() > 0) { BITCOIN_ASSERT(oper.code == opcode::special || oper.code == opcode::pushdata1 || oper.code == opcode::pushdata2 || oper.code == opcode::pushdata4); stack_.push_back(oper.data); } } return true; } data_chunk script::pop_stack() { data_chunk value = stack_.back(); stack_.pop_back(); return value; } bool script::op_dup() { if (stack_.size() < 1) return false; stack_.push_back(stack_.back()); return true; } bool script::op_hash160() { if (stack_.size() < 1) return false; data_chunk data = pop_stack(); short_hash hash = generate_ripemd_hash(data); data_chunk raw_hash(hash.begin(), hash.end()); stack_.push_back(raw_hash); return true; } bool script::op_equalverify() { if (stack_.size() < 2) return false; return pop_stack() == pop_stack(); } inline void nullify_input_sequences( message::transaction_input_list& inputs, uint32_t except_input) { for (size_t i = 0; i < inputs.size(); ++i) if (i != except_input) inputs[i].sequence = 0; } bool script::op_checksig(message::transaction parent_tx, uint32_t input_index) { BITCOIN_ASSERT(input_index < parent_tx.inputs.size()); if (stack_.size() < 2) return false; data_chunk pubkey = pop_stack(), signature = pop_stack(); script script_code; for (operation op: operations_) { if (op.data == signature || op.code == opcode::codeseparator) continue; script_code.push_operation(op); } elliptic_curve_key key; key.set_public_key(pubkey); uint32_t hash_type = 0; hash_type = signature.back(); signature.pop_back(); if ((hash_type & 0x1f) == sighash::none) { parent_tx.outputs.clear(); nullify_input_sequences(parent_tx.inputs, input_index); } else if ((hash_type & 0x1f) == sighash::single) { uint32_t output_index = input_index; if (output_index >= parent_tx.outputs.size()) { log_error() << "sighash::single the output_index is out of range"; return false; } parent_tx.outputs.resize(output_index + 1); for (message::transaction_output& output: parent_tx.outputs) { output.value = ~0; output.output_script = script(); } nullify_input_sequences(parent_tx.inputs, input_index); } if (hash_type & sighash::anyone_can_pay) { parent_tx.inputs[0] = parent_tx.inputs[input_index]; parent_tx.inputs.resize(1); } if (input_index >= parent_tx.inputs.size()) { log_fatal() << "script::op_checksig() : input_index " << input_index << " is out of range."; return false; } message::transaction tx_tmp = parent_tx; // Blank all other inputs' signatures for (message::transaction_input& input: tx_tmp.inputs) input.input_script = script(); tx_tmp.inputs[input_index].input_script = script_code; hash_digest tx_hash = hash_transaction(tx_tmp, hash_type); return key.verify(tx_hash, signature); } bool script::run_operation(operation op, const message::transaction& parent_tx, uint32_t input_index) { switch (op.code) { case opcode::special: return true; case opcode::pushdata1: BITCOIN_ASSERT(op.data.size() == static_cast<size_t>(op.code)); return true; case opcode::pushdata2: BITCOIN_ASSERT(op.data.size() == static_cast<size_t>(op.code)); return true; case opcode::pushdata4: BITCOIN_ASSERT(op.data.size() == static_cast<size_t>(op.code)); return true; case opcode::nop: return true; case opcode::dup: return op_dup(); case opcode::hash160: return op_hash160(); case opcode::equalverify: return op_equalverify(); case opcode::checksig: return op_checksig(parent_tx, input_index); default: log_fatal() << "Umimplemented operation <none " << static_cast<int>(op.code) << ">"; break; } return false; } transaction_type script::type() const { return transaction_type::normal; } bool script::matches_template(operation_stack templ) const { return templ.size() == 0; } std::string script::pretty() const { std::ostringstream ss; for (auto it = operations_.begin(); it != operations_.end(); ++it) { if (it != operations_.begin()) ss << " "; const operation& op = *it; if (op.data.size() == 0) ss << opcode_to_string(op.code); else { ss << "[ " << pretty_hex(op.data) << " ]"; } } return ss.str(); } std::string opcode_to_string(opcode code) { switch (code) { case opcode::special: return "special"; case opcode::pushdata1: return "pushdata1"; case opcode::pushdata2: return "pushdata2"; case opcode::pushdata4: return "pushdata4"; case opcode::nop: return "nop"; case opcode::dup: return "dup"; case opcode::hash160: return "hash160"; case opcode::equalverify: return "equalverify"; case opcode::checksig: return "checksig"; default: { std::ostringstream ss; ss << "<none " << static_cast<int>(code) << ">"; return ss.str(); } } } opcode string_to_opcode(std::string code_repr) { if (code_repr == "special") return opcode::special; else if (code_repr == "pushdata1") return opcode::pushdata1; else if (code_repr == "pushdata2") return opcode::pushdata2; else if (code_repr == "pushdata4") return opcode::pushdata4; else if (code_repr == "nop") return opcode::nop; else if (code_repr == "dup") return opcode::dup; else if (code_repr == "hash160") return opcode::hash160; else if (code_repr == "equalverify") return opcode::equalverify; else if (code_repr == "checksig") return opcode::checksig; // ERROR: unknown... return opcode::bad_operation; } size_t number_of_bytes_from_opcode(opcode code, byte raw_byte) { if (code == opcode::special) return raw_byte; else if (code == opcode::pushdata1 || code == opcode::pushdata2 || code == opcode::pushdata4) return static_cast<size_t>(code); else return 0; } script parse_script(const data_chunk& raw_script) { script script_object; for (auto it = raw_script.begin(); it != raw_script.end(); ++it) { byte raw_byte = *it; operation op; op.code = static_cast<opcode>(raw_byte); // raw_byte is unsigned so it's always >= 0 if (raw_byte <= 75) op.code = opcode::special; size_t read_n_bytes = number_of_bytes_from_opcode(op.code, raw_byte); for (size_t byte_count = 0; byte_count < read_n_bytes; ++byte_count) { ++it; if (it == raw_script.cend()) { log_warning() << "Premature end of script."; return script(); } op.data.push_back(*it); } script_object.push_operation(op); } return script_object; } data_chunk save_script(const script& scr) { data_chunk raw_script; for (operation op: scr.operations()) { byte raw_byte = static_cast<byte>(op.code); if (op.code == opcode::special) raw_byte = op.data.size(); raw_script.push_back(raw_byte); extend_data(raw_script, op.data); } return raw_script; } script script_from_pretty(const std::string& pretty_script) { script script_object; std::stringstream splitter; splitter << pretty_script; std::string token; while (splitter >> token) { operation op; if (token == "[") { while ((splitter >> token) && token != "]") { std::istringstream to_int(token); int value; to_int >> std::hex >> value; op.data.push_back(value); } if (token != "]") { log_warning() << "Premature end of script."; return script(); } op.code = opcode::special; } else { op.code = string_to_opcode(token); } script_object.push_operation(op); } return script_object; } } // libbitcoin <commit_msg>pushdata1/2/4<commit_after>#include <bitcoin/script.hpp> #include <stack> #include <bitcoin/messages.hpp> #include <bitcoin/transaction.hpp> #include <bitcoin/util/elliptic_curve_key.hpp> #include <bitcoin/util/assert.hpp> #include <bitcoin/util/logger.hpp> #include <bitcoin/util/ripemd.hpp> #include <bitcoin/util/sha256.hpp> namespace libbitcoin { void script::join(const script& other) { operations_.insert(operations_.end(), other.operations_.begin(), other.operations_.end()); } void script::push_operation(operation oper) { operations_.push_back(oper); } const operation_stack& script::operations() const { return operations_; } bool script::run(script input_script, const message::transaction& parent_tx, uint32_t input_index) { stack_.clear(); input_script.stack_.clear(); if (!input_script.run(parent_tx, input_index)) return false; stack_ = input_script.stack_; if (!run(parent_tx, input_index)) return false; if (stack_.size() != 0) { // TODO: OP_CHECKSIG actually leaves stuff on stack log_error() << "Script left junk on top of the stack"; return false; } return true; } bool script::run(const message::transaction& parent_tx, uint32_t input_index) { for (const operation oper: operations_) { //log_debug() << "Run: " << opcode_to_string(oper.code); if (!run_operation(oper, parent_tx, input_index)) return false; if (oper.data.size() > 0) { BITCOIN_ASSERT(oper.code == opcode::special || oper.code == opcode::pushdata1 || oper.code == opcode::pushdata2 || oper.code == opcode::pushdata4); stack_.push_back(oper.data); } } return true; } data_chunk script::pop_stack() { data_chunk value = stack_.back(); stack_.pop_back(); return value; } bool script::op_dup() { if (stack_.size() < 1) return false; stack_.push_back(stack_.back()); return true; } bool script::op_hash160() { if (stack_.size() < 1) return false; data_chunk data = pop_stack(); short_hash hash = generate_ripemd_hash(data); data_chunk raw_hash(hash.begin(), hash.end()); stack_.push_back(raw_hash); return true; } bool script::op_equalverify() { if (stack_.size() < 2) return false; return pop_stack() == pop_stack(); } inline void nullify_input_sequences( message::transaction_input_list& inputs, uint32_t except_input) { for (size_t i = 0; i < inputs.size(); ++i) if (i != except_input) inputs[i].sequence = 0; } bool script::op_checksig(message::transaction parent_tx, uint32_t input_index) { BITCOIN_ASSERT(input_index < parent_tx.inputs.size()); if (stack_.size() < 2) return false; data_chunk pubkey = pop_stack(), signature = pop_stack(); script script_code; for (operation op: operations_) { if (op.data == signature || op.code == opcode::codeseparator) continue; script_code.push_operation(op); } elliptic_curve_key key; key.set_public_key(pubkey); uint32_t hash_type = 0; hash_type = signature.back(); signature.pop_back(); if ((hash_type & 0x1f) == sighash::none) { parent_tx.outputs.clear(); nullify_input_sequences(parent_tx.inputs, input_index); } else if ((hash_type & 0x1f) == sighash::single) { uint32_t output_index = input_index; if (output_index >= parent_tx.outputs.size()) { log_error() << "sighash::single the output_index is out of range"; return false; } parent_tx.outputs.resize(output_index + 1); for (message::transaction_output& output: parent_tx.outputs) { output.value = ~0; output.output_script = script(); } nullify_input_sequences(parent_tx.inputs, input_index); } if (hash_type & sighash::anyone_can_pay) { parent_tx.inputs[0] = parent_tx.inputs[input_index]; parent_tx.inputs.resize(1); } if (input_index >= parent_tx.inputs.size()) { log_fatal() << "script::op_checksig() : input_index " << input_index << " is out of range."; return false; } message::transaction tx_tmp = parent_tx; // Blank all other inputs' signatures for (message::transaction_input& input: tx_tmp.inputs) input.input_script = script(); tx_tmp.inputs[input_index].input_script = script_code; hash_digest tx_hash = hash_transaction(tx_tmp, hash_type); return key.verify(tx_hash, signature); } bool script::run_operation(operation op, const message::transaction& parent_tx, uint32_t input_index) { switch (op.code) { case opcode::special: case opcode::pushdata1: case opcode::pushdata2: case opcode::pushdata4: return true; case opcode::nop: return true; case opcode::dup: return op_dup(); case opcode::hash160: return op_hash160(); case opcode::equalverify: return op_equalverify(); case opcode::checksig: return op_checksig(parent_tx, input_index); default: log_fatal() << "Unimplemented operation <none " << static_cast<int>(op.code) << ">"; break; } return false; } transaction_type script::type() const { return transaction_type::normal; } bool script::matches_template(operation_stack templ) const { return templ.size() == 0; } std::string script::pretty() const { std::ostringstream ss; for (auto it = operations_.begin(); it != operations_.end(); ++it) { if (it != operations_.begin()) ss << " "; const operation& op = *it; if (op.data.size() == 0) ss << opcode_to_string(op.code); else { ss << "[ " << pretty_hex(op.data) << " ]"; } } return ss.str(); } std::string opcode_to_string(opcode code) { switch (code) { case opcode::special: return "special"; case opcode::pushdata1: return "pushdata1"; case opcode::pushdata2: return "pushdata2"; case opcode::pushdata4: return "pushdata4"; case opcode::nop: return "nop"; case opcode::dup: return "dup"; case opcode::hash160: return "hash160"; case opcode::equalverify: return "equalverify"; case opcode::checksig: return "checksig"; default: { std::ostringstream ss; ss << "<none " << static_cast<int>(code) << ">"; return ss.str(); } } } opcode string_to_opcode(std::string code_repr) { if (code_repr == "special") return opcode::special; else if (code_repr == "pushdata1") return opcode::pushdata1; else if (code_repr == "pushdata2") return opcode::pushdata2; else if (code_repr == "pushdata4") return opcode::pushdata4; else if (code_repr == "nop") return opcode::nop; else if (code_repr == "dup") return opcode::dup; else if (code_repr == "hash160") return opcode::hash160; else if (code_repr == "equalverify") return opcode::equalverify; else if (code_repr == "checksig") return opcode::checksig; // ERROR: unknown... return opcode::bad_operation; } // Read next n bytes while advancing iterator // Used for seeing length of data to push to stack with pushdata2/4 template <typename Iterator> inline data_chunk read_back_from_iterator(Iterator& it, size_t total) { data_chunk number_bytes; for (size_t i = 0; i < total; ++i) { ++it; number_bytes.push_back(*it); } return number_bytes; } template <typename Iterator> size_t number_of_bytes_from_opcode(opcode code, byte raw_byte, Iterator& it) { switch (code) { case opcode::special: return raw_byte; case opcode::pushdata1: ++it; return static_cast<uint8_t>(*it); case opcode::pushdata2: return cast_chunk<uint16_t>(read_back_from_iterator(it, 2)); case opcode::pushdata4: return cast_chunk<uint32_t>(read_back_from_iterator(it, 4)); default: return 0; } } script parse_script(const data_chunk& raw_script) { script script_object; for (auto it = raw_script.begin(); it != raw_script.end(); ++it) { byte raw_byte = *it; operation op; op.code = static_cast<opcode>(raw_byte); // raw_byte is unsigned so it's always >= 0 if (raw_byte <= 75) op.code = opcode::special; size_t read_n_bytes = number_of_bytes_from_opcode(op.code, raw_byte, it); for (size_t byte_count = 0; byte_count < read_n_bytes; ++byte_count) { ++it; if (it == raw_script.cend()) { log_warning() << "Premature end of script."; return script(); } op.data.push_back(*it); } script_object.push_operation(op); } return script_object; } inline data_chunk operation_metadata(const opcode code, size_t data_size) { switch (code) { case opcode::pushdata1: return uncast_type<uint8_t>(data_size); case opcode::pushdata2: return uncast_type<uint16_t>(data_size); case opcode::pushdata4: return uncast_type<uint32_t>(data_size); default: return data_chunk(); } } data_chunk save_script(const script& scr) { data_chunk raw_script; for (operation op: scr.operations()) { byte raw_byte = static_cast<byte>(op.code); if (op.code == opcode::special) raw_byte = op.data.size(); raw_script.push_back(raw_byte); extend_data(raw_script, operation_metadata(op.code, op.data.size())); extend_data(raw_script, op.data); } return raw_script; } script script_from_pretty(const std::string& pretty_script) { script script_object; std::stringstream splitter; splitter << pretty_script; std::string token; while (splitter >> token) { operation op; if (token == "[") { while ((splitter >> token) && token != "]") { std::istringstream to_int(token); int value; to_int >> std::hex >> value; op.data.push_back(value); } if (token != "]") { log_warning() << "Premature end of script."; return script(); } op.code = opcode::special; } else { op.code = string_to_opcode(token); } script_object.push_operation(op); } return script_object; } } // libbitcoin <|endoftext|>
<commit_before>#include <util/PlatformUtils.hpp> #include <XalanTransformer/XalanTransformer.hpp> #include <cstdio> #if defined(XALAN_OLD_STREAM_HEADERS) #include <iostream.h> #else #include <iostream> #endif // This is a simple class that illustrates how XalanTransformer's "callback" API // is used. This example just abstracts writing data to a FILE*, but other // actions are possible. class CallbackHandler { public: CallbackHandler(FILE* theFile) : m_file(theFile) { assert(m_file != 0); } unsigned long write( const char* theData, unsigned long theLength) { return fwrite(theData, sizeof(char), theLength, m_file); } void flush() { fflush(m_file); } private: FILE* const m_file; }; // These functions need to have C linkage, so surround them with an extern C block... extern "C" { // This is the write callback function, which casts the handle // to the appropriate type, then calls the write() member function // on the CallbackHandler class. unsigned long writeCallback( const char* theData, unsigned long theLength, void* theHandle) { #if defined(XALAN_OLD_STYLE_CASTS) return ((CallbackHandler*)theHandle)->write(theData, theLength); #else return reinterpret_cast<CallbackHandler*>(theHandle)->write(theData, theLength); #endif } // This is the flush callback function, which casts the handle // to the appropriate type, then calls the flush() member function // on the CallbackHandler class. void flushCallback(void* theHandle) { #if defined(XALAN_OLD_STYLE_CASTS) ((CallbackHandler*)theHandle)->flush(); #else reinterpret_cast<CallbackHandler*>(theHandle)->flush(); #endif } }; int doTransform( const char* theXMLFile, const char* theXSLFile, FILE* theOutputFile) { #if !defined(XALAN_NO_NAMESPACES) using std::cerr; using std::endl; #endif // Create a XalanTransformer... XalanTransformer theXalanTransformer; // Create an instance of the class we wrote to handle // the callbacks... CallbackHandler theHandler(theOutputFile); // Do the transform... const int theResult = theXalanTransformer.transform( theXMLFile, theXSLFile, &theHandler, writeCallback, flushCallback); if(theResult != 0) { cerr << "XalanError: " << theXalanTransformer.getLastError() << endl; } return theResult; } int main( int argc, const char* argv[]) { #if !defined(XALAN_NO_NAMESPACES) using std::cerr; using std::endl; #endif if (argc < 3 || argc > 4) { cerr << "Usage: XalanTransformerCallback XMLFileName XSLFileName [OutFileName]" << endl; return -1; } // Call the static initializer for Xerces. XMLPlatformUtils::Initialize(); // Initialize Xalan. XalanTransformer::initialize(); int theResult = 0; if (argc == 3) { // No output file, so use stdout... theResult = doTransform(argv[1], argv[2], stdout); } else { // Ooutput file specified, so try to open it... FILE* const theOutputFile = fopen(argv[3], "w"); if (theOutputFile == 0) { cerr << "Error: " << "Unable to open output file " << argv[3] << endl; } else { theResult = doTransform(argv[1], argv[2], theOutputFile); fclose(theOutputFile); } } // Terminate Xalan. XalanTransformer::terminate(); // Call the static terminator for Xerces. XMLPlatformUtils::Terminate(); return theResult; } <commit_msg>32/64-bit fixes.<commit_after>#include <util/PlatformUtils.hpp> #include <XalanTransformer/XalanTransformer.hpp> #include <cstdio> #if defined(XALAN_OLD_STREAM_HEADERS) #include <iostream.h> #else #include <iostream> #endif // This is a simple class that illustrates how XalanTransformer's "callback" API // is used. This example just abstracts writing data to a FILE*, but other // actions are possible. class CallbackHandler { public: CallbackHandler(FILE* theFile) : m_file(theFile) { assert(m_file != 0); } CallbackSizeType write( const char* theData, CallbackSizeType theLength) { return fwrite(theData, sizeof(char), theLength, m_file); } void flush() { fflush(m_file); } private: FILE* const m_file; }; // These functions need to have C linkage, so surround them with an extern C block... extern "C" { // This is the write callback function, which casts the handle // to the appropriate type, then calls the write() member function // on the CallbackHandler class. CallbackSizeType writeCallback( const char* theData, CallbackSizeType theLength, void* theHandle) { #if defined(XALAN_OLD_STYLE_CASTS) return ((CallbackHandler*)theHandle)->write(theData, theLength); #else return reinterpret_cast<CallbackHandler*>(theHandle)->write(theData, theLength); #endif } // This is the flush callback function, which casts the handle // to the appropriate type, then calls the flush() member function // on the CallbackHandler class. void flushCallback(void* theHandle) { #if defined(XALAN_OLD_STYLE_CASTS) ((CallbackHandler*)theHandle)->flush(); #else reinterpret_cast<CallbackHandler*>(theHandle)->flush(); #endif } }; int doTransform( const char* theXMLFile, const char* theXSLFile, FILE* theOutputFile) { #if !defined(XALAN_NO_NAMESPACES) using std::cerr; using std::endl; #endif // Create a XalanTransformer... XalanTransformer theXalanTransformer; // Create an instance of the class we wrote to handle // the callbacks... CallbackHandler theHandler(theOutputFile); // Do the transform... const int theResult = theXalanTransformer.transform( theXMLFile, theXSLFile, &theHandler, writeCallback, flushCallback); if(theResult != 0) { cerr << "XalanError: " << theXalanTransformer.getLastError() << endl; } return theResult; } int main( int argc, const char* argv[]) { #if !defined(XALAN_NO_NAMESPACES) using std::cerr; using std::endl; #endif if (argc < 3 || argc > 4) { cerr << "Usage: XalanTransformerCallback XMLFileName XSLFileName [OutFileName]" << endl; return -1; } // Call the static initializer for Xerces. XMLPlatformUtils::Initialize(); // Initialize Xalan. XalanTransformer::initialize(); int theResult = 0; if (argc == 3) { // No output file, so use stdout... theResult = doTransform(argv[1], argv[2], stdout); } else { // Ooutput file specified, so try to open it... FILE* const theOutputFile = fopen(argv[3], "w"); if (theOutputFile == 0) { cerr << "Error: " << "Unable to open output file " << argv[3] << endl; } else { theResult = doTransform(argv[1], argv[2], theOutputFile); fclose(theOutputFile); } } // Terminate Xalan. XalanTransformer::terminate(); // Call the static terminator for Xerces. XMLPlatformUtils::Terminate(); return theResult; } <|endoftext|>
<commit_before>/** * \file null_block_allocator.hpp * * \brief todo: fill in documentation * * \author Matthew Rodusek ([email protected]) */ #ifndef BIT_MEMORY_BLOCK_ALLOCATORS_NULL_BLOCK_ALLOCATOR_HPP #define BIT_MEMORY_BLOCK_ALLOCATORS_NULL_BLOCK_ALLOCATOR_HPP #include "../memory.hpp" #include "../memory_block.hpp" #include "cached_block_allocator.hpp" #include <type_traits> // std::integral_constant, std::true_false #include <cstddef> // std::max_align_t namespace bit { namespace memory { ////////////////////////////////////////////////////////////////////////// /// \brief A block allocator that only distributes null blocks /// /// \satisfies BlockAllocator ////////////////////////////////////////////////////////////////////////// class null_block_allocator { //---------------------------------------------------------------------- // Public Member Types //---------------------------------------------------------------------- public: using is_always_equal = std::true_type; using is_stateless = std::true_type; using block_alignment = std::integral_constant<std::size_t,1>; //----------------------------------------------------------------------- // Constructor / Assignment //----------------------------------------------------------------------- public: /// \brief Default-constructs a null_block_allocator null_block_allocator() = default; /// \brief Move-constructs a null_block_allocator from another allocator /// /// \param other the other null_block_allocator to move null_block_allocator( null_block_allocator&& other ) noexcept = default; // Deleted copy constructor null_block_allocator( const null_block_allocator& other ) = delete; //----------------------------------------------------------------------- // Deleted move assignment null_block_allocator& operator=( null_block_allocator&& other ) = delete; // Deleted copy assignment null_block_allocator& operator=( const null_block_allocator& other ) = delete; //---------------------------------------------------------------------- // Block Allocations //---------------------------------------------------------------------- public: /// \brief Allocates a null memory_block /// /// \return a null memory_block owner<memory_block> allocate_block() noexcept; /// \brief Deallocates a memory_block /// /// \param block the block to deallocate void deallocate_block( owner<memory_block> block ) noexcept; }; //------------------------------------------------------------------------- // Comparisons //------------------------------------------------------------------------- bool operator==( const null_block_allocator& lhs, const null_block_allocator& rhs ) noexcept; bool operator!=( const null_block_allocator& lhs, const null_block_allocator& rhs ) noexcept; //------------------------------------------------------------------------- // Utilities //------------------------------------------------------------------------- using cached_null_block_allocator = cached_block_allocator<null_block_allocator>; } // namespace memory } // namespace bit #include "detail/null_block_allocator.inl" #endif /* BIT_MEMORY_BLOCK_ALLOCATORS_NULL_BLOCK_ALLOCATOR_HPP */ <commit_msg>Updated 'null_block_allocator' to be stateless<commit_after>/** * \file null_block_allocator.hpp * * \brief todo: fill in documentation * * \author Matthew Rodusek ([email protected]) */ #ifndef BIT_MEMORY_BLOCK_ALLOCATORS_NULL_BLOCK_ALLOCATOR_HPP #define BIT_MEMORY_BLOCK_ALLOCATORS_NULL_BLOCK_ALLOCATOR_HPP #include "../memory.hpp" #include "../memory_block.hpp" #include "cached_block_allocator.hpp" #include <type_traits> // std::integral_constant, std::true_false #include <cstddef> // std::max_align_t namespace bit { namespace memory { ////////////////////////////////////////////////////////////////////////// /// \brief A block allocator that only distributes null blocks /// /// \satisfies BlockAllocator /// \satisfies Stateless ////////////////////////////////////////////////////////////////////////// class null_block_allocator { //---------------------------------------------------------------------- // Public Member Types //---------------------------------------------------------------------- public: using is_stateless = std::true_type; using block_alignment = std::integral_constant<std::size_t,1>; //----------------------------------------------------------------------- // Constructor / Assignment //----------------------------------------------------------------------- public: /// \brief Default-constructs a null_block_allocator null_block_allocator() = default; /// \brief Move-constructs a null_block_allocator from another allocator /// /// \param other the other null_block_allocator to move null_block_allocator( null_block_allocator&& other ) noexcept = default; /// \brief Copy-constructs a null_block_allocator from another allocator /// /// \param other the other null_block_allocator to copy null_block_allocator( const null_block_allocator& other ) noexcept = default; //----------------------------------------------------------------------- /// \brief Move-assigns a null_block_allocator from another allocator /// /// \param other the other null_block_allocator to move /// \return reference to \c (*this) null_block_allocator& operator=( null_block_allocator&& other ) noexcept = default; /// \brief Copy-assigns a null_block_allocator from another allocator /// /// \param other the other null_block_allocator to copy\ /// \return reference to \c (*this) null_block_allocator& operator=( const null_block_allocator& other ) noexcept = default; //---------------------------------------------------------------------- // Block Allocations //---------------------------------------------------------------------- public: /// \brief Allocates a null memory_block /// /// \return a null memory_block owner<memory_block> allocate_block() noexcept; /// \brief Deallocates a memory_block /// /// \param block the block to deallocate void deallocate_block( owner<memory_block> block ) noexcept; }; //------------------------------------------------------------------------- // Comparisons //------------------------------------------------------------------------- bool operator==( const null_block_allocator& lhs, const null_block_allocator& rhs ) noexcept; bool operator!=( const null_block_allocator& lhs, const null_block_allocator& rhs ) noexcept; //------------------------------------------------------------------------- // Utilities //------------------------------------------------------------------------- using cached_null_block_allocator = cached_block_allocator<null_block_allocator>; } // namespace memory } // namespace bit #include "detail/null_block_allocator.inl" #endif /* BIT_MEMORY_BLOCK_ALLOCATORS_NULL_BLOCK_ALLOCATOR_HPP */ <|endoftext|>
<commit_before>#ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #ifndef __STDC_CONSTANT_MACROS #define __STDC_CONSTANT_MACROS #endif #include <fstream> #include "clang/Frontend/FrontendActions.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Tooling.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Lex/Lexer.h" #include "clang/Basic/TargetOptions.h" #include "clang/Basic/TargetInfo.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/ASTConsumers.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "search.hpp" using namespace clang; using namespace clang::tooling; using namespace clang::ast_matchers; namespace { std::string get_line_from_offset(StringRef buffer, std::size_t offset) { assert(buffer.size() > offset); auto line_start = buffer.find_last_of("\r\n", offset) + 1; auto line_end = buffer.find_first_of("\r\n", offset); return std::string(buffer.begin() + line_start, buffer.begin() + line_end); } /// Adapted from clang CIndex.cpp /// /// Clang internally represents ranges where the end location points to the /// start of the token at the end. However, for external clients it is more /// useful to have a CXSourceRange be a proper half-open interval. This /// routine does the appropriate translation. SourceRange translateSourceRange(const ASTContext* context, const SourceManager* sm, const SourceRange& range) { // We want the last character in this location, so we will adjust the // location accordingly. auto R = CharSourceRange::getTokenRange(range); auto& LangOpts = context->getLangOpts(); SourceLocation EndLoc = R.getEnd(); if (EndLoc.isValid() && EndLoc.isMacroID() && !sm->isMacroArgExpansion(EndLoc)) EndLoc = sm->getExpansionRange(EndLoc).second; if (R.isTokenRange() && EndLoc.isValid()) { unsigned Length = Lexer::MeasureTokenLength(sm->getSpellingLoc(EndLoc), *sm, LangOpts); EndLoc = EndLoc.getLocWithOffset(Length - 1); } SourceRange Result = {R.getBegin(), EndLoc}; return Result; } template <typename U> void print_node(const ASTContext* context, const SourceManager* sm, const U* node) { auto range = node->getSourceRange(); range = translateSourceRange(context, sm, range); if (!range.isValid()) return; auto start_loc = sm->getExpansionLoc(range.getBegin()); auto end_loc = sm->getExpansionLoc(range.getEnd()); auto start_row = sm->getExpansionLineNumber(start_loc); auto start_column = sm->getExpansionColumnNumber(start_loc); auto end_row = sm->getExpansionLineNumber(end_loc); auto end_column = sm->getExpansionColumnNumber(end_loc); auto file_id = sm->getFileID(start_loc); auto buffer = sm->getBufferData(file_id); auto offset = sm->getDecomposedLoc(start_loc).second; std::cout << start_row << ":" << start_column << ":" << get_line_from_offset(buffer, offset) << std::endl; } AST_MATCHER_P(NamedDecl, matchesUnqualifiedName, std::string, RegExp) { assert(!RegExp.empty()); std::string FullNameString = Node.getNameAsString(); llvm::Regex RE(RegExp); return RE.match(FullNameString); } AST_MATCHER_P(QualType, matchesType, std::string, RegExp) { assert(!RegExp.empty()); llvm::Regex RE(RegExp); return RE.match(Node.getAsString()); } AST_MATCHER_P(ParmVarDecl, matchesParameter, ExplicitParameter, param) { auto matcher = parmVarDecl(allOf(matchesUnqualifiedName(param.name), hasType(matchesType(param.type)), unless(isImplicit()))); return matcher.matches(Node, Finder, Builder); } AST_MATCHER_P(FunctionDecl, matchesParameters, std::vector<FunctionParameter>, parameters) { bool ellipses_active = false; auto iter = Node.param_begin(); for (const auto& p : parameters) { if (p.which() == 1) { ellipses_active = true; continue; } if (iter == Node.param_end()) { return false; } auto matcher = matchesParameter(boost::get<ExplicitParameter>(p)); if (!matcher.matches(**iter, Finder, Builder)) { if (!ellipses_active) { return false; } else { ++iter; } } else { ++iter; ellipses_active = false; } } if (iter != Node.param_end() && !ellipses_active) { return false; } return true; } AST_MATCHER_P(NamespaceDecl, matchesNamespace, Namespace, ns) { llvm::Regex RE(ns.name); return RE.match(Node.getNameAsString()); } AST_MATCHER_P(RecordDecl, matchesClass, Class, cls) { llvm::Regex RE(cls.name); return RE.match(Node.getNameAsString()); } AST_MATCHER_P(NamedDecl, matchesQualifiers, std::vector<Qualifier>, qualifiers) { auto context = Node.getDeclContext(); std::vector<const DeclContext*> contexts; while (context && isa<NamedDecl>(context)) { contexts.push_back(context); context = context->getParent(); } if (qualifiers.size() > contexts.size()) { return false; } for (std::size_t i = 0; i < qualifiers.size(); ++i) { const auto& qual = qualifiers[qualifiers.size() - 1 - i]; if (qual.which() == 0) { if (const auto* ND = dyn_cast<NamespaceDecl>(contexts[i])) { auto ns = boost::get<Namespace>(qual); auto matcher = matchesNamespace(ns); if (!matcher.matches(*ND, Finder, Builder)) { return false; } } else { return false; } } else if (qual.which() == 1) { if (const auto* RD = dyn_cast<RecordDecl>(contexts[i])) { auto cls = boost::get<Class>(qual); auto matcher = matchesClass(cls); if (!matcher.matches(*RD, Finder, Builder)) { return false; } } else { return false; } } } return true; } } template <typename T> class Printer; template <> class Printer<Variable> : public MatchFinder::MatchCallback { public: virtual void run(const MatchFinder::MatchResult& Result) { auto d = Result.Nodes.getNodeAs<VarDecl>("varDecl"); print_node(Result.Context, Result.SourceManager, d); } }; template <> class Printer<Function> : public MatchFinder::MatchCallback { public: virtual void run(const MatchFinder::MatchResult& Result) { if (auto d = Result.Nodes.getNodeAs<FunctionDecl>("funcDecl")) { print_node(Result.Context, Result.SourceManager, d); } if (auto e = Result.Nodes.getNodeAs<CallExpr>("funcCall")) { print_node(Result.Context, Result.SourceManager, e); } } }; void addMatchersForTerm(const Variable& v, MatchFinder& finder, Printer<Variable>* printer) { auto varDeclMatcher = varDecl(allOf(matchesUnqualifiedName(v.name), hasType(matchesType(v.type)), matchesQualifiers(v.qualifiers), unless(isImplicit()))) .bind("varDecl"); finder.addMatcher(varDeclMatcher, printer); } void addMatchersForTerm(const Function& f, MatchFinder& finder, Printer<Function>* printer) { auto declMatcher = functionDecl(allOf(matchesUnqualifiedName(f.name), returns(matchesType(f.return_type)), unless(isImplicit()), matchesQualifiers(f.qualifiers), matchesParameters(f.parameters))); auto funcDeclMatcher = declMatcher.bind("funcDecl"); auto funcCallMatcher = callExpr(hasDeclaration(declMatcher)).bind("funcCall"); finder.addMatcher(funcDeclMatcher, printer); finder.addMatcher(funcCallMatcher, printer); } template <typename T> void findTermIn(std::string path, const T& term) { std::ifstream file{path}; std::stringstream buffer; buffer << file.rdbuf(); Printer<T> Printer; MatchFinder Finder; addMatchersForTerm(term, Finder, &Printer); auto action_factory = newFrontendActionFactory(&Finder); auto action = action_factory->create(); runToolOnCodeWithArgs(action, buffer.str(), {"-w", "-std=c++14", "-I/usr/lib/clang/3.7.1/include"}); } void search_file(const char* file, Term& term, const po::variables_map& config) { auto p = boost::filesystem::path(file); auto extension = boost::filesystem::extension(p); if (!config.count("search-all-extensions") && extension != ".cpp" && extension != ".c" && extension != ".h" && extension != ".hpp") { return; } boost::apply_visitor(TermSearchVisitor(file, config), term); } void TermSearchVisitor::operator()(Function& f) const { findTermIn(this->m_root_filename, f); } void TermSearchVisitor::operator()(Variable& v) const { findTermIn(this->m_root_filename, v); } <commit_msg>Exclude declarations from include files<commit_after>#ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #ifndef __STDC_CONSTANT_MACROS #define __STDC_CONSTANT_MACROS #endif #include <fstream> #include "clang/Frontend/FrontendActions.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Tooling.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Lex/Lexer.h" #include "clang/Basic/TargetOptions.h" #include "clang/Basic/TargetInfo.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/ASTConsumers.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "search.hpp" using namespace clang; using namespace clang::tooling; using namespace clang::ast_matchers; namespace { std::string get_line_from_offset(StringRef buffer, std::size_t offset) { assert(buffer.size() > offset); auto line_start = buffer.find_last_of("\r\n", offset) + 1; auto line_end = buffer.find_first_of("\r\n", offset); return std::string(buffer.begin() + line_start, buffer.begin() + line_end); } /// Adapted from clang CIndex.cpp /// /// Clang internally represents ranges where the end location points to the /// start of the token at the end. However, for external clients it is more /// useful to have a CXSourceRange be a proper half-open interval. This /// routine does the appropriate translation. SourceRange translateSourceRange(const ASTContext* context, const SourceManager* sm, const SourceRange& range) { // We want the last character in this location, so we will adjust the // location accordingly. auto R = CharSourceRange::getTokenRange(range); auto& LangOpts = context->getLangOpts(); SourceLocation EndLoc = R.getEnd(); if (EndLoc.isValid() && EndLoc.isMacroID() && !sm->isMacroArgExpansion(EndLoc)) EndLoc = sm->getExpansionRange(EndLoc).second; if (R.isTokenRange() && EndLoc.isValid()) { unsigned Length = Lexer::MeasureTokenLength(sm->getSpellingLoc(EndLoc), *sm, LangOpts); EndLoc = EndLoc.getLocWithOffset(Length - 1); } SourceRange Result = {R.getBegin(), EndLoc}; return Result; } template <typename U> void print_node(const ASTContext* context, const SourceManager* sm, const U* node) { auto range = node->getSourceRange(); range = translateSourceRange(context, sm, range); if (!range.isValid()) return; auto start_loc = sm->getExpansionLoc(range.getBegin()); auto end_loc = sm->getExpansionLoc(range.getEnd()); auto start_row = sm->getExpansionLineNumber(start_loc); auto start_column = sm->getExpansionColumnNumber(start_loc); auto end_row = sm->getExpansionLineNumber(end_loc); auto end_column = sm->getExpansionColumnNumber(end_loc); auto file_id = sm->getFileID(start_loc); auto buffer = sm->getBufferData(file_id); auto offset = sm->getDecomposedLoc(start_loc).second; std::cout << start_row << ":" << start_column << ":" << get_line_from_offset(buffer, offset) << std::endl; } AST_MATCHER_P(NamedDecl, matchesUnqualifiedName, std::string, RegExp) { assert(!RegExp.empty()); std::string FullNameString = Node.getNameAsString(); llvm::Regex RE(RegExp); return RE.match(FullNameString); } AST_MATCHER_P(QualType, matchesType, std::string, RegExp) { assert(!RegExp.empty()); llvm::Regex RE(RegExp); return RE.match(Node.getAsString()); } AST_MATCHER_P(ParmVarDecl, matchesParameter, ExplicitParameter, param) { auto matcher = parmVarDecl(allOf(matchesUnqualifiedName(param.name), hasType(matchesType(param.type)), unless(isImplicit()))); return matcher.matches(Node, Finder, Builder); } AST_MATCHER_P(FunctionDecl, matchesParameters, std::vector<FunctionParameter>, parameters) { bool ellipses_active = false; auto iter = Node.param_begin(); for (const auto& p : parameters) { if (p.which() == 1) { ellipses_active = true; continue; } if (iter == Node.param_end()) { return false; } auto matcher = matchesParameter(boost::get<ExplicitParameter>(p)); if (!matcher.matches(**iter, Finder, Builder)) { if (!ellipses_active) { return false; } else { ++iter; } } else { ++iter; ellipses_active = false; } } if (iter != Node.param_end() && !ellipses_active) { return false; } return true; } AST_MATCHER_P(NamespaceDecl, matchesNamespace, Namespace, ns) { llvm::Regex RE(ns.name); return RE.match(Node.getNameAsString()); } AST_MATCHER_P(RecordDecl, matchesClass, Class, cls) { llvm::Regex RE(cls.name); return RE.match(Node.getNameAsString()); } AST_MATCHER_P(NamedDecl, matchesQualifiers, std::vector<Qualifier>, qualifiers) { auto context = Node.getDeclContext(); std::vector<const DeclContext*> contexts; while (context && isa<NamedDecl>(context)) { contexts.push_back(context); context = context->getParent(); } if (qualifiers.size() > contexts.size()) { return false; } for (std::size_t i = 0; i < qualifiers.size(); ++i) { const auto& qual = qualifiers[qualifiers.size() - 1 - i]; if (qual.which() == 0) { if (const auto* ND = dyn_cast<NamespaceDecl>(contexts[i])) { auto ns = boost::get<Namespace>(qual); auto matcher = matchesNamespace(ns); if (!matcher.matches(*ND, Finder, Builder)) { return false; } } else { return false; } } else if (qual.which() == 1) { if (const auto* RD = dyn_cast<RecordDecl>(contexts[i])) { auto cls = boost::get<Class>(qual); auto matcher = matchesClass(cls); if (!matcher.matches(*RD, Finder, Builder)) { return false; } } else { return false; } } } return true; } } template <typename T> class Printer; template <> class Printer<Variable> : public MatchFinder::MatchCallback { public: virtual void run(const MatchFinder::MatchResult& Result) { auto d = Result.Nodes.getNodeAs<VarDecl>("varDecl"); print_node(Result.Context, Result.SourceManager, d); } }; template <> class Printer<Function> : public MatchFinder::MatchCallback { public: virtual void run(const MatchFinder::MatchResult& Result) { if (auto d = Result.Nodes.getNodeAs<FunctionDecl>("funcDecl")) { print_node(Result.Context, Result.SourceManager, d); } if (auto e = Result.Nodes.getNodeAs<CallExpr>("funcCall")) { print_node(Result.Context, Result.SourceManager, e); } } }; void addMatchersForTerm(const Variable& v, MatchFinder& finder, Printer<Variable>* printer) { auto varDeclMatcher = varDecl(allOf(isExpansionInMainFile(), matchesUnqualifiedName(v.name), hasType(matchesType(v.type)), matchesQualifiers(v.qualifiers), unless(isImplicit()))) .bind("varDecl"); finder.addMatcher(varDeclMatcher, printer); } void addMatchersForTerm(const Function& f, MatchFinder& finder, Printer<Function>* printer) { auto declMatcher = functionDecl( allOf(isExpansionInMainFile(), matchesUnqualifiedName(f.name), returns(matchesType(f.return_type)), unless(isImplicit()), matchesQualifiers(f.qualifiers), matchesParameters(f.parameters))); auto funcDeclMatcher = declMatcher.bind("funcDecl"); auto funcCallMatcher = callExpr(hasDeclaration(declMatcher)).bind("funcCall"); finder.addMatcher(funcDeclMatcher, printer); finder.addMatcher(funcCallMatcher, printer); } template <typename T> void findTermIn(std::string path, const T& term) { std::ifstream file{path}; std::stringstream buffer; buffer << file.rdbuf(); Printer<T> Printer; MatchFinder Finder; addMatchersForTerm(term, Finder, &Printer); auto action_factory = newFrontendActionFactory(&Finder); auto action = action_factory->create(); runToolOnCodeWithArgs(action, buffer.str(), {"-w", "-std=c++14", "-I/usr/lib/clang/3.7.1/include"}); } void search_file(const char* file, Term& term, const po::variables_map& config) { auto p = boost::filesystem::path(file); auto extension = boost::filesystem::extension(p); if (!config.count("search-all-extensions") && extension != ".cpp" && extension != ".c" && extension != ".h" && extension != ".hpp") { return; } boost::apply_visitor(TermSearchVisitor(file, config), term); } void TermSearchVisitor::operator()(Function& f) const { findTermIn(this->m_root_filename, f); } void TermSearchVisitor::operator()(Variable& v) const { findTermIn(this->m_root_filename, v); } <|endoftext|>
<commit_before>/************************************************************************** ** ** Copyright (C) 2012, 2013 BlackBerry Limited. All rights reserved ** ** Contact: BlackBerry ([email protected]) ** Contact: KDAB ([email protected]) ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qnxutils.h" #include "qnxabstractqtversion.h" #include <utils/hostosinfo.h> #include <utils/synchronousprocess.h> #include <QDir> #include <QDesktopServices> #include <QDomDocument> #include <QProcess> #include <QTemporaryFile> #include <QApplication> using namespace Qnx; using namespace Qnx::Internal; namespace { const char *EVAL_ENV_VARS[] = { "QNX_TARGET", "QNX_HOST", "QNX_CONFIGURATION", "MAKEFLAGS", "LD_LIBRARY_PATH", "PATH", "QDE", "CPUVARDIR", "PYTHONPATH" }; } QString QnxUtils::addQuotes(const QString &string) { return QLatin1Char('"') + string + QLatin1Char('"'); } Qnx::QnxArchitecture QnxUtils::cpudirToArch(const QString &cpuDir) { if (cpuDir == QLatin1String("x86")) return Qnx::X86; else if (cpuDir == QLatin1String("armle-v7")) return Qnx::ArmLeV7; else return Qnx::UnknownArch; } QStringList QnxUtils::searchPaths(QnxAbstractQtVersion *qtVersion) { const QDir pluginDir(qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_PLUGINS"))); const QStringList pluginSubDirs = pluginDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); QStringList searchPaths; Q_FOREACH (const QString &dir, pluginSubDirs) { searchPaths << qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_PLUGINS")) + QLatin1Char('/') + dir; } searchPaths << qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_LIBS")); searchPaths << qtVersion->qnxTarget() + QLatin1Char('/') + qtVersion->archString().toLower() + QLatin1String("/lib"); searchPaths << qtVersion->qnxTarget() + QLatin1Char('/') + qtVersion->archString().toLower() + QLatin1String("/usr/lib"); return searchPaths; } QList<Utils::EnvironmentItem> QnxUtils::qnxEnvironmentFromNdkFile(const QString &fileName) { QList <Utils::EnvironmentItem> items; if (!QFileInfo(fileName).exists()) return items; const bool isWindows = Utils::HostOsInfo::isWindowsHost(); // locking creating bbndk-env file wrapper script QTemporaryFile tmpFile( QDir::tempPath() + QDir::separator() + QLatin1String("bbndk-env-eval-XXXXXX") + QLatin1String(isWindows ? ".bat" : ".sh")); if (!tmpFile.open()) return items; tmpFile.setTextModeEnabled(true); // writing content to wrapper script QTextStream fileContent(&tmpFile); if (isWindows) fileContent << QLatin1String("@echo off\n") << QLatin1String("call ") << fileName << QLatin1Char('\n'); else fileContent << QLatin1String("#!/bin/bash\n") << QLatin1String(". ") << fileName << QLatin1Char('\n'); QString linePattern = QString::fromLatin1(isWindows ? "echo %1=%%1%" : "echo %1=$%1"); for (int i = 0, len = sizeof(EVAL_ENV_VARS) / sizeof(const char *); i < len; ++i) fileContent << linePattern.arg(QLatin1String(EVAL_ENV_VARS[i])) << QLatin1Char('\n'); tmpFile.close(); // running wrapper script QProcess process; if (isWindows) process.start(QLatin1String("cmd.exe"), QStringList() << QLatin1String("/C") << tmpFile.fileName()); else process.start(QLatin1String("/bin/bash"), QStringList() << tmpFile.fileName()); // waiting for finish QApplication::setOverrideCursor(Qt::BusyCursor); bool waitResult = process.waitForFinished(10000); QApplication::restoreOverrideCursor(); if (!waitResult) { Utils::SynchronousProcess::stopProcess(process); return items; } if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) return items; // parsing process output QTextStream str(&process); while (!str.atEnd()) { QString line = str.readLine(); int equalIndex = line.indexOf(QLatin1Char('=')); if (equalIndex < 0) continue; QString var = line.left(equalIndex); QString value = line.mid(equalIndex + 1); items.append(Utils::EnvironmentItem(var, value)); } return items; } bool QnxUtils::isValidNdkPath(const QString &ndkPath) { return (QFileInfo(envFilePath(ndkPath)).exists()); } QString QnxUtils::envFilePath(const QString &ndkPath, const QString &targetVersion) { QString envFile; if (Utils::HostOsInfo::isWindowsHost()) envFile = ndkPath + QLatin1String("/bbndk-env.bat"); else if (Utils::HostOsInfo::isAnyUnixHost()) envFile = ndkPath + QLatin1String("/bbndk-env.sh"); if (!QFileInfo(envFile).exists()) { QString version = targetVersion.isEmpty() ? defaultTargetVersion(ndkPath) : targetVersion; version = version.replace(QLatin1Char('.'), QLatin1Char('_')); if (Utils::HostOsInfo::isWindowsHost()) envFile = ndkPath + QLatin1String("/bbndk-env_") + version + QLatin1String(".bat"); else if (Utils::HostOsInfo::isAnyUnixHost()) envFile = ndkPath + QLatin1String("/bbndk-env_") + version + QLatin1String(".sh"); } return envFile; } Utils::FileName QnxUtils::executableWithExtension(const Utils::FileName &fileName) { Utils::FileName result = fileName; if (Utils::HostOsInfo::isWindowsHost()) result.append(QLatin1String(".exe")); return result; } QString QnxUtils::dataDirPath() { const QString homeDir = QDir::homePath(); if (Utils::HostOsInfo::isMacHost()) return homeDir + QLatin1String("/Library/Research in Motion"); if (Utils::HostOsInfo::isAnyUnixHost()) return homeDir + QLatin1String("/.rim"); if (Utils::HostOsInfo::isWindowsHost()) { // Get the proper storage location on Windows using QDesktopServices, // to not hardcode "AppData/Local", as it might refer to "AppData/Roaming". QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation); dataDir = dataDir.left(dataDir.indexOf(QCoreApplication::organizationName())); dataDir.append(QLatin1String("Research in Motion")); return dataDir; } return QString(); } QString QnxUtils::qConfigPath() { if (Utils::HostOsInfo::isMacHost() || Utils::HostOsInfo::isWindowsHost()) return dataDirPath() + QLatin1String("/BlackBerry Native SDK/qconfig"); else return dataDirPath() + QLatin1String("/bbndk/qconfig"); } QString QnxUtils::defaultTargetVersion(const QString &ndkPath) { foreach (const NdkInstallInformation &ndkInfo, installedNdks()) { if (!ndkInfo.path.compare(ndkPath, Utils::HostOsInfo::fileNameCaseSensitivity())) return ndkInfo.version; } return QString(); } QList<NdkInstallInformation> QnxUtils::installedNdks() { QList<NdkInstallInformation> ndkList; QString ndkConfigPath = qConfigPath(); if (!QDir(ndkConfigPath).exists()) return ndkList; QFileInfoList ndkfileList = QDir(ndkConfigPath).entryInfoList(QStringList() << QLatin1String("*.xml"), QDir::Files, QDir::Time); foreach (const QFileInfo &ndkFile, ndkfileList) { QFile xmlFile(ndkFile.absoluteFilePath()); if (!xmlFile.open(QIODevice::ReadOnly)) continue; QDomDocument doc; if (!doc.setContent(&xmlFile)) // Skip error message continue; QDomElement docElt = doc.documentElement(); if (docElt.tagName() != QLatin1String("qnxSystemDefinition")) continue; QDomElement childElt = docElt.firstChildElement(QLatin1String("installation")); // The file contains only one installation node if (!childElt.isNull()) { // The file contains only one base node NdkInstallInformation ndkInfo; ndkInfo.path = childElt.firstChildElement(QLatin1String("base")).text(); ndkInfo.name = childElt.firstChildElement(QLatin1String("name")).text(); ndkInfo.host = childElt.firstChildElement(QLatin1String("host")).text(); ndkInfo.target = childElt.firstChildElement(QLatin1String("target")).text(); ndkInfo.version = childElt.firstChildElement(QLatin1String("version")).text(); ndkList.append(ndkInfo); } } return ndkList; } QString QnxUtils::sdkInstallerPath(const QString &ndkPath) { QString sdkinstallPath; if (Utils::HostOsInfo::isWindowsHost()) sdkinstallPath = ndkPath + QLatin1String("/qde.exe"); else sdkinstallPath = ndkPath + QLatin1String("/qde"); if (QFileInfo(sdkinstallPath).exists()) return sdkinstallPath; return QString(); } // The resulting process when launching sdkinstall QString QnxUtils::qdeInstallProcess(const QString &ndkPath, const QString &option, const QString &version) { QString installerPath = sdkInstallerPath(ndkPath); if (installerPath.isEmpty()) return QString(); return QString::fromLatin1("%1 -nosplash -application com.qnx.tools.ide.sdk.manager.core.SDKInstallerApplication " "%2 %3 -vmargs -Dosgi.console=:none").arg(installerPath, option, version); } QList<Utils::EnvironmentItem> QnxUtils::qnxEnvironment(const QString &sdkPath) { // Mimic what the SDP installer puts into the system environment QList<Utils::EnvironmentItem> environmentItems; if (Utils::HostOsInfo::isWindowsHost()) { // TODO: //environment.insert(QLatin1String("QNX_CONFIGURATION"), QLatin1String("/etc/qnx")); environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_TARGET_KEY), sdkPath + QLatin1String("/target/qnx6"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_HOST_KEY), sdkPath + QLatin1String("/host/win32/x86"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String("PATH"), sdkPath + QLatin1String("/host/win32/x86/usr/bin;%PATH%"))); // TODO: //environment.insert(QLatin1String("PATH"), QLatin1String("/etc/qnx/bin")); } else if (Utils::HostOsInfo::isAnyUnixHost()) { environmentItems.append(Utils::EnvironmentItem(QLatin1String("QNX_CONFIGURATION"), QLatin1String("/etc/qnx"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_TARGET_KEY), sdkPath + QLatin1String("/target/qnx6"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_HOST_KEY), sdkPath + QLatin1String("/host/linux/x86"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String("PATH"), sdkPath + QLatin1String("/host/linux/x86/usr/bin:/etc/qnx/bin:${PATH}"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String("LD_LIBRARY_PATH"), sdkPath + QLatin1String("/host/linux/x86/usr/lib:${LD_LIBRARY_PATH}"))); } environmentItems.append(Utils::EnvironmentItem(QLatin1String("QNX_JAVAHOME"), sdkPath + QLatin1String("/_jvm"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String("MAKEFLAGS"), QLatin1String("-I") + sdkPath + QLatin1String("/target/qnx6/usr/include"))); return environmentItems; } <commit_msg>QNX: Use correct command for running the SDK installer<commit_after>/************************************************************************** ** ** Copyright (C) 2012, 2013 BlackBerry Limited. All rights reserved ** ** Contact: BlackBerry ([email protected]) ** Contact: KDAB ([email protected]) ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qnxutils.h" #include "qnxabstractqtversion.h" #include <utils/hostosinfo.h> #include <utils/synchronousprocess.h> #include <QDir> #include <QDesktopServices> #include <QDomDocument> #include <QProcess> #include <QTemporaryFile> #include <QApplication> using namespace Qnx; using namespace Qnx::Internal; namespace { const char *EVAL_ENV_VARS[] = { "QNX_TARGET", "QNX_HOST", "QNX_CONFIGURATION", "MAKEFLAGS", "LD_LIBRARY_PATH", "PATH", "QDE", "CPUVARDIR", "PYTHONPATH" }; } QString QnxUtils::addQuotes(const QString &string) { return QLatin1Char('"') + string + QLatin1Char('"'); } Qnx::QnxArchitecture QnxUtils::cpudirToArch(const QString &cpuDir) { if (cpuDir == QLatin1String("x86")) return Qnx::X86; else if (cpuDir == QLatin1String("armle-v7")) return Qnx::ArmLeV7; else return Qnx::UnknownArch; } QStringList QnxUtils::searchPaths(QnxAbstractQtVersion *qtVersion) { const QDir pluginDir(qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_PLUGINS"))); const QStringList pluginSubDirs = pluginDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); QStringList searchPaths; Q_FOREACH (const QString &dir, pluginSubDirs) { searchPaths << qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_PLUGINS")) + QLatin1Char('/') + dir; } searchPaths << qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_LIBS")); searchPaths << qtVersion->qnxTarget() + QLatin1Char('/') + qtVersion->archString().toLower() + QLatin1String("/lib"); searchPaths << qtVersion->qnxTarget() + QLatin1Char('/') + qtVersion->archString().toLower() + QLatin1String("/usr/lib"); return searchPaths; } QList<Utils::EnvironmentItem> QnxUtils::qnxEnvironmentFromNdkFile(const QString &fileName) { QList <Utils::EnvironmentItem> items; if (!QFileInfo(fileName).exists()) return items; const bool isWindows = Utils::HostOsInfo::isWindowsHost(); // locking creating bbndk-env file wrapper script QTemporaryFile tmpFile( QDir::tempPath() + QDir::separator() + QLatin1String("bbndk-env-eval-XXXXXX") + QLatin1String(isWindows ? ".bat" : ".sh")); if (!tmpFile.open()) return items; tmpFile.setTextModeEnabled(true); // writing content to wrapper script QTextStream fileContent(&tmpFile); if (isWindows) fileContent << QLatin1String("@echo off\n") << QLatin1String("call ") << fileName << QLatin1Char('\n'); else fileContent << QLatin1String("#!/bin/bash\n") << QLatin1String(". ") << fileName << QLatin1Char('\n'); QString linePattern = QString::fromLatin1(isWindows ? "echo %1=%%1%" : "echo %1=$%1"); for (int i = 0, len = sizeof(EVAL_ENV_VARS) / sizeof(const char *); i < len; ++i) fileContent << linePattern.arg(QLatin1String(EVAL_ENV_VARS[i])) << QLatin1Char('\n'); tmpFile.close(); // running wrapper script QProcess process; if (isWindows) process.start(QLatin1String("cmd.exe"), QStringList() << QLatin1String("/C") << tmpFile.fileName()); else process.start(QLatin1String("/bin/bash"), QStringList() << tmpFile.fileName()); // waiting for finish QApplication::setOverrideCursor(Qt::BusyCursor); bool waitResult = process.waitForFinished(10000); QApplication::restoreOverrideCursor(); if (!waitResult) { Utils::SynchronousProcess::stopProcess(process); return items; } if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) return items; // parsing process output QTextStream str(&process); while (!str.atEnd()) { QString line = str.readLine(); int equalIndex = line.indexOf(QLatin1Char('=')); if (equalIndex < 0) continue; QString var = line.left(equalIndex); QString value = line.mid(equalIndex + 1); items.append(Utils::EnvironmentItem(var, value)); } return items; } bool QnxUtils::isValidNdkPath(const QString &ndkPath) { return (QFileInfo(envFilePath(ndkPath)).exists()); } QString QnxUtils::envFilePath(const QString &ndkPath, const QString &targetVersion) { QString envFile; if (Utils::HostOsInfo::isWindowsHost()) envFile = ndkPath + QLatin1String("/bbndk-env.bat"); else if (Utils::HostOsInfo::isAnyUnixHost()) envFile = ndkPath + QLatin1String("/bbndk-env.sh"); if (!QFileInfo(envFile).exists()) { QString version = targetVersion.isEmpty() ? defaultTargetVersion(ndkPath) : targetVersion; version = version.replace(QLatin1Char('.'), QLatin1Char('_')); if (Utils::HostOsInfo::isWindowsHost()) envFile = ndkPath + QLatin1String("/bbndk-env_") + version + QLatin1String(".bat"); else if (Utils::HostOsInfo::isAnyUnixHost()) envFile = ndkPath + QLatin1String("/bbndk-env_") + version + QLatin1String(".sh"); } return envFile; } Utils::FileName QnxUtils::executableWithExtension(const Utils::FileName &fileName) { Utils::FileName result = fileName; if (Utils::HostOsInfo::isWindowsHost()) result.append(QLatin1String(".exe")); return result; } QString QnxUtils::dataDirPath() { const QString homeDir = QDir::homePath(); if (Utils::HostOsInfo::isMacHost()) return homeDir + QLatin1String("/Library/Research in Motion"); if (Utils::HostOsInfo::isAnyUnixHost()) return homeDir + QLatin1String("/.rim"); if (Utils::HostOsInfo::isWindowsHost()) { // Get the proper storage location on Windows using QDesktopServices, // to not hardcode "AppData/Local", as it might refer to "AppData/Roaming". QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation); dataDir = dataDir.left(dataDir.indexOf(QCoreApplication::organizationName())); dataDir.append(QLatin1String("Research in Motion")); return dataDir; } return QString(); } QString QnxUtils::qConfigPath() { if (Utils::HostOsInfo::isMacHost() || Utils::HostOsInfo::isWindowsHost()) return dataDirPath() + QLatin1String("/BlackBerry Native SDK/qconfig"); else return dataDirPath() + QLatin1String("/bbndk/qconfig"); } QString QnxUtils::defaultTargetVersion(const QString &ndkPath) { foreach (const NdkInstallInformation &ndkInfo, installedNdks()) { if (!ndkInfo.path.compare(ndkPath, Utils::HostOsInfo::fileNameCaseSensitivity())) return ndkInfo.version; } return QString(); } QList<NdkInstallInformation> QnxUtils::installedNdks() { QList<NdkInstallInformation> ndkList; QString ndkConfigPath = qConfigPath(); if (!QDir(ndkConfigPath).exists()) return ndkList; QFileInfoList ndkfileList = QDir(ndkConfigPath).entryInfoList(QStringList() << QLatin1String("*.xml"), QDir::Files, QDir::Time); foreach (const QFileInfo &ndkFile, ndkfileList) { QFile xmlFile(ndkFile.absoluteFilePath()); if (!xmlFile.open(QIODevice::ReadOnly)) continue; QDomDocument doc; if (!doc.setContent(&xmlFile)) // Skip error message continue; QDomElement docElt = doc.documentElement(); if (docElt.tagName() != QLatin1String("qnxSystemDefinition")) continue; QDomElement childElt = docElt.firstChildElement(QLatin1String("installation")); // The file contains only one installation node if (!childElt.isNull()) { // The file contains only one base node NdkInstallInformation ndkInfo; ndkInfo.path = childElt.firstChildElement(QLatin1String("base")).text(); ndkInfo.name = childElt.firstChildElement(QLatin1String("name")).text(); ndkInfo.host = childElt.firstChildElement(QLatin1String("host")).text(); ndkInfo.target = childElt.firstChildElement(QLatin1String("target")).text(); ndkInfo.version = childElt.firstChildElement(QLatin1String("version")).text(); ndkList.append(ndkInfo); } } return ndkList; } QString QnxUtils::sdkInstallerPath(const QString &ndkPath) { QString sdkinstallPath; if (Utils::HostOsInfo::isWindowsHost()) sdkinstallPath = ndkPath + QLatin1String("/qde.exe"); else sdkinstallPath = ndkPath + QLatin1String("/qde"); if (QFileInfo(sdkinstallPath).exists()) return sdkinstallPath; return QString(); } // The resulting process when launching sdkinstall QString QnxUtils::qdeInstallProcess(const QString &ndkPath, const QString &option, const QString &version) { QString installerPath = sdkInstallerPath(ndkPath); if (installerPath.isEmpty()) return QString(); const QDir pluginDir(ndkPath + QLatin1String("/plugins")); const QStringList installerPlugins = pluginDir.entryList(QStringList() << QLatin1String("com.qnx.tools.ide.sdk.installer.app_*.jar")); const QString installerApplication = installerPlugins.size() >= 1 ? QLatin1String("com.qnx.tools.ide.sdk.installer.app.SDKInstallerApplication") : QLatin1String("com.qnx.tools.ide.sdk.manager.core.SDKInstallerApplication"); return QString::fromLatin1("%1 -nosplash -application %2 " "%3 %4 -vmargs -Dosgi.console=:none").arg(installerPath, installerApplication, option, version); } QList<Utils::EnvironmentItem> QnxUtils::qnxEnvironment(const QString &sdkPath) { // Mimic what the SDP installer puts into the system environment QList<Utils::EnvironmentItem> environmentItems; if (Utils::HostOsInfo::isWindowsHost()) { // TODO: //environment.insert(QLatin1String("QNX_CONFIGURATION"), QLatin1String("/etc/qnx")); environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_TARGET_KEY), sdkPath + QLatin1String("/target/qnx6"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_HOST_KEY), sdkPath + QLatin1String("/host/win32/x86"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String("PATH"), sdkPath + QLatin1String("/host/win32/x86/usr/bin;%PATH%"))); // TODO: //environment.insert(QLatin1String("PATH"), QLatin1String("/etc/qnx/bin")); } else if (Utils::HostOsInfo::isAnyUnixHost()) { environmentItems.append(Utils::EnvironmentItem(QLatin1String("QNX_CONFIGURATION"), QLatin1String("/etc/qnx"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_TARGET_KEY), sdkPath + QLatin1String("/target/qnx6"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_HOST_KEY), sdkPath + QLatin1String("/host/linux/x86"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String("PATH"), sdkPath + QLatin1String("/host/linux/x86/usr/bin:/etc/qnx/bin:${PATH}"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String("LD_LIBRARY_PATH"), sdkPath + QLatin1String("/host/linux/x86/usr/lib:${LD_LIBRARY_PATH}"))); } environmentItems.append(Utils::EnvironmentItem(QLatin1String("QNX_JAVAHOME"), sdkPath + QLatin1String("/_jvm"))); environmentItems.append(Utils::EnvironmentItem(QLatin1String("MAKEFLAGS"), QLatin1String("-I") + sdkPath + QLatin1String("/target/qnx6/usr/include"))); return environmentItems; } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include<iostream> #include<thread> #include<cstdio> #include<cstring> #include<sys/socket.h> #include<sys/un.h> #include<sys/types.h> #include<unistd.h> #include<signal.h> #include <wiringPi.h> namespace { int socket_fd; const std::size_t UNIX_PATH_MAX = 108; const std::size_t gpio_led_pin = 1; char buffer[4096]; void connection_handler(int connection_fd){ std::cout << "asgard: New connection received" << std::endl; int nbytes; while((nbytes = read(connection_fd, buffer, 4096)) > 0){ buffer[nbytes] = 0; std::cout << "asgard: Received message: " << buffer << std::endl; } close(connection_fd); } void close(){ digitalWrite(gpio_led_pin, LOW); close(socket_fd); unlink("/tmp/asgard_socket"); } void terminate(int /*signo*/){ close(); abort(); } bool revoke_root(){ if (getuid() == 0) { if (setgid(1000) != 0){ std::cout << "asgard: setgid: Unable to drop group privileges: " << strerror(errno) << std::endl; return false; } if (setuid(1000) != 0){ std::cout << "asgard: setgid: Unable to drop user privileges: " << strerror(errno) << std::endl; return false; } } if (setuid(0) != -1){ std::cout << "asgard: managed to regain root privileges, exiting..." << std::endl; return false; } return true; } } //end of anonymous namespace int main(){ //Run the wiringPi setup (as root) wiringPiSetup(); //Drop root privileges and run as pi:pi again if(!revoke_root()){ std::cout << "asgard: unable to revoke root privileges, exiting..." << std::endl; return 1; } //Register signals for "proper" shutdown signal(SIGTERM, terminate); signal(SIGINT, terminate); pinMode(gpio_led_pin, OUTPUT); digitalWrite(gpio_led_pin, HIGH); //Open the socket socket_fd = socket(PF_UNIX, SOCK_STREAM, 0); if(socket_fd < 0){ printf("socket() failed\n"); return 1; } unlink("/tmp/asgard_socket"); //Init the address struct sockaddr_un address; memset(&address, 0, sizeof(struct sockaddr_un)); address.sun_family = AF_UNIX; snprintf(address.sun_path, UNIX_PATH_MAX, "/tmp/asgard_socket"); //Bind if(bind(socket_fd, (struct sockaddr *) &address, sizeof(struct sockaddr_un)) != 0){ printf("bind() failed\n"); return 1; } if(listen(socket_fd, 5) != 0){ printf("listen() failed\n"); return 1; } int connection_fd; socklen_t address_length; while((connection_fd = accept(socket_fd, (struct sockaddr *) &address, &address_length)) > -1){ std::thread(connection_handler, connection_fd).detach(); } close(); return 0; } <commit_msg>Fix buffer<commit_after>//======================================================================= // Copyright (c) 2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include<iostream> #include<thread> #include<cstdio> #include<cstring> #include<sys/socket.h> #include<sys/un.h> #include<sys/types.h> #include<unistd.h> #include<signal.h> #include <wiringPi.h> namespace { int socket_fd; const std::size_t UNIX_PATH_MAX = 108; const std::size_t gpio_led_pin = 1; const std::size_t socket_buffer_size = 4096; void connection_handler(int connection_fd){ char buffer[socket_buffer_size]; std::cout << "asgard: New connection received" << std::endl; int nbytes; while((nbytes = read(connection_fd, buffer, socket_buffer_size)) > 0){ buffer[nbytes] = 0; std::cout << "asgard: Received message: " << buffer << std::endl; } close(connection_fd); } void close(){ digitalWrite(gpio_led_pin, LOW); close(socket_fd); unlink("/tmp/asgard_socket"); } void terminate(int /*signo*/){ close(); abort(); } bool revoke_root(){ if (getuid() == 0) { if (setgid(1000) != 0){ std::cout << "asgard: setgid: Unable to drop group privileges: " << strerror(errno) << std::endl; return false; } if (setuid(1000) != 0){ std::cout << "asgard: setgid: Unable to drop user privileges: " << strerror(errno) << std::endl; return false; } } if (setuid(0) != -1){ std::cout << "asgard: managed to regain root privileges, exiting..." << std::endl; return false; } return true; } } //end of anonymous namespace int main(){ //Run the wiringPi setup (as root) wiringPiSetup(); //Drop root privileges and run as pi:pi again if(!revoke_root()){ std::cout << "asgard: unable to revoke root privileges, exiting..." << std::endl; return 1; } //Register signals for "proper" shutdown signal(SIGTERM, terminate); signal(SIGINT, terminate); pinMode(gpio_led_pin, OUTPUT); digitalWrite(gpio_led_pin, HIGH); //Open the socket socket_fd = socket(PF_UNIX, SOCK_STREAM, 0); if(socket_fd < 0){ printf("socket() failed\n"); return 1; } unlink("/tmp/asgard_socket"); //Init the address struct sockaddr_un address; memset(&address, 0, sizeof(struct sockaddr_un)); address.sun_family = AF_UNIX; snprintf(address.sun_path, UNIX_PATH_MAX, "/tmp/asgard_socket"); //Bind if(bind(socket_fd, (struct sockaddr *) &address, sizeof(struct sockaddr_un)) != 0){ printf("bind() failed\n"); return 1; } if(listen(socket_fd, 5) != 0){ printf("listen() failed\n"); return 1; } int connection_fd; socklen_t address_length; while((connection_fd = accept(socket_fd, (struct sockaddr *) &address, &address_length)) > -1){ std::thread(connection_handler, connection_fd).detach(); } close(); return 0; } <|endoftext|>
<commit_before>/* * ============================================================================ * Filename: server.hxx * Description: Server side implementation for flihabi network * Version: 1.0 * Created: 04/20/2015 06:21:00 PM * Revision: none * Compiler: gcc * Author: Rafael Gozlan * Organization: Flihabi * ============================================================================ */ #include <thread> #include <iostream> #include "server.hh" #include "broadcaster.hh" #include "listener.hh" #include "network.hh" // PUBLIC METHODS Server::Server(int port) : results_(), busy_(), todo_() { port_ = port; // Launch the server broadcaster and connection handler std::thread broadcaster(broadcastLoop); broadcaster.detach(); std::thread handler(Server::handler); handler.detach(); } Result *Server::getResult(int i) { Result *r = results_[i]; if (r != NULL) { results_[i] = NULL; busy_[i] = false; /* set busy to false so the emplacement is free*/ } return r; } // PRIVATE METHODS void Server::setResult(int i, std::string s) { Result *r = new Result(); /* TODO: Test if s is persistant */ r->value = s; results_[i] = r; } int Server::getResultEmplacement() { for (size_t i = 0; i < busy_.size(); i++) { if (!busy_[i]) { busy_[i] = true; return i; } } /* Add emplacement */ busy_.push_back(false); results_.push_back(NULL); return getResultEmplacement(); /* FIXME: not optimal */ } /* Server slaves handling */ void Server::handler() { int sockfd, new_fd; // listen on sock_fd, new connection on new_fd struct addrinfo hints, *servinfo, *p; struct sockaddr_storage their_addr; // connector's address information socklen_t sin_size; int yes=1; char s[INET6_ADDRSTRLEN]; int rv; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP if ((rv = getaddrinfo(NULL, std::to_string(CONNECTION_PORT).c_str(), &hints, &servinfo)) != 0) { fprintf(stderr, "Handler: getaddrinfo: %s\n", gai_strerror(rv)); return; } // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("Handler: socket"); continue; } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("Handler: setsockopt"); exit(1); } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("Handler: bind"); continue; } break; } if (p == NULL) { fprintf(stderr, "Handler: failed to bind\n"); return; } freeaddrinfo(servinfo); // all done with this structure if (listen(sockfd, 10) == -1) { perror("listen"); exit(1); } printf("Handler: waiting for connections...\n"); while (true) /* I love stuff like this */ { sin_size = sizeof their_addr; new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); if (new_fd == -1) { perror("Handler: accept"); continue; } inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s); printf("Handler: got connection from %s\n", s); std::thread client(clientThread, new_fd); } } void Server::clientThread(int s) { std::cout << "Client thread: Hello!" << std::endl; if (s) return; } <commit_msg>Server: sending ack after slave connection<commit_after>/* * ============================================================================ * Filename: server.hxx * Description: Server side implementation for flihabi network * Version: 1.0 * Created: 04/20/2015 06:21:00 PM * Revision: none * Compiler: gcc * Author: Rafael Gozlan * Organization: Flihabi * ============================================================================ */ #include <thread> #include <iostream> #include "server.hh" #include "broadcaster.hh" #include "listener.hh" #include "network.hh" // PUBLIC METHODS Server::Server(int port) : results_(), busy_(), todo_() { port_ = port; // Launch the server broadcaster and connection handler std::thread broadcaster(broadcastLoop); broadcaster.detach(); std::thread handler(Server::handler); handler.detach(); } Result *Server::getResult(int i) { Result *r = results_[i]; if (r != NULL) { results_[i] = NULL; busy_[i] = false; /* set busy to false so the emplacement is free*/ } return r; } // PRIVATE METHODS void Server::setResult(int i, std::string s) { Result *r = new Result(); /* TODO: Test if s is persistant */ r->value = s; results_[i] = r; } int Server::getResultEmplacement() { for (size_t i = 0; i < busy_.size(); i++) { if (!busy_[i]) { busy_[i] = true; return i; } } /* Add emplacement */ busy_.push_back(false); results_.push_back(NULL); return getResultEmplacement(); /* FIXME: not optimal */ } /* Server slaves handling */ void Server::handler() { int sockfd, new_fd; // listen on sock_fd, new connection on new_fd struct addrinfo hints, *servinfo, *p; struct sockaddr_storage their_addr; // connector's address information socklen_t sin_size; int yes=1; char s[INET6_ADDRSTRLEN]; int rv; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP if ((rv = getaddrinfo(NULL, std::to_string(CONNECTION_PORT).c_str(), &hints, &servinfo)) != 0) { fprintf(stderr, "Handler: getaddrinfo: %s\n", gai_strerror(rv)); return; } // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("Handler: socket"); continue; } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("Handler: setsockopt"); exit(1); } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("Handler: bind"); continue; } break; } if (p == NULL) { fprintf(stderr, "Handler: failed to bind\n"); return; } freeaddrinfo(servinfo); // all done with this structure if (listen(sockfd, 10) == -1) { perror("listen"); exit(1); } printf("Handler: waiting for connections...\n"); while (true) /* I love stuff like this */ { sin_size = sizeof their_addr; new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); if (new_fd == -1) { perror("Handler: accept"); continue; } inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s); printf("Handler: got connection from %s\n", s); int numbytes; char buf[100]; // Receiving connection msg if ((numbytes = recv(sockfd, buf, 100-1, 0)) == -1) { perror("Server: failed to recv the connection msg"); exit(1); } buf[numbytes] = '\0'; printf("Server: received '%s'\n",buf); if (std::string(buf) == CONNECTION_MSG) { std::thread client(clientThread, new_fd); client.detach(); } } } void Server::clientThread(int sockfd) { std::cout << "Client thread: sending Hello!" << std::endl; // Sending ACK if (send(sockfd, CONNECTION_MSG, strlen(CONNECTION_MSG), 0) == -1) perror("Server: failed sending Hello!"); // Receiving ACK } <|endoftext|>
<commit_before>/** * @file * * @brief Read key sets using yaml-cpp * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include "read.hpp" #include "yaml-cpp/yaml.h" #include <kdb.hpp> #include <kdbease.h> #include <kdblogger.h> #include <kdbplugin.h> #include <sstream> using namespace std; using namespace kdb; namespace { /** * @brief This function creates a new key from the given parameters. * * @param name This string specifies the postfix of the name of the key produced by this function. * @param parent This key specifies the prefix of the name of the key produced by this function. * * @returns The function returns a new key that combines the name of the parent key and `name`. */ Key newKey (string const & name, Key const & parent) { ELEKTRA_LOG_DEBUG ("Add new key with base name “%s”", name.c_str ()); Key key{ parent.getFullName (), KEY_BINARY, KEY_END }; key.addBaseName (name); return key; } /** * @brief This function creates a new array key from the given parameters. * * @param mappings This argument specifies the key set of the new key this function creates. * @param arrayKey This argument specifies the key that represents the root of the array. * * @returns The function returns a new key that is part of the array represented by `arrayKey`. */ Key newArrayKey (KeySet const & mappings, Key & arrayKey) { ELEKTRA_LOG_DEBUG ("Add new array element to array parent “%s”", arrayKey.getName ().c_str ()); KeySet arrayEntries{ elektraArrayGet (*arrayKey, mappings.getKeySet ()) }; if (arrayEntries.size () <= 0) { Key first = arrayKey.dup (); first.addBaseName ("#"); arrayEntries.append (first); } Key newKey{ elektraArrayGetNextKey (arrayEntries.getKeySet ()) }; arrayKey.setMeta ("array", newKey.getBaseName ()); return newKey; } /** * @brief Add metadata saved in a YAML map to the specified key * * @param key This parameter saves the key to which this function should add the metadata stored in `node`. * @param node This YAML node stores a map containing metadata. */ void addMetadata (Key & key, YAML::Node const & node) { for (auto & element : node) { auto metakey = element.first.as<string> (); auto metavalue = element.second.IsNull () ? "" : element.second.as<string> (); ELEKTRA_LOG_DEBUG ("Add metakey “%s: %s”", metakey.c_str (), metavalue.c_str ()); key.setMeta (metakey, metavalue); } } /** * @brief Create a key containing a (possibly empty) value. * * @param node This YAML node stores the data that should be converted to a new `Key`. * @param name This text specifies the name of the key this function creates. * * @return A new key containing the data specified in `node` */ Key createLeafKey (YAML::Node const & node, string const & name) { Key key{ name, KEY_BINARY, KEY_END }; if (!node.IsNull ()) { try { key.set<bool> (node.as<bool> ()); } catch (YAML::BadConversion const &) { key.setString (node.as<string> ()); } } if (node.Tag () == "tag:yaml.org,2002:binary") { ELEKTRA_LOG_DEBUG ("Set metadata type of key to binary"); key.setMeta ("type", "binary"); } ELEKTRA_LOG_DEBUG ("Add key “%s: %s”", key.getName ().c_str (), key.getBinarySize () == 0 ? "NULL" : key.isBinary () ? "binary value!" : key.get<string> ().c_str ()); return key; } /** * @brief Convert the key value of a YAML meta node to a key * * @param node This YAML meta node stores the data this function stores in the returned key * @param parent This key stores the prefix for the key name * * @return A key representing the key value stored in `node` */ Key convertMetaNodeToKey (YAML::Node const & node, Key & parent) { auto key = node[0].IsNull () ? Key{ parent.getFullName (), KEY_BINARY, KEY_END } : Key{ parent.getFullName (), KEY_VALUE, node[0].as<string> ().c_str (), KEY_END }; ELEKTRA_LOG_DEBUG ("Add key “%s”: “%s”", key.getName ().c_str (), key.getBinarySize () == 0 ? "NULL" : key.isString () ? key.getString ().c_str () : "binary value!"); return key; } /** * @brief Convert a YAML node to a key set * * @param node This YAML node stores the data that should be added to the keyset `mappings` * @param mappings The key set where the YAML data will be stored * @param parent This key stores the prefix for the key name */ void convertNodeToKeySet (YAML::Node const & node, KeySet & mappings, Key & parent) { if (node.Tag () == "!elektra/meta") { auto key = convertMetaNodeToKey (node, parent); mappings.append (key); addMetadata (key, node[1]); } else if (node.IsScalar () || node.IsNull ()) { auto key = createLeafKey (node, parent.getFullName ()); mappings.append (key); } else if (node.IsMap () || node.IsSequence ()) { for (auto element : node) { Key key = node.IsMap () ? newKey (element.first.as<string> (), parent) : newArrayKey (mappings, parent); if (!node.IsMap ()) mappings.append (parent); // Update array metadata convertNodeToKeySet (node.IsMap () ? element.second : element, mappings, key); } } } } // end namespace /** * @brief Read a YAML file and add the resulting data to a given key set * * @param mappings The key set where the YAML data will be stored * @param parent This key stores the path to the YAML data file that should be read */ void yamlcpp::yamlRead (KeySet & mappings, Key & parent) { YAML::Node config = YAML::LoadFile (parent.getString ()); #ifdef HAVE_LOGGER ostringstream data; data << config; ELEKTRA_LOG_DEBUG ("Read Data:"); ELEKTRA_LOG_DEBUG ("——————————"); istringstream stream (data.str ()); for (string line; std::getline (stream, line);) { ELEKTRA_LOG_DEBUG ("%s", line.c_str ()); } ELEKTRA_LOG_DEBUG ("——————————"); #endif convertNodeToKeySet (config, mappings, parent); ELEKTRA_LOG_DEBUG ("Added %zd key%s", mappings.size (), mappings.size () == 1 ? "" : "s"); } <commit_msg>YAML CPP: Improve read performance<commit_after>/** * @file * * @brief Read key sets using yaml-cpp * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include "read.hpp" #include "yaml-cpp/yaml.h" #include <kdb.hpp> #include <kdbease.h> #include <kdblogger.h> #include <kdbplugin.h> #include <sstream> using namespace std; using namespace kdb; namespace { /** * @brief This function creates a new key from the given parameters. * * @param name This string specifies the postfix of the name of the key produced by this function. * @param parent This key specifies the prefix of the name of the key produced by this function. * * @returns The function returns a new key that combines the name of the parent key and `name`. */ Key newKey (string const & name, Key const & parent) { ELEKTRA_LOG_DEBUG ("Add new key with base name “%s”", name.c_str ()); Key key{ parent.getFullName (), KEY_BINARY, KEY_END }; key.addBaseName (name); return key; } /** * @brief This function creates a new array key from the given parameters. * * @param mappings This argument specifies the key set of the new key this function creates. * @param arrayKey This argument specifies the key that represents the root of the array. * * @returns The function returns a new key that is part of the array represented by `arrayKey`. */ Key newArrayKey (KeySet const & mappings, Key & arrayKey) { ELEKTRA_LOG_DEBUG ("Add new array element to array parent “%s”", arrayKey.getName ().c_str ()); KeySet arrayEntries{ elektraArrayGet (*arrayKey, mappings.getKeySet ()) }; if (arrayEntries.size () <= 0) { Key first = arrayKey.dup (); first.addBaseName ("#"); arrayEntries.append (first); } Key newKey{ elektraArrayGetNextKey (arrayEntries.getKeySet ()) }; arrayKey.setMeta ("array", newKey.getBaseName ()); return newKey; } /** * @brief Add metadata saved in a YAML map to the specified key * * @param key This parameter saves the key to which this function should add the metadata stored in `node`. * @param node This YAML node stores a map containing metadata. */ void addMetadata (Key & key, YAML::Node const & node) { for (auto & element : node) { auto metakey = element.first.as<string> (); auto metavalue = element.second.IsNull () ? "" : element.second.as<string> (); ELEKTRA_LOG_DEBUG ("Add metakey “%s: %s”", metakey.c_str (), metavalue.c_str ()); key.setMeta (metakey, metavalue); } } /** * @brief Create a key containing a (possibly empty) value. * * @param node This YAML node stores the data that should be converted to a new `Key`. * @param name This text specifies the name of the key this function creates. * * @return A new key containing the data specified in `node` */ Key createLeafKey (YAML::Node const & node, string const & name) { Key key{ name, KEY_BINARY, KEY_END }; if (!node.IsNull ()) { auto value = node.as<string> (); if (value == "true" || value == "false") { try { key.set<bool> (node.as<bool> ()); } catch (YAML::BadConversion const &) { key.set<string> (value); // Save value as string, if `node` is a quoted scalar } } else { key.set<string> (value); } } if (node.Tag () == "tag:yaml.org,2002:binary") { ELEKTRA_LOG_DEBUG ("Set metadata type of key to binary"); key.setMeta ("type", "binary"); } ELEKTRA_LOG_DEBUG ("Add key “%s: %s”", key.getName ().c_str (), key.getBinarySize () == 0 ? "NULL" : key.isBinary () ? "binary value!" : key.get<string> ().c_str ()); return key; } /** * @brief Convert the key value of a YAML meta node to a key * * @param node This YAML meta node stores the data this function stores in the returned key * @param parent This key stores the prefix for the key name * * @return A key representing the key value stored in `node` */ Key convertMetaNodeToKey (YAML::Node const & node, Key & parent) { auto key = node[0].IsNull () ? Key{ parent.getFullName (), KEY_BINARY, KEY_END } : Key{ parent.getFullName (), KEY_VALUE, node[0].as<string> ().c_str (), KEY_END }; ELEKTRA_LOG_DEBUG ("Add key “%s”: “%s”", key.getName ().c_str (), key.getBinarySize () == 0 ? "NULL" : key.isString () ? key.getString ().c_str () : "binary value!"); return key; } /** * @brief Convert a YAML node to a key set * * @param node This YAML node stores the data that should be added to the keyset `mappings` * @param mappings The key set where the YAML data will be stored * @param parent This key stores the prefix for the key name */ void convertNodeToKeySet (YAML::Node const & node, KeySet & mappings, Key & parent) { if (node.Tag () == "!elektra/meta") { auto key = convertMetaNodeToKey (node, parent); mappings.append (key); addMetadata (key, node[1]); } else if (node.IsScalar () || node.IsNull ()) { auto key = createLeafKey (node, parent.getFullName ()); mappings.append (key); } else if (node.IsMap () || node.IsSequence ()) { for (auto element : node) { Key key = node.IsMap () ? newKey (element.first.as<string> (), parent) : newArrayKey (mappings, parent); if (!node.IsMap ()) mappings.append (parent); // Update array metadata convertNodeToKeySet (node.IsMap () ? element.second : element, mappings, key); } } } } // end namespace /** * @brief Read a YAML file and add the resulting data to a given key set * * @param mappings The key set where the YAML data will be stored * @param parent This key stores the path to the YAML data file that should be read */ void yamlcpp::yamlRead (KeySet & mappings, Key & parent) { YAML::Node config = YAML::LoadFile (parent.getString ()); #ifdef HAVE_LOGGER ostringstream data; data << config; ELEKTRA_LOG_DEBUG ("Read Data:"); ELEKTRA_LOG_DEBUG ("——————————"); istringstream stream (data.str ()); for (string line; std::getline (stream, line);) { ELEKTRA_LOG_DEBUG ("%s", line.c_str ()); } ELEKTRA_LOG_DEBUG ("——————————"); #endif convertNodeToKeySet (config, mappings, parent); ELEKTRA_LOG_DEBUG ("Added %zd key%s", mappings.size (), mappings.size () == 1 ? "" : "s"); } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include "consoleui.h" #include "scientist.h" using namespace std; ConsoleUI::ConsoleUI() { } // Should not contain logic for individual commands, that should be in separate functions! void ConsoleUI::run() { string command; do { cout << "Select one of the following options: " << endl; cout << "Add - add a programmer/computer scientist" << endl; cout << "List - add a programmer/computer scientist" << endl; cout << "Quit - end program" << endl; cin >> command; if(command == "add" || command == "Add" || command == "ADD") // Could possibly be improved upon { userMenuAdd(); } if(command == "list" || command == "List" || command == "LIST") // Could possibly be improved upon { userMenuList(); } }while(command != "quit"); } void ConsoleUI::userMenuAdd() { string name; char gender; int birthYear; int deathYear = 0; //int age = 22; // TEMP cout << "Enter the programmer's/computer scientist's name: "; cin >> name; // TODO - take in as ( GETLINE ) cout << "Enter the programmer's/computer scientist's gender (m/f): "; cin >> gender; cout << "Enter the programmer's/computer scientist's year of birth: "; cin >> birthYear; cout << "Enter the programmer's/computer scientist's year of death (leave empty if not applicable): "; cin >> deathYear; Scientist newScientist(name, gender, birthYear, deathYear); } void ConsoleUI::userMenuList() { vector<Scientist> scientist = _service.getScientist(); cout << "Performer name:" << endl; cout << "===============" << endl; for (size_t i = 0; i< scientist.size(); ++i) { cout << scientist[i].getName() << endl; } } <commit_msg>Text fix<commit_after>#include <iostream> #include <string> #include "consoleui.h" #include "scientist.h" using namespace std; ConsoleUI::ConsoleUI() { } // Should not contain logic for individual commands, that should be in separate functions! void ConsoleUI::run() { string command; do { cout << "Select one of the following options: " << endl; cout << "Add - add a programmer/computer scientist" << endl; cout << "List - add a programmer/computer scientist" << endl; cout << "Quit - end program" << endl; cin >> command; if(command == "add" || command == "Add" || command == "ADD") // Could possibly be improved upon { userMenuAdd(); } if(command == "list" || command == "List" || command == "LIST") // Could possibly be improved upon { userMenuList(); } }while(command != "quit"); } void ConsoleUI::userMenuAdd() { string name; char gender; int birthYear; int deathYear = 0; //int age = 22; // TEMP cout << "Enter the programmer's/computer scientist's name: "; cin >> name; // TODO - take in as ( GETLINE ) cout << "Enter the programmer's/computer scientist's gender (m/f): "; cin >> gender; cout << "Enter the programmer's/computer scientist's year of birth: "; cin >> birthYear; cout << "Enter the programmer's/computer scientist's year of death (leave empty if not applicable): "; cin >> deathYear; Scientist newScientist(name, gender, birthYear, deathYear); } void ConsoleUI::userMenuList() { vector<Scientist> scientist = _service.getScientist(); cout << "Scientist name:" << endl; cout << "===============" << endl; for (size_t i = 0; i< scientist.size(); ++i) { cout << scientist[i].getName() << endl; } } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include "consoleui.h" #include "scientist.h" using namespace std; ConsoleUI::ConsoleUI() { _service.getScientists(); // gets information from file so it's used from the beginning. } // Should not contain logic for individual commands, that should be in separate functions! void ConsoleUI::run() { string command; while(true) { cout << "Select one of the following options: " << endl; cout << "=====================================" << endl; cout << "Add - add a programmer/computer scientist" << endl; cout << "Remove - remove a programmer/computer scientist" << endl; cout << "List - show a list of all programmer's/computer scientist's" << endl; cout << "Search - search the list of programmer's/computer scientist's" << endl; cout << "Sort - sort list by name, gender, age or year of death" << endl; cout << "Quit - end program" << endl; cin >> command; for(unsigned int i = 0; i < command.length(); i++) // to make all lowercase, taken from c++ site { command[i] = tolower(command[i]); } if(command == "add") { userMenuAdd(); } else if(command == "remove") { userMenuRemove(); } else if(command == "list") { userMenuList(); } else if(command == "search") { userMenuSearch(); } else if(command == "sort") { userMenuSort(); } else if(command == "quit") { break; } else { cout << "Invalid input" << endl; } } } void ConsoleUI::userMenuAdd() { string name; char gender; int birthYear; int deathYear = 0; int age = 0; int a; while(true) { cout << "Enter the programmer's/computer scientist's name: "; cin.ignore(); getline(cin, name); // Check for gender while(true) { cout << "Enter the programmer's/computer scientist's gender (m/f): "; cin >> gender; if((gender != 'm') && (gender != 'f')) { cout << "Invalid input" << endl; } else { break; } } // Check year of birth while(true) { cout << "Enter the programmer's/computer scientist's year of birth: "; cin >> birthYear; if(birthYear < 2016) // Just in case we find a programmer of the univers { break; } else { cout << "Invalid input" << endl; } } // Check when year of death (if dead) while(true) { cout << "Enter the programmer's/computer scientist's year of death (type 0 if not applicable): "; cin >> deathYear; if (deathYear == 0) { break; } else if(deathYear >= birthYear) { break; } else { cout << "Invalid input" << endl; } } // Check if input is correct cout << "Name: " << name << endl << "Gender: " << gender << endl << "Born: " << birthYear << endl; if(deathYear != 0) { cout << "Died: " << deathYear << endl; } else { cout << endl; } a = userCheckInput(); if (a == 0) { _service.addScientist(name, gender, birthYear, deathYear, age); break; } else if (a == 2) { break; } } cout << endl; } void ConsoleUI::userMenuList() { vector<Scientist> scientist = _service.getScientists(); userMenuPrint(scientist); } void ConsoleUI::userMenuSearch() { string command; cout << "Select a search option: " << endl; cout << "Name - Search by name" << endl; cout << "Gender - Search by gender" << endl; cout << "Age - Search by age" << endl; cout << "Birth - search by year of birth" << endl; cout << "Death - search by year of death" << endl; cin >> command; cout << endl; for(unsigned int i = 0; i < command.length(); i++) // to make all lowercase, taken from c++ site { command[i] = tolower(command[i]); } if(command == "name") { string userInputName; cout << "Search by name: "; cin.ignore(); getline(cin, userInputName); vector<Scientist> scientist = _service.findScientistByName(userInputName); userMenuPrint(scientist); } else if(command == "gender") // findScientistByGender { char userInputGender; cout << "Search by gender: "; cin >> userInputGender; vector<Scientist> scientist = _service.findScientistByGender(userInputGender); userMenuPrint(scientist); } else if(command == "age") // findScientistByGender { int userInputAge; cout << "Search by age: "; cin >> userInputAge; vector<Scientist> scientist = _service.findScientistByAge(userInputAge); userMenuPrint(scientist); } else if(command == "birth") { int userInputBirth; cout << "Search by year of birth: "; cin >> userInputBirth; vector<Scientist> scientist = _service.findScientistByBirth(userInputBirth); userMenuPrint(scientist); } else if(command == "death") { int userInputDeath; cout << "Search by year of death (0 for still alive): "; cin >> userInputDeath; vector<Scientist> scientist = _service.findScientistByDeath(userInputDeath); userMenuPrint(scientist); } cout << endl; } void ConsoleUI::userMenuSort() { int userInput; cout << "Sort list by Name A-Z(1), Name Z-A(2), Gender(3), Year of Birth(4), Year of Death(5) or Age (6)" << endl; cin >> userInput; _service.scientistSort(userInput); userMenuList(); } void ConsoleUI::userMenuPrint(vector<Scientist>scientist) { cout << endl; cout << "Scientist name: gender: born: died: age: " << endl; cout << "====================================================" << endl; for (size_t i = 0; i< scientist.size(); ++i) { cout << scientist[i].getName() << "\t" << scientist[i].getGender() << "\t" << scientist[i].getBirth() << "\t"; if(scientist[i].getDeath() == 0) { cout << "-" << "\t"; } else { cout << scientist[i].getDeath() << "\t"; } cout << scientist[i].getAge() << endl; } cout << endl; } int ConsoleUI::userCheckInput() { // Check if all data is correct while(true) { char answear; cout << "Is this data correct? (input y/n) or press q to quit" << endl; cin >> answear; if(answear == 'y') { return 0; } else if (answear == 'n') { return 1; } else if (answear == 'q') { return 2; } else { cout << "Invalid input!"; } } } void ConsoleUI::userMenuRemove() { string userInputName; cout << "Remove a programmer/computer scientist: "; cin.ignore(); getline(cin, userInputName); _service.removeScientist(userInputName); } <commit_msg>ui update<commit_after>#include <iostream> #include <string> #include "consoleui.h" #include "scientist.h" using namespace std; ConsoleUI::ConsoleUI() { _service.getScientists(); // gets information from file so it's used from the beginning. } // Should not contain logic for individual commands, that should be in separate functions! void ConsoleUI::run() { string command; while(true) { cout << "Select one of the following options: " << endl; cout << "=====================================" << endl; cout << "Add - add a programmer/computer scientist" << endl; cout << "Remove - remove a programmer/computer scientist" << endl; cout << "List - show a list of all programmer's/computer scientist's" << endl; cout << "Search - search the list of programmer's/computer scientist's" << endl; cout << "Sort - sort list by name, gender, age or year of death" << endl; cout << "Quit - end program" << endl; cin >> command; for(unsigned int i = 0; i < command.length(); i++) // to make all lowercase, taken from c++ site { command[i] = tolower(command[i]); } if(command == "add") { userMenuAdd(); } else if(command == "remove") { userMenuRemove(); } else if(command == "list") { userMenuList(); } else if(command == "search") { userMenuSearch(); } else if(command == "sort") { userMenuSort(); } else if(command == "quit") { break; } else { cout << "Invalid input" << endl; } } } void ConsoleUI::userMenuAdd() { string name; char gender; int birthYear; int deathYear = 0; int age = 0; int a; while(true) { cout << "Enter the programmer's/computer scientist's name: "; cin.ignore(); getline(cin, name); // Check for gender while(true) { cout << "Enter the programmer's/computer scientist's gender (m/f): "; cin >> gender; if((gender != 'm') && (gender != 'f')) { cout << "Invalid input" << endl; } else { break; } } // Check year of birth while(true) { cout << "Enter the programmer's/computer scientist's year of birth: "; cin >> birthYear; if(birthYear < 2016) // Just in case we find a programmer of the univers { break; } else { cout << "Invalid input" << endl; } } // Check when year of death (if dead) while(true) { cout << "Enter the programmer's/computer scientist's year of death (type 0 if not applicable): "; cin >> deathYear; if (deathYear == 0) { break; } else if(deathYear >= birthYear) { break; } else { cout << "Invalid input" << endl; } } // Check if input is correct cout << "Name: " << name << endl << "Gender: " << gender << endl << "Born: " << birthYear << endl; if(deathYear != 0) { cout << "Died: " << deathYear << endl; } else { cout << endl; } a = userCheckInput(); if (a == 0) { _service.addScientist(name, gender, birthYear, deathYear, age); break; } else if (a == 2) { break; } } cout << endl; } void ConsoleUI::userMenuList() { vector<Scientist> scientist = _service.getScientists(); userMenuPrint(scientist); } void ConsoleUI::userMenuSearch() { string command; cout << "Select a search option: " << endl; cout << "Name - Search by name" << endl; cout << "Gender - Search by gender" << endl; cout << "Age - Search by age" << endl; cout << "Birth - search by year of birth" << endl; cout << "Death - search by year of death" << endl; cin >> command; cout << endl; for(unsigned int i = 0; i < command.length(); i++) // to make all lowercase, taken from c++ site { command[i] = tolower(command[i]); } if(command == "name") { string userInputName; cout << "Search by name: "; cin.ignore(); getline(cin, userInputName); vector<Scientist> scientist = _service.findScientistByName(userInputName); userMenuPrint(scientist); } else if(command == "gender") // findScientistByGender { char userInputGender; cout << "Search by gender: "; cin >> userInputGender; vector<Scientist> scientist = _service.findScientistByGender(userInputGender); userMenuPrint(scientist); } else if(command == "age") // findScientistByGender { int userInputAge; cout << "Search by age: "; cin >> userInputAge; vector<Scientist> scientist = _service.findScientistByAge(userInputAge); userMenuPrint(scientist); } else if(command == "birth") { int userInputBirth; cout << "Search by year of birth: "; cin >> userInputBirth; vector<Scientist> scientist = _service.findScientistByBirth(userInputBirth); userMenuPrint(scientist); } else if(command == "death") { int userInputDeath; cout << "Search by year of death (0 for still alive): "; cin >> userInputDeath; vector<Scientist> scientist = _service.findScientistByDeath(userInputDeath); userMenuPrint(scientist); } cout << endl; } void ConsoleUI::userMenuSort() { int userInput; cout << "Sort list by Name A-Z(1), Name Z-A(2), Gender(3), Year of Birth(4), Year of Death(5) or Age (6)" << endl; cin >> userInput; _service.scientistSort(userInput); userMenuList(); } void ConsoleUI::userMenuPrint(vector<Scientist>scientist) { cout << string( 100, '\n' ); cout << "Scientist name: gender: born: died: age: " << endl; cout << "====================================================" << endl; for (size_t i = 0; i< scientist.size(); ++i) { cout << scientist[i].getName() << "\t" << scientist[i].getGender() << "\t" << scientist[i].getBirth() << "\t"; if(scientist[i].getDeath() == 0) { cout << "-" << "\t"; } else { cout << scientist[i].getDeath() << "\t"; } cout << scientist[i].getAge() << endl; } cout << endl; } int ConsoleUI::userCheckInput() { // Check if all data is correct while(true) { char answear; cout << "Is this data correct? (input y/n) or press q to quit" << endl; cin >> answear; if(answear == 'y') { return 0; } else if (answear == 'n') { return 1; } else if (answear == 'q') { return 2; } else { cout << "Invalid input!"; } } } void ConsoleUI::userMenuRemove() { string userInputName; cout << "Remove a programmer/computer scientist: "; cin.ignore(); getline(cin, userInputName); _service.removeScientist(userInputName); } <|endoftext|>
<commit_before>// ----------------------------------------------------------------- // libpion: a C++ framework for building lightweight HTTP interfaces // ----------------------------------------------------------------- // Copyright (C) 2007 Atomic Labs, Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // #include <libpion/HTTPServer.hpp> #include <libpion/HTTPRequest.hpp> #include <libpion/HTTPResponse.hpp> #include <libpion/HTTPRequestParser.hpp> #include <boost/bind.hpp> #include <boost/asio.hpp> namespace pion { // begin namespace pion // HTTPServer member functions void HTTPServer::handleConnection(TCPConnectionPtr& tcp_conn) { HTTPRequestParserPtr request_parser(HTTPRequestParser::create(boost::bind(&HTTPServer::handleRequest, this, _1, _2), tcp_conn)); request_parser->readRequest(); } void HTTPServer::handleRequest(HTTPRequestPtr& http_request, TCPConnectionPtr& tcp_conn) { if (! http_request->isValid()) { // the request is invalid or an error occured LOG4CXX_INFO(m_logger, "Received an invalid HTTP request"); tcp_conn->setKeepAlive(false); if (! m_bad_request_module->handleRequest(http_request, tcp_conn)) { // this shouldn't ever happen, but just in case tcp_conn->finish(); } return; } LOG4CXX_DEBUG(m_logger, "Received a valid HTTP request"); // set the connection's keep_alive flag tcp_conn->setKeepAlive(http_request->checkKeepAlive()); // strip off trailing slash if the request has one std::string resource(http_request->getResource()); if (! resource.empty() && resource[resource.size() - 1] == '/') resource.resize( resource.size() - 1 ); // true if a module successfully handled the request bool request_was_handled = false; if (m_modules.empty()) { // no modules configured LOG4CXX_WARN(m_logger, "No modules configured"); } else { // lock mutex for thread safety (this should probably use ref counters) boost::mutex::scoped_lock modules_lock(m_mutex); // iterate through each module that may be able to handle the request ModuleMap::iterator i = m_modules.upper_bound(resource); while (i != m_modules.begin()) { --i; // keep checking while the first part of the strings match if (i->second->checkResource(resource)) { // try to handle the request with the module request_was_handled = i->second->handleRequest(http_request, tcp_conn); if (request_was_handled) { // the module successfully handled the request LOG4CXX_DEBUG(m_logger, "HTTP request handled by module: " << i->second->getResource()); break; } } else { // we've gone to far; the first part no longer matches break; } } } if (! request_was_handled) { // no modules found that could handle the request LOG4CXX_INFO(m_logger, "No modules found to handle HTTP request: " << resource); if (! m_not_found_module->handleRequest(http_request, tcp_conn)) { // this shouldn't ever happen, but just in case tcp_conn->finish(); } } } void HTTPServer::addModule(HTTPModulePtr m) { boost::mutex::scoped_lock modules_lock(m_mutex); m_modules.insert(std::make_pair(m->getResource(), m)); } void HTTPServer::clearModules(void) { boost::mutex::scoped_lock modules_lock(m_mutex); m_modules.clear(); } // static members of HTTPServer::BadRequestModule const std::string HTTPServer::BadRequestModule::BAD_REQUEST_HTML = "<html><body>The request is <em>invalid</em></body></html>\r\n\r\n"; // HTTPServer::BadRequestModule member functions bool HTTPServer::BadRequestModule::handleRequest(HTTPRequestPtr& request, TCPConnectionPtr& tcp_conn) { HTTPResponsePtr response(HTTPResponse::create()); response->setResponseCode(HTTPTypes::RESPONSE_CODE_BAD_REQUEST); response->setResponseMessage(HTTPTypes::RESPONSE_MESSAGE_BAD_REQUEST); response->writeNoCopy(BAD_REQUEST_HTML); response->send(tcp_conn); return true; } // static members of HTTPServer::NotFoundModule const std::string HTTPServer::NotFoundModule::NOT_FOUND_HTML = "<html><body>Request Not Found</body></html>\r\n\r\n"; // HTTPServer::BadRequestModule member functions bool HTTPServer::NotFoundModule::handleRequest(HTTPRequestPtr& request, TCPConnectionPtr& tcp_conn) { HTTPResponsePtr response(HTTPResponse::create()); response->setResponseCode(HTTPTypes::RESPONSE_CODE_NOT_FOUND); response->setResponseMessage(HTTPTypes::RESPONSE_MESSAGE_NOT_FOUND); response->writeNoCopy(NOT_FOUND_HTML); response->send(tcp_conn); return true; } } // end namespace pion <commit_msg>Patched an infinite loop that occurred when a connection was closed while parsing the request<commit_after>// ----------------------------------------------------------------- // libpion: a C++ framework for building lightweight HTTP interfaces // ----------------------------------------------------------------- // Copyright (C) 2007 Atomic Labs, Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // #include <libpion/HTTPServer.hpp> #include <libpion/HTTPRequest.hpp> #include <libpion/HTTPResponse.hpp> #include <libpion/HTTPRequestParser.hpp> #include <boost/bind.hpp> #include <boost/asio.hpp> namespace pion { // begin namespace pion // HTTPServer member functions void HTTPServer::handleConnection(TCPConnectionPtr& tcp_conn) { tcp_conn->setKeepAlive(false); // default to closing the connection HTTPRequestParserPtr request_parser(HTTPRequestParser::create(boost::bind(&HTTPServer::handleRequest, this, _1, _2), tcp_conn)); request_parser->readRequest(); } void HTTPServer::handleRequest(HTTPRequestPtr& http_request, TCPConnectionPtr& tcp_conn) { if (! http_request->isValid()) { // the request is invalid or an error occured LOG4CXX_INFO(m_logger, "Received an invalid HTTP request"); if (! m_bad_request_module->handleRequest(http_request, tcp_conn)) { // this shouldn't ever happen, but just in case tcp_conn->finish(); } return; } LOG4CXX_DEBUG(m_logger, "Received a valid HTTP request"); // set the connection's keep_alive flag tcp_conn->setKeepAlive(http_request->checkKeepAlive()); // strip off trailing slash if the request has one std::string resource(http_request->getResource()); if (! resource.empty() && resource[resource.size() - 1] == '/') resource.resize( resource.size() - 1 ); // true if a module successfully handled the request bool request_was_handled = false; if (m_modules.empty()) { // no modules configured LOG4CXX_WARN(m_logger, "No modules configured"); } else { // lock mutex for thread safety (this should probably use ref counters) boost::mutex::scoped_lock modules_lock(m_mutex); // iterate through each module that may be able to handle the request ModuleMap::iterator i = m_modules.upper_bound(resource); while (i != m_modules.begin()) { --i; // keep checking while the first part of the strings match if (i->second->checkResource(resource)) { // try to handle the request with the module request_was_handled = i->second->handleRequest(http_request, tcp_conn); if (request_was_handled) { // the module successfully handled the request LOG4CXX_DEBUG(m_logger, "HTTP request handled by module: " << i->second->getResource()); break; } } else { // we've gone to far; the first part no longer matches break; } } } if (! request_was_handled) { // no modules found that could handle the request LOG4CXX_INFO(m_logger, "No modules found to handle HTTP request: " << resource); if (! m_not_found_module->handleRequest(http_request, tcp_conn)) { // this shouldn't ever happen, but just in case tcp_conn->finish(); } } } void HTTPServer::addModule(HTTPModulePtr m) { boost::mutex::scoped_lock modules_lock(m_mutex); m_modules.insert(std::make_pair(m->getResource(), m)); } void HTTPServer::clearModules(void) { boost::mutex::scoped_lock modules_lock(m_mutex); m_modules.clear(); } // static members of HTTPServer::BadRequestModule const std::string HTTPServer::BadRequestModule::BAD_REQUEST_HTML = "<html><body>The request is <em>invalid</em></body></html>\r\n\r\n"; // HTTPServer::BadRequestModule member functions bool HTTPServer::BadRequestModule::handleRequest(HTTPRequestPtr& request, TCPConnectionPtr& tcp_conn) { HTTPResponsePtr response(HTTPResponse::create()); response->setResponseCode(HTTPTypes::RESPONSE_CODE_BAD_REQUEST); response->setResponseMessage(HTTPTypes::RESPONSE_MESSAGE_BAD_REQUEST); response->writeNoCopy(BAD_REQUEST_HTML); response->send(tcp_conn); return true; } // static members of HTTPServer::NotFoundModule const std::string HTTPServer::NotFoundModule::NOT_FOUND_HTML = "<html><body>Request Not Found</body></html>\r\n\r\n"; // HTTPServer::BadRequestModule member functions bool HTTPServer::NotFoundModule::handleRequest(HTTPRequestPtr& request, TCPConnectionPtr& tcp_conn) { HTTPResponsePtr response(HTTPResponse::create()); response->setResponseCode(HTTPTypes::RESPONSE_CODE_NOT_FOUND); response->setResponseMessage(HTTPTypes::RESPONSE_MESSAGE_NOT_FOUND); response->writeNoCopy(NOT_FOUND_HTML); response->send(tcp_conn); return true; } } // end namespace pion <|endoftext|>
<commit_before>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2004-2007 Torsten Rahn <[email protected]>" // Copyright 2007 Inge Wallin <[email protected]>" // #include "MarbleDirs.h" #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtGui/QApplication> #ifdef Q_OS_MACX //for getting app bundle path #include <ApplicationServices/ApplicationServices.h> #endif #ifdef Q_OS_WIN //for getting appdata path #define _WIN32_IE 0x0400 #include <shlobj.h> #endif #include <config-marble.h> namespace { QString runTimeMarbleDataPath = ""; QString runTimeMarblePluginPath = ""; } MarbleDirs::MarbleDirs() : d( 0 ) { } QString MarbleDirs::path( const QString& relativePath ) { QString localpath = localPath() + '/' + relativePath; // local path QString systempath = systemPath() + '/' + relativePath; // system path QString fullpath = systempath; if ( QFile::exists( localpath ) ) { fullpath = localpath; } return QDir( fullpath ).canonicalPath(); } QString MarbleDirs::pluginPath( const QString& relativePath ) { QString localpath = pluginLocalPath() + QDir::separator() + relativePath; // local path QString systempath = pluginSystemPath() + QDir::separator() + relativePath; // system path QString fullpath = systempath; if ( QFile::exists( localpath ) ) { fullpath = localpath; } return QDir( fullpath ).canonicalPath(); } QStringList MarbleDirs::entryList( const QString& relativePath, QDir::Filters filters ) { QStringList filesLocal = QDir( MarbleDirs::localPath() + '/' + relativePath ).entryList(filters); QStringList filesSystem = QDir( MarbleDirs::systemPath() + '/' + relativePath ).entryList(filters); QStringList allFiles( filesLocal ); allFiles << filesSystem; // remove duplicate entries allFiles.sort(); for ( int i = 1; i < allFiles.size(); ++i ) { if ( allFiles.at(i) == allFiles.at( i - 1 ) ) { allFiles.removeAt(i); --i; } } for (int i = 0; i < allFiles.size(); ++i) qDebug() << "Files: " << allFiles.at(i); return allFiles; } QStringList MarbleDirs::pluginEntryList( const QString& relativePath, QDir::Filters filters ) { QStringList filesLocal = QDir( MarbleDirs::pluginLocalPath() + '/' + relativePath ).entryList(filters); QStringList filesSystem = QDir( MarbleDirs::pluginSystemPath() + '/' + relativePath ).entryList(filters); QStringList allFiles( filesLocal ); allFiles << filesSystem; // remove duplicate entries allFiles.sort(); for ( int i = 1; i < allFiles.size(); ++i ) { if ( allFiles.at(i) == allFiles.at( i - 1 ) ) { allFiles.removeAt(i); --i; } } for (int i = 0; i < allFiles.size(); ++i) qDebug() << "Files: " << allFiles.at(i); return allFiles; } QString MarbleDirs::systemPath() { QString systempath; #ifdef Q_OS_MACX // // On OSX lets try to find any file first in the bundle // before branching out to home and sys dirs // CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle); const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding()); CFRelease(myBundleRef); CFRelease(myMacPath); QString myPath(mypPathPtr); //do some magick so that we can still find data dir if //marble was not built as a bundle if (myPath.contains(".app")) //its a bundle! { systempath = myPath + "/Contents/Resources/data"; } if ( QFile::exists( systempath ) ){ return systempath; } #endif // mac bundle // Should this happen before the Mac bundle already? if ( !runTimeMarbleDataPath.isEmpty() ) return runTimeMarbleDataPath; #ifdef MARBLE_DATA_PATH //MARBLE_DATA_PATH is a compiler define set by cmake QString compileTimeMarbleDataPath(MARBLE_DATA_PATH); if(QDir(compileTimeMarbleDataPath).exists()) return compileTimeMarbleDataPath; #endif // MARBLE_DATA_PATH return QDir( QCoreApplication::applicationDirPath() #if defined(QTONLY) + QLatin1String( "/data" ) #else + QLatin1String( "/../share/apps/marble/data" ) #endif ).canonicalPath(); } QString MarbleDirs::pluginSystemPath() { QString systempath; #ifdef Q_OS_MACX // // On OSX lets try to find any file first in the bundle // before branching out to home and sys dirs // CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle); const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding()); CFRelease(myBundleRef); CFRelease(myMacPath); QString myPath(mypPathPtr); //do some magick so that we can still find data dir if //marble was not built as a bundle if (myPath.contains(".app")) //its a bundle! { systempath = myPath + "/Contents/Resources/plugins"; } if ( QFile::exists( systempath ) ){ return systempath; } #endif // mac bundle // Should this happen before the Mac bundle already? if ( !runTimeMarblePluginPath.isEmpty() ) return runTimeMarblePluginPath; #ifdef MARBLE_PLUGIN_PATH //MARBLE_PLUGIN_PATH is a compiler define set by cmake QString compileTimeMarblePluginPath(MARBLE_PLUGIN_PATH); if(QDir(compileTimeMarblePluginPath).exists()) return compileTimeMarblePluginPath; #endif // MARBLE_PLUGIN_PATH return QDir( QCoreApplication::applicationDirPath() #if defined(QTONLY) + QLatin1String( "/plugins" ) #else + QLatin1String( "/../lib/kde4/plugins/marble" ) #endif ).canonicalPath(); } QString MarbleDirs::localPath() { #ifndef Q_OS_WIN return QString( QDir::homePath() + "/.marble/data" ); // local path #else HWND hwnd = 0; WCHAR *appdata_path = new WCHAR[MAX_PATH+1]; SHGetSpecialFolderPathW( hwnd, appdata_path, CSIDL_APPDATA, 0 ); QString appdata = QString::fromUtf16( reinterpret_cast<ushort*>( appdata_path ) ); delete appdata_path; return QString( QDir::fromNativeSeparators( appdata ) + "/.marble/data" ); // local path #endif } QString MarbleDirs::pluginLocalPath() { #ifndef Q_OS_WIN return QString( QDir::homePath() + "/.marble/plugins" ); // local path #else HWND hwnd = 0; WCHAR *appdata_path = new WCHAR[MAX_PATH]; SHGetSpecialFolderPathW( hwnd, appdata_path, CSIDL_APPDATA, 0 ); QString appdata = QString::fromUtf16( reinterpret_cast<ushort*>( appdata_path ) ); delete appdata_path; return QString( QDir::fromNativeSeparators( appdata ) + "/.marble/plugins" ); // local path #endif } QString MarbleDirs::marbleDataPath() { return runTimeMarbleDataPath; } QString MarbleDirs::marblePluginPath() { return runTimeMarbleDataPath; } void MarbleDirs::setMarbleDataPath( const QString& adaptedPath ) { if ( !QDir::root().exists( adaptedPath ) ) { qDebug( "WARNING: Invalid MarbleDataPath %s. Using builtin path instead.", qPrintable( adaptedPath ) ); return; } runTimeMarbleDataPath = adaptedPath; } void MarbleDirs::setMarblePluginPath( const QString& adaptedPath ) { if ( !QDir::root().exists( adaptedPath ) ) { qDebug( "WARNING: Invalid MarblePluginPath %s. Using builtin path instead.", qPrintable( adaptedPath ) ); return; } runTimeMarblePluginPath = adaptedPath; } void MarbleDirs::debug() { qDebug() << "=== MarbleDirs: ==="; qDebug() << "Local Path:" << localPath(); qDebug() << "Plugin Local Path:" << pluginLocalPath(); qDebug() << ""; qDebug() << "Marble Data Path (Run Time) :" << runTimeMarbleDataPath; qDebug() << "Marble Data Path (Compile Time):" << QString(MARBLE_DATA_PATH); qDebug() << ""; qDebug() << "Marble Plugin Path (Run Time) :" << runTimeMarblePluginPath; qDebug() << "Marble Plugin Path (Compile Time):" << QString(MARBLE_PLUGIN_PATH); qDebug() << ""; qDebug() << "System Path:" << systemPath(); qDebug() << "Plugin System Path:" << pluginSystemPath(); qDebug() << "==================="; } <commit_msg>occurs twice<commit_after>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2004-2007 Torsten Rahn <[email protected]>" // Copyright 2007 Inge Wallin <[email protected]>" // #include "MarbleDirs.h" #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtGui/QApplication> #ifdef Q_OS_MACX //for getting app bundle path #include <ApplicationServices/ApplicationServices.h> #endif #ifdef Q_OS_WIN //for getting appdata path #define _WIN32_IE 0x0400 #include <shlobj.h> #endif #include <config-marble.h> namespace { QString runTimeMarbleDataPath = ""; QString runTimeMarblePluginPath = ""; } MarbleDirs::MarbleDirs() : d( 0 ) { } QString MarbleDirs::path( const QString& relativePath ) { QString localpath = localPath() + '/' + relativePath; // local path QString systempath = systemPath() + '/' + relativePath; // system path QString fullpath = systempath; if ( QFile::exists( localpath ) ) { fullpath = localpath; } return QDir( fullpath ).canonicalPath(); } QString MarbleDirs::pluginPath( const QString& relativePath ) { QString localpath = pluginLocalPath() + QDir::separator() + relativePath; // local path QString systempath = pluginSystemPath() + QDir::separator() + relativePath; // system path QString fullpath = systempath; if ( QFile::exists( localpath ) ) { fullpath = localpath; } return QDir( fullpath ).canonicalPath(); } QStringList MarbleDirs::entryList( const QString& relativePath, QDir::Filters filters ) { QStringList filesLocal = QDir( MarbleDirs::localPath() + '/' + relativePath ).entryList(filters); QStringList filesSystem = QDir( MarbleDirs::systemPath() + '/' + relativePath ).entryList(filters); QStringList allFiles( filesLocal ); allFiles << filesSystem; // remove duplicate entries allFiles.sort(); for ( int i = 1; i < allFiles.size(); ++i ) { if ( allFiles.at(i) == allFiles.at( i - 1 ) ) { allFiles.removeAt(i); --i; } } for (int i = 0; i < allFiles.size(); ++i) qDebug() << "Files: " << allFiles.at(i); return allFiles; } QStringList MarbleDirs::pluginEntryList( const QString& relativePath, QDir::Filters filters ) { QStringList filesLocal = QDir( MarbleDirs::pluginLocalPath() + '/' + relativePath ).entryList(filters); QStringList filesSystem = QDir( MarbleDirs::pluginSystemPath() + '/' + relativePath ).entryList(filters); QStringList allFiles( filesLocal ); allFiles << filesSystem; // remove duplicate entries allFiles.sort(); for ( int i = 1; i < allFiles.size(); ++i ) { if ( allFiles.at(i) == allFiles.at( i - 1 ) ) { allFiles.removeAt(i); --i; } } for (int i = 0; i < allFiles.size(); ++i) qDebug() << "Files: " << allFiles.at(i); return allFiles; } QString MarbleDirs::systemPath() { QString systempath; #ifdef Q_OS_MACX // // On OSX lets try to find any file first in the bundle // before branching out to home and sys dirs // CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle); const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding()); CFRelease(myBundleRef); CFRelease(myMacPath); QString myPath(mypPathPtr); //do some magick so that we can still find data dir if //marble was not built as a bundle if (myPath.contains(".app")) //its a bundle! { systempath = myPath + "/Contents/Resources/data"; } if ( QFile::exists( systempath ) ){ return systempath; } #endif // mac bundle // Should this happen before the Mac bundle already? if ( !runTimeMarbleDataPath.isEmpty() ) return runTimeMarbleDataPath; #ifdef MARBLE_DATA_PATH //MARBLE_DATA_PATH is a compiler define set by cmake QString compileTimeMarbleDataPath(MARBLE_DATA_PATH); if(QDir(compileTimeMarbleDataPath).exists()) return compileTimeMarbleDataPath; #endif // MARBLE_DATA_PATH return QDir( QCoreApplication::applicationDirPath() #if defined(QTONLY) + QLatin1String( "/data" ) #else + QLatin1String( "/../share/apps/marble/data" ) #endif ).canonicalPath(); } QString MarbleDirs::pluginSystemPath() { QString systempath; #ifdef Q_OS_MACX // // On OSX lets try to find any file first in the bundle // before branching out to home and sys dirs // CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle); const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding()); CFRelease(myBundleRef); CFRelease(myMacPath); QString myPath(mypPathPtr); //do some magick so that we can still find data dir if //marble was not built as a bundle if (myPath.contains(".app")) //its a bundle! { systempath = myPath + "/Contents/Resources/plugins"; } if ( QFile::exists( systempath ) ){ return systempath; } #endif // mac bundle // Should this happen before the Mac bundle already? if ( !runTimeMarblePluginPath.isEmpty() ) return runTimeMarblePluginPath; #ifdef MARBLE_PLUGIN_PATH //MARBLE_PLUGIN_PATH is a compiler define set by cmake QString compileTimeMarblePluginPath(MARBLE_PLUGIN_PATH); if(QDir(compileTimeMarblePluginPath).exists()) return compileTimeMarblePluginPath; #endif // MARBLE_PLUGIN_PATH return QDir( QCoreApplication::applicationDirPath() #if defined(QTONLY) + QLatin1String( "/plugins" ) #else + QLatin1String( "/../lib/kde4/plugins/marble" ) #endif ).canonicalPath(); } QString MarbleDirs::localPath() { #ifndef Q_OS_WIN return QString( QDir::homePath() + "/.marble/data" ); // local path #else HWND hwnd = 0; WCHAR *appdata_path = new WCHAR[MAX_PATH+1]; SHGetSpecialFolderPathW( hwnd, appdata_path, CSIDL_APPDATA, 0 ); QString appdata = QString::fromUtf16( reinterpret_cast<ushort*>( appdata_path ) ); delete appdata_path; return QString( QDir::fromNativeSeparators( appdata ) + "/.marble/data" ); // local path #endif } QString MarbleDirs::pluginLocalPath() { #ifndef Q_OS_WIN return QString( QDir::homePath() + "/.marble/plugins" ); // local path #else HWND hwnd = 0; WCHAR *appdata_path = new WCHAR[MAX_PATH+1]; SHGetSpecialFolderPathW( hwnd, appdata_path, CSIDL_APPDATA, 0 ); QString appdata = QString::fromUtf16( reinterpret_cast<ushort*>( appdata_path ) ); delete appdata_path; return QString( QDir::fromNativeSeparators( appdata ) + "/.marble/plugins" ); // local path #endif } QString MarbleDirs::marbleDataPath() { return runTimeMarbleDataPath; } QString MarbleDirs::marblePluginPath() { return runTimeMarbleDataPath; } void MarbleDirs::setMarbleDataPath( const QString& adaptedPath ) { if ( !QDir::root().exists( adaptedPath ) ) { qDebug( "WARNING: Invalid MarbleDataPath %s. Using builtin path instead.", qPrintable( adaptedPath ) ); return; } runTimeMarbleDataPath = adaptedPath; } void MarbleDirs::setMarblePluginPath( const QString& adaptedPath ) { if ( !QDir::root().exists( adaptedPath ) ) { qDebug( "WARNING: Invalid MarblePluginPath %s. Using builtin path instead.", qPrintable( adaptedPath ) ); return; } runTimeMarblePluginPath = adaptedPath; } void MarbleDirs::debug() { qDebug() << "=== MarbleDirs: ==="; qDebug() << "Local Path:" << localPath(); qDebug() << "Plugin Local Path:" << pluginLocalPath(); qDebug() << ""; qDebug() << "Marble Data Path (Run Time) :" << runTimeMarbleDataPath; qDebug() << "Marble Data Path (Compile Time):" << QString(MARBLE_DATA_PATH); qDebug() << ""; qDebug() << "Marble Plugin Path (Run Time) :" << runTimeMarblePluginPath; qDebug() << "Marble Plugin Path (Compile Time):" << QString(MARBLE_PLUGIN_PATH); qDebug() << ""; qDebug() << "System Path:" << systemPath(); qDebug() << "Plugin System Path:" << pluginSystemPath(); qDebug() << "==================="; } <|endoftext|>
<commit_before>/* libvisio * Copyright (C) 2011 Fridrich Strba <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02111-1301 USA */ #include <libwpd-stream/libwpd-stream.h> #include <libvisio_utils.h> #include "VSDXParser.h" #include "VSDInternalStream.h" #include <locale.h> #include <sstream> #include <string> libvisio::VSDXParser::VSDXParser(WPXInputStream *input) : m_input(input) {} libvisio::VSDXParser::~VSDXParser() {} /************************************************** * Visio 2000 parser implementation **************************************************/ libvisio::VSD6Parser::VSD6Parser(WPXInputStream *input) : VSDXParser(input) {} libvisio::VSD6Parser::~VSD6Parser() {} /** Parses VSD 2000 input stream content, making callbacks to functions provided by WPGPaintInterface class implementation as needed. \param iface A WPGPaintInterface implementation \return A value indicating whether parsing was successful */ bool libvisio::VSD6Parser::parse(libwpg::WPGPaintInterface *iface) { const unsigned int SHIFT = 4; if (!m_input) { return false; } // Seek to trailer stream pointer m_input->seek(0x24, WPX_SEEK_SET); m_input->seek(8, WPX_SEEK_CUR); unsigned int offset = readU32(m_input); unsigned int length = readU32(m_input); unsigned short format = readU16(m_input); bool compressed = ((format & 2) == 2); m_input->seek(offset, WPX_SEEK_SET); VSDInternalStream trailerStream(m_input, length, compressed); // Parse out pointers to other streams from trailer trailerStream.seek(SHIFT, WPX_SEEK_SET); offset = readU32(&trailerStream); trailerStream.seek(offset+SHIFT, WPX_SEEK_SET); unsigned int pointerCount = readU32(&trailerStream); trailerStream.seek(SHIFT, WPX_SEEK_CUR); unsigned int ptrType; unsigned int ptrOffset; unsigned int ptrLength; unsigned int ptrFormat; for (unsigned int i = 0; i < pointerCount; i++) { ptrType = readU32(&trailerStream); trailerStream.seek(4, WPX_SEEK_CUR); // Skip dword ptrOffset = readU32(&trailerStream); ptrLength = readU32(&trailerStream); ptrFormat = readU16(&trailerStream); VSD_DEBUG_MSG(("Found pointer of type %x and format %x\n", ptrType, ptrFormat)); } return true; } /************************************************** * Visio 2003 parser implementation **************************************************/ libvisio::VSD11Parser::VSD11Parser(WPXInputStream *input) : VSDXParser(input) {} libvisio::VSD11Parser::~VSD11Parser() {} /** Parses VSD 2003 input stream content, making callbacks to functions provided by WPGPaintInterface class implementation as needed. \param iface A WPGPaintInterface implementation \return A value indicating whether parsing was successful */ bool libvisio::VSD11Parser::parse(libwpg::WPGPaintInterface *iface) { const unsigned int SHIFT = 4; if (!m_input) { return false; } // Seek to trailer stream pointer m_input->seek(0x24, WPX_SEEK_SET); m_input->seek(8, WPX_SEEK_CUR); unsigned int offset = readU32(m_input); unsigned int length = readU32(m_input); unsigned short format = readU16(m_input); bool compressed = ((format & 2) == 2); m_input->seek(offset, WPX_SEEK_SET); VSDInternalStream trailerStream(m_input, length, compressed); // Parse out pointers to other streams from trailer trailerStream.seek(SHIFT, WPX_SEEK_SET); offset = readU32(&trailerStream); trailerStream.seek(offset+SHIFT, WPX_SEEK_SET); unsigned int pointerCount = readU32(&trailerStream); trailerStream.seek(SHIFT, WPX_SEEK_CUR); unsigned int ptrType; unsigned int ptrOffset; unsigned int ptrLength; unsigned int ptrFormat; for (unsigned int i = 0; i < pointerCount; i++) { ptrType = readU32(&trailerStream); trailerStream.seek(4, WPX_SEEK_CUR); // Skip dword ptrOffset = readU32(&trailerStream); ptrLength = readU32(&trailerStream); ptrFormat = readU16(&trailerStream); VSD_DEBUG_MSG(("Found pointer of type %x and format %x\n", ptrType, ptrFormat)); } return true; } <commit_msg>Started handling of stream types in v11 parser<commit_after>/* libvisio * Copyright (C) 2011 Fridrich Strba <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02111-1301 USA */ #include <libwpd-stream/libwpd-stream.h> #include <libvisio_utils.h> #include "VSDXParser.h" #include "VSDInternalStream.h" #include <locale.h> #include <sstream> #include <string> libvisio::VSDXParser::VSDXParser(WPXInputStream *input) : m_input(input) {} libvisio::VSDXParser::~VSDXParser() {} /************************************************** * Visio 2000 parser implementation **************************************************/ libvisio::VSD6Parser::VSD6Parser(WPXInputStream *input) : VSDXParser(input) {} libvisio::VSD6Parser::~VSD6Parser() {} /** Parses VSD 2000 input stream content, making callbacks to functions provided by WPGPaintInterface class implementation as needed. \param iface A WPGPaintInterface implementation \return A value indicating whether parsing was successful */ bool libvisio::VSD6Parser::parse(libwpg::WPGPaintInterface *iface) { const unsigned int SHIFT = 4; if (!m_input) { return false; } // Seek to trailer stream pointer m_input->seek(0x24, WPX_SEEK_SET); m_input->seek(8, WPX_SEEK_CUR); unsigned int offset = readU32(m_input); unsigned int length = readU32(m_input); unsigned short format = readU16(m_input); bool compressed = ((format & 2) == 2); m_input->seek(offset, WPX_SEEK_SET); VSDInternalStream trailerStream(m_input, length, compressed); // Parse out pointers to other streams from trailer trailerStream.seek(SHIFT, WPX_SEEK_SET); offset = readU32(&trailerStream); trailerStream.seek(offset+SHIFT, WPX_SEEK_SET); unsigned int pointerCount = readU32(&trailerStream); trailerStream.seek(SHIFT, WPX_SEEK_CUR); unsigned int ptrType; unsigned int ptrOffset; unsigned int ptrLength; unsigned int ptrFormat; for (unsigned int i = 0; i < pointerCount; i++) { ptrType = readU32(&trailerStream); trailerStream.seek(4, WPX_SEEK_CUR); // Skip dword ptrOffset = readU32(&trailerStream); ptrLength = readU32(&trailerStream); ptrFormat = readU16(&trailerStream); VSD_DEBUG_MSG(("Found pointer of type %x and format %x\n", ptrType, ptrFormat)); } return true; } /************************************************** * Visio 2003 parser implementation **************************************************/ libvisio::VSD11Parser::VSD11Parser(WPXInputStream *input) : VSDXParser(input) {} libvisio::VSD11Parser::~VSD11Parser() {} /** Parses VSD 2003 input stream content, making callbacks to functions provided by WPGPaintInterface class implementation as needed. \param iface A WPGPaintInterface implementation \return A value indicating whether parsing was successful */ bool libvisio::VSD11Parser::parse(libwpg::WPGPaintInterface *iface) { const unsigned int SHIFT = 4; if (!m_input) { return false; } // Seek to trailer stream pointer m_input->seek(0x24, WPX_SEEK_SET); m_input->seek(8, WPX_SEEK_CUR); unsigned int offset = readU32(m_input); unsigned int length = readU32(m_input); unsigned short format = readU16(m_input); bool compressed = ((format & 2) == 2); m_input->seek(offset, WPX_SEEK_SET); VSDInternalStream trailerStream(m_input, length, compressed); // Parse out pointers to other streams from trailer typedef void (VSD11Parser::*Method)(VSDInternalStream&); struct StreamHandler { unsigned int type; const char *name; Method handler;}; static const struct StreamHandler handlers[] = { {0xa, "Name", 0}, {0xb, "Name Idx", 0}, {0x14, "Trailer, 0"}, {0x15, "Page", 0}, {0x16, "Colors"}, {0x17, "??? seems to have no data", 0}, {0x18, "FontFaces (ver.11)", 0}, {0x1a, "Styles", 0}, {0x1b, "??? saw 'Acrobat PDFWriter' string here", 0}, {0x1c, "??? saw 'winspool.Acrobat PDFWriter.LPT1' string here", 0}, {0x1d, "Stencils"}, {0x1e, "Stencil Page (collection of Shapes, one collection per each stencil item)", 0}, {0x20, "??? seems to have no data", 0}, {0x21, "??? seems to have no data", 0}, {0x23, "Icon (for stencil only?)", 0}, {0x24, "??? seems to have no data", 0}, {0x26, "??? some fractions, maybe PrintProps", 0}, {0x27, "Pages", 0}, {0x29, "Collection of Type 2a streams", 0}, {0x2a, "???", 0}, {0x31, "Document", 0}, {0x32, "NameList", 0}, {0x33, "Name", 0}, {0x3d, "??? found in VSS, seems to have no data", 0}, {0x3f, "List of name indexes collections", 0}, {0x40, "Name Idx + ?? group (contains 0xb type streams)", 0}, {0x44, "??? Collection of Type 0x45 streams", 0}, {0x45, "??? match number of Pages or Stencil Pages in Pages/Stencils", 0}, {0xc9, "some collection of 13 bytes structures related to 3f/40 streams", 0}, {0xd7, "FontFace (ver.11)", 0}, {0xd8, "FontFaces (ver.6)", 0} }; trailerStream.seek(SHIFT, WPX_SEEK_SET); offset = readU32(&trailerStream); trailerStream.seek(offset+SHIFT, WPX_SEEK_SET); unsigned int pointerCount = readU32(&trailerStream); trailerStream.seek(SHIFT, WPX_SEEK_CUR); unsigned int ptrType; unsigned int ptrOffset; unsigned int ptrLength; unsigned int ptrFormat; for (unsigned int i = 0; i < pointerCount; i++) { ptrType = readU32(&trailerStream); trailerStream.seek(4, WPX_SEEK_CUR); // Skip dword ptrOffset = readU32(&trailerStream); ptrLength = readU32(&trailerStream); ptrFormat = readU16(&trailerStream); compressed = ((format & 2) == 2); m_input->seek(ptrOffset, WPX_SEEK_SET); VSDInternalStream stream(m_input, ptrLength, compressed); int index = -1; for (int i = 0; (index < 0) && handlers[i].name; i++) { if (handlers[i].type == ptrType) index = i; } if (index < 0) { VSD_DEBUG_MSG(("Unknown stream pointer type 0x%02x found in trailer at %li\n", ptrType, trailerStream.tell() - 18)); } else { Method streamHandler = handlers[index].handler; if (!streamHandler) VSD_DEBUG_MSG(("Stream '%s', type 0x%02x, format 0x%02x at %li ignored\n", handlers[index].name, handlers[index].type, ptrFormat, trailerStream.tell() - 18)); else { VSD_DEBUG_MSG(("Stream '%s', type 0x%02x, format 0x%02x at %li handled\n", handlers[index].name, handlers[index].type, ptrFormat, trailerStream.tell() - 18)); (this->*streamHandler)(stream); } } } return true; } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 Marc Boris Duerner, Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #if defined(HAVE_ACCEPT4) || defined(HAVE_SO_NOSIGPIPE) || defined(MSG_NOSIGNAL) #include <sys/types.h> #include <sys/socket.h> #endif #if !defined(MSG_MSG_NOSIGNAL) #include <signal.h> #endif #include "tcpsocketimpl.h" #include "tcpserverimpl.h" #include "cxxtools/net/tcpserver.h" #include "cxxtools/net/tcpsocket.h" #include "cxxtools/systemerror.h" #include "cxxtools/ioerror.h" #include "cxxtools/log.h" #include "config.h" #include "error.h" #include <cerrno> #include <cstring> #include <cassert> #include <fcntl.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sstream> log_define("cxxtools.net.tcpsocket.impl") namespace cxxtools { namespace net { namespace { std::string connectFailedMessage(const AddrInfo& ai, int err) { std::ostringstream msg; msg << "failed to connect to host \"" << ai.host() << "\" port " << ai.port() << ": " << getErrnoString(err); return msg.str(); } } void formatIp(const Sockaddr& sa, std::string& str) { #ifdef HAVE_INET_NTOP #ifdef HAVE_IPV6 char strbuf[INET6_ADDRSTRLEN + 1]; #else char strbuf[INET_ADDRSTRLEN + 1]; #endif const char* p = 0; switch(sa.sa_in.sin_family) { case AF_INET: p = inet_ntop(AF_INET, &sa.sa_in.sin_addr, strbuf, sizeof(strbuf)); break; #ifdef HAVE_IPV6 case AF_INET6: p = inet_ntop(AF_INET6, &sa.sa_in6.sin6_addr, strbuf, sizeof(strbuf)); break; #endif } str = (p == 0 ? "-" : strbuf); #else static cxxtools::Mutex monitor; cxxtools::MutexLock lock(monitor); const char* p = inet_ntoa(sa.sa_in.sin_addr); if (p) str = p; else str.clear(); #endif } std::string getSockAddr(int fd) { Sockaddr addr; socklen_t slen = sizeof(addr); if (::getsockname(fd, &addr.sa, &slen) < 0) throw SystemError("getsockname"); std::string ret; formatIp(addr, ret); return ret; } TcpSocketImpl::TcpSocketImpl(TcpSocket& socket) : IODeviceImpl(socket) , _socket(socket) , _isConnected(false) { } TcpSocketImpl::~TcpSocketImpl() { assert(_pfd == 0); } void TcpSocketImpl::close() { log_debug("close socket " << _fd); IODeviceImpl::close(); _isConnected = false; } std::string TcpSocketImpl::getSockAddr() const { return net::getSockAddr(fd()); } std::string TcpSocketImpl::getPeerAddr() const { Sockaddr addr; addr.storage = _peeraddr; std::string ret; formatIp(addr, ret); return ret; } void TcpSocketImpl::connect(const AddrInfo& addrInfo) { log_debug("connect"); this->beginConnect(addrInfo); this->endConnect(); } int TcpSocketImpl::checkConnect() { log_trace("checkConnect"); int sockerr; socklen_t optlen = sizeof(sockerr); // check for socket error if( ::getsockopt(this->fd(), SOL_SOCKET, SO_ERROR, &sockerr, &optlen) != 0 ) { // getsockopt failed int e = errno; close(); throw SystemError(e, "getsockopt"); } if (sockerr == 0) { log_debug("connected successfully to " << getPeerAddr()); _isConnected = true; } return sockerr; } void TcpSocketImpl::checkPendingError() { if (!_connectResult.empty()) { std::string p = _connectResult; _connectResult.clear(); throw IOError(p); } } std::string TcpSocketImpl::tryConnect() { log_trace("tryConnect"); assert(_fd == -1); if (_addrInfoPtr == _addrInfo.impl()->end()) { log_debug("no more address informations"); std::ostringstream msg; msg << "invalid address information; host \"" << _addrInfo.host() << "\" port " << _addrInfo.port(); return msg.str(); } while (true) { int fd; while (true) { log_debug("create socket"); fd = ::socket(_addrInfoPtr->ai_family, SOCK_STREAM, 0); if (fd >= 0) break; if (++_addrInfoPtr == _addrInfo.impl()->end()) { std::ostringstream msg; msg << "failed to create socket for host \"" << _addrInfo.host() << "\" port " << _addrInfo.port() << ": " << getErrnoString(); return msg.str(); } } #ifdef HAVE_SO_NOSIGPIPE static const int on = 1; if (::setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on)) < 0) throw cxxtools::SystemError("setsockopt(SO_NOSIGPIPE)"); #endif IODeviceImpl::open(fd, true, false); std::memmove(&_peeraddr, _addrInfoPtr->ai_addr, _addrInfoPtr->ai_addrlen); log_debug("created socket " << _fd << " max: " << FD_SETSIZE); if( ::connect(this->fd(), _addrInfoPtr->ai_addr, _addrInfoPtr->ai_addrlen) == 0 ) { _isConnected = true; log_debug("connected successfully to " << getPeerAddr()); break; } if (errno == EINPROGRESS) { log_debug("connect in progress"); break; } close(); if (++_addrInfoPtr == _addrInfo.impl()->end()) return connectFailedMessage(_addrInfo, errno); } return std::string(); } bool TcpSocketImpl::beginConnect(const AddrInfo& addrInfo) { log_trace("begin connect"); assert(!_isConnected); _addrInfo = addrInfo; _addrInfoPtr = _addrInfo.impl()->begin(); _connectResult = tryConnect(); checkPendingError(); return _isConnected; } void TcpSocketImpl::endConnect() { log_trace("ending connect"); if(_pfd && ! _socket.wbuf()) { _pfd->events &= ~POLLOUT; } checkPendingError(); if( _isConnected ) return; try { while (true) { pollfd pfd; pfd.fd = this->fd(); pfd.revents = 0; pfd.events = POLLOUT; log_debug("wait " << timeout() << " ms"); bool avail = this->wait(this->timeout(), pfd); if (avail) { // something has happened int sockerr = checkConnect(); if (_isConnected) return; if (++_addrInfoPtr == _addrInfo.impl()->end()) { // no more addrInfo - propagate error throw IOError(connectFailedMessage(_addrInfo, sockerr)); } } else if (++_addrInfoPtr == _addrInfo.impl()->end()) { log_debug("timeout"); throw IOTimeout(); } close(); _connectResult = tryConnect(); if (_isConnected) return; checkPendingError(); } } catch(...) { close(); throw; } } void TcpSocketImpl::accept(const TcpServer& server, unsigned flags) { socklen_t peeraddr_len = sizeof(_peeraddr); _fd = server.impl().accept(flags, reinterpret_cast <struct sockaddr*>(&_peeraddr), peeraddr_len); if( _fd < 0 ) throw SystemError("accept"); #ifdef HAVE_ACCEPT4 IODeviceImpl::open(_fd, false, false); #else bool inherit = (flags & TcpSocket::INHERIT) != 0; IODeviceImpl::open(_fd, true, inherit); #endif //TODO ECONNABORTED EINTR EPERM _isConnected = true; log_debug( "accepted from " << getPeerAddr()); } void TcpSocketImpl::initWait(pollfd& pfd) { IODeviceImpl::initWait(pfd); if( ! _isConnected ) { log_debug("not connected, setting POLLOUT "); pfd.events = POLLOUT; } } bool TcpSocketImpl::checkPollEvent(pollfd& pfd) { log_debug("checkPollEvent " << pfd.revents); if( _isConnected ) { // check for error while neither reading nor writing // // if reading or writing, IODeviceImpl::checkPollEvent will emit // inputReady or outputReady signal and the user gets an exception in // endRead or endWrite. if ( !_device.reading() && !_device.writing() && (pfd.revents & POLLERR) ) { _device.close(); _socket.closed(_socket); return true; } return IODeviceImpl::checkPollEvent(pfd); } if ( pfd.revents & POLLERR ) { AddrInfoImpl::const_iterator ptr = _addrInfoPtr; if (++ptr == _addrInfo.impl()->end()) { // not really connected but error // end of addrinfo list means that no working addrinfo was found log_debug("no more addrinfos found"); _socket.connected(_socket); return true; } else { _addrInfoPtr = ptr; close(); _connectResult = tryConnect(); if (_isConnected || !_connectResult.empty()) { // immediate success or error log_debug("connected successfully"); _socket.connected(_socket); } else { // by closing the previous file handle _pfd is set to 0. // creating a new socket in tryConnect may also change the value of fd. initializePoll(&pfd, 1); } return true; } } else if( pfd.revents & POLLOUT ) { int sockerr = checkConnect(); if (_isConnected) { _socket.connected(_socket); return true; } // something went wrong - look for next addrInfo log_debug("sockerr is " << sockerr << " try next"); if (++_addrInfoPtr == _addrInfo.impl()->end()) { // no more addrInfo - propagate error _connectResult = connectFailedMessage(_addrInfo, sockerr); _socket.connected(_socket); return true; } _connectResult = tryConnect(); if (_isConnected) { _socket.connected(_socket); return true; } } return false; } size_t TcpSocketImpl::beginWrite(const char* buffer, size_t n) { log_debug("::send(" << _fd << ", buffer, " << n << ')'); #if defined(HAVE_MSG_NOSIGNAL) ssize_t ret = ::send(_fd, (const void*)buffer, n, MSG_NOSIGNAL); #elif defined(HAVE_SO_NOSIGPIPE) ssize_t ret = ::send(_fd, (const void*)buffer, n, 0); #else // block SIGPIPE sigset_t sigpipeMask, oldSigmask; sigemptyset(&sigpipeMask); sigaddset(&sigpipeMask, SIGPIPE); pthread_sigmask(SIG_BLOCK, &sigpipeMask, &oldSigmask); // execute send ssize_t ret = ::send(_fd, (const void*)buffer, n, 0); // clear possible SIGPIPE sigset_t pending; sigemptyset(&pending); sigpending(&pending); if (sigismember(&pending, SIGPIPE)) { static const struct timespec nowait = { 0, 0 }; while (sigtimedwait(&sigpipeMask, 0, &nowait) == -1 && errno == EINTR) ; } // unblock SIGPIPE pthread_sigmask(SIG_SETMASK, &oldSigmask, 0); #endif log_debug("send returned " << ret); if (ret > 0) return static_cast<size_t>(ret); if (ret == 0 || errno == ECONNRESET || errno == EPIPE) throw IOError("lost connection to peer"); if(_pfd) { _pfd->events |= POLLOUT; } return 0; } } // namespace net } // namespace cxxtools <commit_msg>add missing include for os without inet_ntop like haiku<commit_after>/* * Copyright (C) 2009 Marc Boris Duerner, Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #if defined(HAVE_ACCEPT4) || defined(HAVE_SO_NOSIGPIPE) || defined(MSG_NOSIGNAL) #include <sys/types.h> #include <sys/socket.h> #endif #if !defined(MSG_MSG_NOSIGNAL) #include <signal.h> #endif #include "tcpsocketimpl.h" #include "tcpserverimpl.h" #include "cxxtools/net/tcpserver.h" #include "cxxtools/net/tcpsocket.h" #include "cxxtools/systemerror.h" #include "cxxtools/ioerror.h" #include "cxxtools/log.h" #include "config.h" #include "error.h" #include <cerrno> #include <cstring> #include <cassert> #include <fcntl.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sstream> #ifndef HAVE_INET_NTOP #include "cxxtools/mutex.h" #endif log_define("cxxtools.net.tcpsocket.impl") namespace cxxtools { namespace net { namespace { std::string connectFailedMessage(const AddrInfo& ai, int err) { std::ostringstream msg; msg << "failed to connect to host \"" << ai.host() << "\" port " << ai.port() << ": " << getErrnoString(err); return msg.str(); } } void formatIp(const Sockaddr& sa, std::string& str) { #ifdef HAVE_INET_NTOP #ifdef HAVE_IPV6 char strbuf[INET6_ADDRSTRLEN + 1]; #else char strbuf[INET_ADDRSTRLEN + 1]; #endif const char* p = 0; switch(sa.sa_in.sin_family) { case AF_INET: p = inet_ntop(AF_INET, &sa.sa_in.sin_addr, strbuf, sizeof(strbuf)); break; #ifdef HAVE_IPV6 case AF_INET6: p = inet_ntop(AF_INET6, &sa.sa_in6.sin6_addr, strbuf, sizeof(strbuf)); break; #endif } str = (p == 0 ? "-" : strbuf); #else static cxxtools::Mutex monitor; cxxtools::MutexLock lock(monitor); const char* p = inet_ntoa(sa.sa_in.sin_addr); if (p) str = p; else str.clear(); #endif } std::string getSockAddr(int fd) { Sockaddr addr; socklen_t slen = sizeof(addr); if (::getsockname(fd, &addr.sa, &slen) < 0) throw SystemError("getsockname"); std::string ret; formatIp(addr, ret); return ret; } TcpSocketImpl::TcpSocketImpl(TcpSocket& socket) : IODeviceImpl(socket) , _socket(socket) , _isConnected(false) { } TcpSocketImpl::~TcpSocketImpl() { assert(_pfd == 0); } void TcpSocketImpl::close() { log_debug("close socket " << _fd); IODeviceImpl::close(); _isConnected = false; } std::string TcpSocketImpl::getSockAddr() const { return net::getSockAddr(fd()); } std::string TcpSocketImpl::getPeerAddr() const { Sockaddr addr; addr.storage = _peeraddr; std::string ret; formatIp(addr, ret); return ret; } void TcpSocketImpl::connect(const AddrInfo& addrInfo) { log_debug("connect"); this->beginConnect(addrInfo); this->endConnect(); } int TcpSocketImpl::checkConnect() { log_trace("checkConnect"); int sockerr; socklen_t optlen = sizeof(sockerr); // check for socket error if( ::getsockopt(this->fd(), SOL_SOCKET, SO_ERROR, &sockerr, &optlen) != 0 ) { // getsockopt failed int e = errno; close(); throw SystemError(e, "getsockopt"); } if (sockerr == 0) { log_debug("connected successfully to " << getPeerAddr()); _isConnected = true; } return sockerr; } void TcpSocketImpl::checkPendingError() { if (!_connectResult.empty()) { std::string p = _connectResult; _connectResult.clear(); throw IOError(p); } } std::string TcpSocketImpl::tryConnect() { log_trace("tryConnect"); assert(_fd == -1); if (_addrInfoPtr == _addrInfo.impl()->end()) { log_debug("no more address informations"); std::ostringstream msg; msg << "invalid address information; host \"" << _addrInfo.host() << "\" port " << _addrInfo.port(); return msg.str(); } while (true) { int fd; while (true) { log_debug("create socket"); fd = ::socket(_addrInfoPtr->ai_family, SOCK_STREAM, 0); if (fd >= 0) break; if (++_addrInfoPtr == _addrInfo.impl()->end()) { std::ostringstream msg; msg << "failed to create socket for host \"" << _addrInfo.host() << "\" port " << _addrInfo.port() << ": " << getErrnoString(); return msg.str(); } } #ifdef HAVE_SO_NOSIGPIPE static const int on = 1; if (::setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on)) < 0) throw cxxtools::SystemError("setsockopt(SO_NOSIGPIPE)"); #endif IODeviceImpl::open(fd, true, false); std::memmove(&_peeraddr, _addrInfoPtr->ai_addr, _addrInfoPtr->ai_addrlen); log_debug("created socket " << _fd << " max: " << FD_SETSIZE); if( ::connect(this->fd(), _addrInfoPtr->ai_addr, _addrInfoPtr->ai_addrlen) == 0 ) { _isConnected = true; log_debug("connected successfully to " << getPeerAddr()); break; } if (errno == EINPROGRESS) { log_debug("connect in progress"); break; } close(); if (++_addrInfoPtr == _addrInfo.impl()->end()) return connectFailedMessage(_addrInfo, errno); } return std::string(); } bool TcpSocketImpl::beginConnect(const AddrInfo& addrInfo) { log_trace("begin connect"); assert(!_isConnected); _addrInfo = addrInfo; _addrInfoPtr = _addrInfo.impl()->begin(); _connectResult = tryConnect(); checkPendingError(); return _isConnected; } void TcpSocketImpl::endConnect() { log_trace("ending connect"); if(_pfd && ! _socket.wbuf()) { _pfd->events &= ~POLLOUT; } checkPendingError(); if( _isConnected ) return; try { while (true) { pollfd pfd; pfd.fd = this->fd(); pfd.revents = 0; pfd.events = POLLOUT; log_debug("wait " << timeout() << " ms"); bool avail = this->wait(this->timeout(), pfd); if (avail) { // something has happened int sockerr = checkConnect(); if (_isConnected) return; if (++_addrInfoPtr == _addrInfo.impl()->end()) { // no more addrInfo - propagate error throw IOError(connectFailedMessage(_addrInfo, sockerr)); } } else if (++_addrInfoPtr == _addrInfo.impl()->end()) { log_debug("timeout"); throw IOTimeout(); } close(); _connectResult = tryConnect(); if (_isConnected) return; checkPendingError(); } } catch(...) { close(); throw; } } void TcpSocketImpl::accept(const TcpServer& server, unsigned flags) { socklen_t peeraddr_len = sizeof(_peeraddr); _fd = server.impl().accept(flags, reinterpret_cast <struct sockaddr*>(&_peeraddr), peeraddr_len); if( _fd < 0 ) throw SystemError("accept"); #ifdef HAVE_ACCEPT4 IODeviceImpl::open(_fd, false, false); #else bool inherit = (flags & TcpSocket::INHERIT) != 0; IODeviceImpl::open(_fd, true, inherit); #endif //TODO ECONNABORTED EINTR EPERM _isConnected = true; log_debug( "accepted from " << getPeerAddr()); } void TcpSocketImpl::initWait(pollfd& pfd) { IODeviceImpl::initWait(pfd); if( ! _isConnected ) { log_debug("not connected, setting POLLOUT "); pfd.events = POLLOUT; } } bool TcpSocketImpl::checkPollEvent(pollfd& pfd) { log_debug("checkPollEvent " << pfd.revents); if( _isConnected ) { // check for error while neither reading nor writing // // if reading or writing, IODeviceImpl::checkPollEvent will emit // inputReady or outputReady signal and the user gets an exception in // endRead or endWrite. if ( !_device.reading() && !_device.writing() && (pfd.revents & POLLERR) ) { _device.close(); _socket.closed(_socket); return true; } return IODeviceImpl::checkPollEvent(pfd); } if ( pfd.revents & POLLERR ) { AddrInfoImpl::const_iterator ptr = _addrInfoPtr; if (++ptr == _addrInfo.impl()->end()) { // not really connected but error // end of addrinfo list means that no working addrinfo was found log_debug("no more addrinfos found"); _socket.connected(_socket); return true; } else { _addrInfoPtr = ptr; close(); _connectResult = tryConnect(); if (_isConnected || !_connectResult.empty()) { // immediate success or error log_debug("connected successfully"); _socket.connected(_socket); } else { // by closing the previous file handle _pfd is set to 0. // creating a new socket in tryConnect may also change the value of fd. initializePoll(&pfd, 1); } return true; } } else if( pfd.revents & POLLOUT ) { int sockerr = checkConnect(); if (_isConnected) { _socket.connected(_socket); return true; } // something went wrong - look for next addrInfo log_debug("sockerr is " << sockerr << " try next"); if (++_addrInfoPtr == _addrInfo.impl()->end()) { // no more addrInfo - propagate error _connectResult = connectFailedMessage(_addrInfo, sockerr); _socket.connected(_socket); return true; } _connectResult = tryConnect(); if (_isConnected) { _socket.connected(_socket); return true; } } return false; } size_t TcpSocketImpl::beginWrite(const char* buffer, size_t n) { log_debug("::send(" << _fd << ", buffer, " << n << ')'); #if defined(HAVE_MSG_NOSIGNAL) ssize_t ret = ::send(_fd, (const void*)buffer, n, MSG_NOSIGNAL); #elif defined(HAVE_SO_NOSIGPIPE) ssize_t ret = ::send(_fd, (const void*)buffer, n, 0); #else // block SIGPIPE sigset_t sigpipeMask, oldSigmask; sigemptyset(&sigpipeMask); sigaddset(&sigpipeMask, SIGPIPE); pthread_sigmask(SIG_BLOCK, &sigpipeMask, &oldSigmask); // execute send ssize_t ret = ::send(_fd, (const void*)buffer, n, 0); // clear possible SIGPIPE sigset_t pending; sigemptyset(&pending); sigpending(&pending); if (sigismember(&pending, SIGPIPE)) { static const struct timespec nowait = { 0, 0 }; while (sigtimedwait(&sigpipeMask, 0, &nowait) == -1 && errno == EINTR) ; } // unblock SIGPIPE pthread_sigmask(SIG_SETMASK, &oldSigmask, 0); #endif log_debug("send returned " << ret); if (ret > 0) return static_cast<size_t>(ret); if (ret == 0 || errno == ECONNRESET || errno == EPIPE) throw IOError("lost connection to peer"); if(_pfd) { _pfd->events |= POLLOUT; } return 0; } } // namespace net } // namespace cxxtools <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: test-lexers.cpp // Purpose: Implementation for wxExtension cpp unit testing // Author: Anton van Wezenbeek // Copyright: (c) 2015 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/extension/lexers.h> #include <wx/extension/managedframe.h> #include <wx/extension/stc.h> #include "test.h" void fixture::testLexers() { wxExSTC* stc = new wxExSTC(m_Frame, "hello stc"); CPPUNIT_ASSERT( wxExLexers::Get() != NULL); CPPUNIT_ASSERT( wxExLexers::Get()->GetCount() > 0); CPPUNIT_ASSERT( wxExLexers::Get()->GetDefaultStyle().ContainsDefaultStyle()); CPPUNIT_ASSERT( wxExLexers::Get()->GetDefaultStyle().IsOk()); // Test lexer and global macros. for (const auto& macro : std::vector< std::pair< std::pair<std::string,std::string>, std::string>> { {{"number","asm"},"2"}, {{"number","cpp"},"4"}, {{"XXX","global"},"XXX"}, {{"mark_lcorner","global"},"10"}, {{"mark_circle","global"},"0"}, {{"iv_none","global"},"0"}}) { CPPUNIT_ASSERT( wxExLexers::Get()->ApplyMacro( macro.first.first, macro.first.second) == macro.second); } // At this moment we have no global properties. CPPUNIT_ASSERT( wxExLexers::Get()->GetProperties().empty()); wxExLexers::Get()->ApplyMarkers(stc); wxExLexers::Get()->ApplyProperties(stc); CPPUNIT_ASSERT(!wxExLexers::Get()->BuildWildCards( GetTestFile()).empty()); CPPUNIT_ASSERT( wxExLexers::Get()->GetCount() > 0); CPPUNIT_ASSERT( wxExLexers::Get()->FindByFileName( GetTestFile()).GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT( wxExLexers::Get()->FindByName( "xxx").GetScintillaLexer().empty()); CPPUNIT_ASSERT( wxExLexers::Get()->FindByName( "cpp").GetScintillaLexer() == "cpp"); for (const auto& findby : std::vector<std::pair< std::string, std::pair<std::string, std::string>>> { {"// this is a cpp comment text",{"cpp","cpp"}}, {"#!/bin/sh",{"bash","sh"}}, {"#!/bin/csh",{"bash","csh"}}, {"#!/bin/tcsh",{"bash","tcsh"}}, {"#!/bin/bash",{"bash","bash"}}, {"#!/bin/bash\n",{"bash","bash"}}, {"#!/usr/bin/csh",{"bash","bash"}}, {"<html>",{"hypertext","hypertext"}}, {"<?xml",{"hypertext","xml"}}}) { CPPUNIT_ASSERT( wxExLexers::Get()->FindByText( findby.first).GetScintillaLexer() == findby.second.first); CPPUNIT_ASSERT( wxExLexers::Get()->FindByText( findby.first).GetDisplayLexer() == findby.second.second); } CPPUNIT_ASSERT( wxExLexers::Get()->GetFileName().IsOk()); CPPUNIT_ASSERT(!wxExLexers::Get()->GetMacros("global").empty()); CPPUNIT_ASSERT(!wxExLexers::Get()->GetMacros("cpp").empty()); CPPUNIT_ASSERT(!wxExLexers::Get()->GetMacros("pascal").empty()); CPPUNIT_ASSERT( wxExLexers::Get()->GetMacros("XXX").empty()); CPPUNIT_ASSERT(!wxExLexers::Get()->GetTheme().empty()); CPPUNIT_ASSERT( wxExLexers::Get()->GetThemeOk()); CPPUNIT_ASSERT(!wxExLexers::Get()->GetThemeMacros().empty()); CPPUNIT_ASSERT(!wxExLexers::Get()->GetThemes() > 1); CPPUNIT_ASSERT(!wxExLexers::Get()->SetTheme("xxx")); CPPUNIT_ASSERT(!wxExLexers::Get()->GetTheme().empty()); CPPUNIT_ASSERT( wxExLexers::Get()->GetThemeOk()); CPPUNIT_ASSERT( wxExLexers::Get()->SetTheme("torte")); CPPUNIT_ASSERT( wxExLexers::Get()->GetTheme() == "torte"); CPPUNIT_ASSERT( wxExLexers::Get()->GetThemeOk()); wxExLexers::Get()->SetThemeNone(); CPPUNIT_ASSERT( wxExLexers::Get()->GetTheme().empty()); CPPUNIT_ASSERT(!wxExLexers::Get()->GetThemeOk()); wxExLexers::Get()->RestoreTheme(); CPPUNIT_ASSERT( wxExLexers::Get()->GetTheme() == "torte"); CPPUNIT_ASSERT( wxExLexers::Get()->GetThemeOk()); CPPUNIT_ASSERT(!wxExLexers::Get()->IndicatorIsLoaded(wxExIndicator(99, -1))); CPPUNIT_ASSERT( wxExLexers::Get()->IndicatorIsLoaded(wxExIndicator(0, -1))); CPPUNIT_ASSERT( wxExLexers::Get()->MarkerIsLoaded(wxExMarker(0, -1))); wxString lexer("cpp"); wxExLexers::Get()->ShowDialog(m_Frame, lexer, wxEmptyString, false); wxExLexers::Get()->ShowThemeDialog(m_Frame, wxEmptyString, false); CPPUNIT_ASSERT(!wxExLexers::Get()->GetKeywords("cpp").empty()); CPPUNIT_ASSERT(!wxExLexers::Get()->GetKeywords("csh").empty()); CPPUNIT_ASSERT( wxExLexers::Get()->GetKeywords("xxx").empty()); CPPUNIT_ASSERT( wxExLexers::Get()->GetKeywords(wxEmptyString).empty()); CPPUNIT_ASSERT( wxExLexers::Get()->LoadDocument()); } <commit_msg>fixed test<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: test-lexers.cpp // Purpose: Implementation for wxExtension cpp unit testing // Author: Anton van Wezenbeek // Copyright: (c) 2015 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/extension/lexers.h> #include <wx/extension/managedframe.h> #include <wx/extension/stc.h> #include "test.h" void fixture::testLexers() { wxExSTC* stc = new wxExSTC(m_Frame, "hello stc"); CPPUNIT_ASSERT( wxExLexers::Get() != NULL); CPPUNIT_ASSERT( wxExLexers::Get()->GetCount() > 0); CPPUNIT_ASSERT( wxExLexers::Get()->GetDefaultStyle().ContainsDefaultStyle()); CPPUNIT_ASSERT( wxExLexers::Get()->GetDefaultStyle().IsOk()); // Test lexer and global macros. for (const auto& macro : std::vector< std::pair< std::pair<std::string,std::string>, std::string>> { {{"number","asm"},"2"}, {{"number","cpp"},"4"}, {{"XXX","global"},"XXX"}, {{"mark_lcorner","global"},"10"}, {{"mark_circle","global"},"0"}, {{"iv_none","global"},"0"}}) { CPPUNIT_ASSERT( wxExLexers::Get()->ApplyMacro( macro.first.first, macro.first.second) == macro.second); } // At this moment we have no global properties. CPPUNIT_ASSERT( wxExLexers::Get()->GetProperties().empty()); wxExLexers::Get()->ApplyMarkers(stc); wxExLexers::Get()->ApplyProperties(stc); CPPUNIT_ASSERT(!wxExLexers::Get()->BuildWildCards( GetTestFile()).empty()); CPPUNIT_ASSERT( wxExLexers::Get()->GetCount() > 0); CPPUNIT_ASSERT( wxExLexers::Get()->FindByFileName( GetTestFile()).GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT( wxExLexers::Get()->FindByName( "xxx").GetScintillaLexer().empty()); CPPUNIT_ASSERT( wxExLexers::Get()->FindByName( "cpp").GetScintillaLexer() == "cpp"); for (const auto& findby : std::vector<std::pair< std::string, std::pair<std::string, std::string>>> { {"// this is a cpp comment text",{"cpp","cpp"}}, {"#!/bin/sh",{"bash","sh"}}, {"#!/bin/csh",{"bash","csh"}}, {"#!/bin/tcsh",{"bash","tcsh"}}, {"#!/bin/bash",{"bash","bash"}}, {"#!/bin/bash\n",{"bash","bash"}}, {"#!/usr/bin/csh",{"bash","bash"}}, {"<html>",{"hypertext","hypertext"}}, {"<?xml",{"hypertext","xml"}}}) { CPPUNIT_ASSERT( wxExLexers::Get()->FindByText( findby.first).GetScintillaLexer() == findby.second.first); CPPUNIT_ASSERT( wxExLexers::Get()->FindByText( findby.first).GetDisplayLexer() == findby.second.second); } CPPUNIT_ASSERT( wxExLexers::Get()->GetFileName().IsOk()); CPPUNIT_ASSERT(!wxExLexers::Get()->GetMacros("global").empty()); CPPUNIT_ASSERT(!wxExLexers::Get()->GetMacros("cpp").empty()); CPPUNIT_ASSERT(!wxExLexers::Get()->GetMacros("pascal").empty()); CPPUNIT_ASSERT( wxExLexers::Get()->GetMacros("XXX").empty()); CPPUNIT_ASSERT(!wxExLexers::Get()->GetTheme().empty()); CPPUNIT_ASSERT( wxExLexers::Get()->GetThemeOk()); CPPUNIT_ASSERT(!wxExLexers::Get()->GetThemeMacros().empty()); CPPUNIT_ASSERT( wxExLexers::Get()->GetThemes() > 1); CPPUNIT_ASSERT(!wxExLexers::Get()->SetTheme("xxx")); CPPUNIT_ASSERT(!wxExLexers::Get()->GetTheme().empty()); CPPUNIT_ASSERT( wxExLexers::Get()->GetThemeOk()); CPPUNIT_ASSERT( wxExLexers::Get()->SetTheme("torte")); CPPUNIT_ASSERT( wxExLexers::Get()->GetTheme() == "torte"); CPPUNIT_ASSERT( wxExLexers::Get()->GetThemeOk()); wxExLexers::Get()->SetThemeNone(); CPPUNIT_ASSERT( wxExLexers::Get()->GetTheme().empty()); CPPUNIT_ASSERT(!wxExLexers::Get()->GetThemeOk()); wxExLexers::Get()->RestoreTheme(); CPPUNIT_ASSERT( wxExLexers::Get()->GetTheme() == "torte"); CPPUNIT_ASSERT( wxExLexers::Get()->GetThemeOk()); CPPUNIT_ASSERT(!wxExLexers::Get()->IndicatorIsLoaded(wxExIndicator(99, -1))); CPPUNIT_ASSERT( wxExLexers::Get()->IndicatorIsLoaded(wxExIndicator(0, -1))); CPPUNIT_ASSERT( wxExLexers::Get()->MarkerIsLoaded(wxExMarker(0, -1))); wxString lexer("cpp"); wxExLexers::Get()->ShowDialog(m_Frame, lexer, wxEmptyString, false); wxExLexers::Get()->ShowThemeDialog(m_Frame, wxEmptyString, false); CPPUNIT_ASSERT(!wxExLexers::Get()->GetKeywords("cpp").empty()); CPPUNIT_ASSERT(!wxExLexers::Get()->GetKeywords("csh").empty()); CPPUNIT_ASSERT( wxExLexers::Get()->GetKeywords("xxx").empty()); CPPUNIT_ASSERT( wxExLexers::Get()->GetKeywords(wxEmptyString).empty()); CPPUNIT_ASSERT( wxExLexers::Get()->LoadDocument()); } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkComputeContourSetNormalsFilter.h" #include "mitkImagePixelReadAccessor.h" #include "mitkIOUtil.h" mitk::ComputeContourSetNormalsFilter::ComputeContourSetNormalsFilter() : m_SegmentationBinaryImage(NULL) , m_MaxSpacing(5) , m_NegativeNormalCounter(0) , m_PositiveNormalCounter(0) , m_UseProgressBar(false) , m_ProgressStepSize(1) { mitk::Surface::Pointer output = mitk::Surface::New(); this->SetNthOutput(0, output.GetPointer()); } mitk::ComputeContourSetNormalsFilter::~ComputeContourSetNormalsFilter() { } void mitk::ComputeContourSetNormalsFilter::GenerateData() { unsigned int numberOfInputs = this->GetNumberOfIndexedInputs(); this->CreateOutputsForAllInputs(numberOfInputs); //Iterating over each input for(unsigned int i = 0; i < numberOfInputs; i++) { //Getting the inputs polydata and polygons Surface* currentSurface = const_cast<Surface*>( this->GetInput(i) ); vtkPolyData* polyData = currentSurface->GetVtkPolyData(); vtkSmartPointer<vtkCellArray> existingPolys = polyData->GetPolys(); vtkSmartPointer<vtkPoints> existingPoints = polyData->GetPoints(); existingPolys->InitTraversal(); vtkIdType* cell (NULL); vtkIdType cellSize (0); //The array that contains all the vertex normals of the current polygon vtkSmartPointer<vtkDoubleArray> normals = vtkSmartPointer<vtkDoubleArray>::New(); normals->SetNumberOfComponents(3); normals->SetNumberOfTuples(polyData->GetNumberOfPoints()); //If the current contour is an inner contour then the direction is -1 //A contour lies inside another one if the pixel values in the direction of the normal is 1 m_NegativeNormalCounter = 0; m_PositiveNormalCounter = 0; vtkIdType offSet (0); //Iterating over each polygon for( existingPolys->InitTraversal(); existingPolys->GetNextCell(cellSize, cell);) { if(cellSize < 3)continue; //First we calculate the current polygon's normal double polygonNormal[3] = {0.0}; double p1[3]; double p2[3]; double v1[3]; double v2[3]; existingPoints->GetPoint(cell[0], p1); unsigned int index = cellSize*0.5; existingPoints->GetPoint(cell[index], p2); v1[0] = p2[0]-p1[0]; v1[1] = p2[1]-p1[1]; v1[2] = p2[2]-p1[2]; for (vtkIdType k = 2; k < cellSize; k++) { index = cellSize*0.25; existingPoints->GetPoint(cell[index], p1); index = cellSize*0.75; existingPoints->GetPoint(cell[index], p2); v2[0] = p2[0]-p1[0]; v2[1] = p2[1]-p1[1]; v2[2] = p2[2]-p1[2]; vtkMath::Cross(v1,v2,polygonNormal); if (vtkMath::Norm(polygonNormal) != 0) break; } vtkMath::Normalize(polygonNormal); //Now we start computing the normal for each vertex double vertexNormalTemp[3]; existingPoints->GetPoint(cell[0], p1); existingPoints->GetPoint(cell[1], p2); v1[0] = p2[0]-p1[0]; v1[1] = p2[1]-p1[1]; v1[2] = p2[2]-p1[2]; vtkMath::Cross(v1,polygonNormal,vertexNormalTemp); vtkMath::Normalize(vertexNormalTemp); double vertexNormal[3]; for (vtkIdType j = 0; j < cellSize-2; j++) { existingPoints->GetPoint(cell[j+1], p1); existingPoints->GetPoint(cell[j+2], p2); v1[0] = p2[0]-p1[0]; v1[1] = p2[1]-p1[1]; v1[2] = p2[2]-p1[2]; vtkMath::Cross(v1,polygonNormal,vertexNormal); vtkMath::Normalize(vertexNormal); double finalNormal[3]; finalNormal[0] = (vertexNormal[0] + vertexNormalTemp[0])*0.5; finalNormal[1] = (vertexNormal[1] + vertexNormalTemp[1])*0.5; finalNormal[2] = (vertexNormal[2] + vertexNormalTemp[2])*0.5; //Here we determine the direction of the normal if (m_SegmentationBinaryImage) { Point3D worldCoord; worldCoord[0] = p1[0]+finalNormal[0]*m_MaxSpacing; worldCoord[1] = p1[1]+finalNormal[1]*m_MaxSpacing; worldCoord[2] = p1[2]+finalNormal[2]*m_MaxSpacing; std::cout << "World coords: " << worldCoord[0] << " , " << worldCoord[1] << " , " << worldCoord[2] << std::endl; std::cout << "...for point: " << p1[0] << " , " << p1[1] << " , " << p1[2] << std::endl; std::cout << "...and normal: " << finalNormal[0] << " , " << finalNormal[1] << " , " << finalNormal[2] << std::endl; std::cout << "MaxSpacing: " << m_MaxSpacing << std::endl; double val = 0.0; mitk::ImagePixelReadAccessor<unsigned char> readAccess(m_SegmentationBinaryImage); itk::Index<3> idx; m_SegmentationBinaryImage->GetGeometry()->WorldToIndex(worldCoord, idx); try { val = readAccess.GetPixelByIndexSafe(idx); } catch (mitk::Exception e) { // If value is outside the image's region ignore it } if (val == 0.0) { //MITK_INFO << "val equals zero."; ++m_PositiveNormalCounter; } else { //MITK_INFO << "val does not equal zero."; ++m_NegativeNormalCounter; } } vertexNormalTemp[0] = vertexNormal[0]; vertexNormalTemp[1] = vertexNormal[1]; vertexNormalTemp[2] = vertexNormal[2]; vtkIdType id = cell[j+1]; normals->SetTuple(id,finalNormal); } existingPoints->GetPoint(cell[0], p1); existingPoints->GetPoint(cell[1], p2); v1[0] = p2[0]-p1[0]; v1[1] = p2[1]-p1[1]; v1[2] = p2[2]-p1[2]; vtkMath::Cross(v1,polygonNormal,vertexNormal); vtkMath::Normalize(vertexNormal); vertexNormal[0] = (vertexNormal[0] + vertexNormalTemp[0])*0.5; vertexNormal[1] = (vertexNormal[1] + vertexNormalTemp[1])*0.5; vertexNormal[2] = (vertexNormal[2] + vertexNormalTemp[2])*0.5; vtkIdType id = cell[0]; normals->SetTuple(id,vertexNormal); id = cell[cellSize-1]; normals->SetTuple(id,vertexNormal); std::cout << "Negative normal counter: " << m_NegativeNormalCounter << std::endl; std::cout << "Positive normal counter: " << m_PositiveNormalCounter << std::endl; if(m_NegativeNormalCounter > m_PositiveNormalCounter) { for(vtkIdType n = 0; n < cellSize; n++) { double normal[3]; normals->GetTuple(offSet+n, normal); normal[0] = (-1)*normal[0]; normal[1] = (-1)*normal[1]; normal[2] = (-1)*normal[2]; normals->SetTuple(offSet+n, normal); } } m_NegativeNormalCounter = 0; m_PositiveNormalCounter = 0; offSet += cellSize; }//end for all cells Surface::Pointer surface = this->GetOutput(i); surface->GetVtkPolyData()->GetCellData()->SetNormals(normals); }//end for all inputs //Setting progressbar if (this->m_UseProgressBar) mitk::ProgressBar::GetInstance()->Progress(this->m_ProgressStepSize); } mitk::Surface::Pointer mitk::ComputeContourSetNormalsFilter::GetNormalsAsSurface() { //Just for debugging: vtkSmartPointer<vtkPolyData> newPolyData = vtkSmartPointer<vtkPolyData>::New(); vtkSmartPointer<vtkCellArray> newLines = vtkSmartPointer<vtkCellArray>::New(); vtkSmartPointer<vtkPoints> newPoints = vtkSmartPointer<vtkPoints>::New(); unsigned int idCounter (0); //Debug end for (unsigned int i = 0; i < this->GetNumberOfIndexedOutputs(); i++) { Surface* currentSurface = const_cast<Surface*>( this->GetOutput(i) ); vtkPolyData* polyData = currentSurface->GetVtkPolyData(); vtkSmartPointer<vtkDoubleArray> currentCellNormals = vtkDoubleArray::SafeDownCast(polyData->GetCellData()->GetNormals()); vtkSmartPointer<vtkCellArray> existingPolys = polyData->GetPolys(); vtkSmartPointer<vtkPoints> existingPoints = polyData->GetPoints(); existingPolys->InitTraversal(); vtkIdType* cell (NULL); vtkIdType cellSize (0); for( existingPolys->InitTraversal(); existingPolys->GetNextCell(cellSize, cell);) { for ( vtkIdType j = 0; j < cellSize; j++ ) { double currentNormal[3]; currentCellNormals->GetTuple(cell[j], currentNormal); vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New(); line->GetPointIds()->SetNumberOfIds(2); double newPoint[3]; double p0[3]; existingPoints->GetPoint(cell[j], p0); newPoint[0] = p0[0] + currentNormal[0]; newPoint[1] = p0[1] + currentNormal[1]; newPoint[2] = p0[2] + currentNormal[2]; line->GetPointIds()->SetId(0, idCounter); newPoints->InsertPoint(idCounter, p0); idCounter++; line->GetPointIds()->SetId(1, idCounter); newPoints->InsertPoint(idCounter, newPoint); idCounter++; newLines->InsertNextCell(line); }//end for all points }//end for all cells }//end for all outputs newPolyData->SetPoints(newPoints); newPolyData->SetLines(newLines); newPolyData->BuildCells(); mitk::Surface::Pointer surface = mitk::Surface::New(); surface->SetVtkPolyData(newPolyData); return surface; } void mitk::ComputeContourSetNormalsFilter::SetMaxSpacing(double maxSpacing) { m_MaxSpacing = maxSpacing; } void mitk::ComputeContourSetNormalsFilter::GenerateOutputInformation() { Superclass::GenerateOutputInformation(); } void mitk::ComputeContourSetNormalsFilter::Reset() { for (unsigned int i = 0; i < this->GetNumberOfIndexedInputs(); i++) { this->PopBackInput(); } this->SetNumberOfIndexedInputs(0); this->SetNumberOfIndexedOutputs(0); mitk::Surface::Pointer output = mitk::Surface::New(); this->SetNthOutput(0, output.GetPointer()); } void mitk::ComputeContourSetNormalsFilter::SetUseProgressBar(bool status) { this->m_UseProgressBar = status; } void mitk::ComputeContourSetNormalsFilter::SetProgressStepSize(unsigned int stepSize) { this->m_ProgressStepSize = stepSize; } <commit_msg>Cleanup.<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkComputeContourSetNormalsFilter.h" #include "mitkImagePixelReadAccessor.h" #include "mitkIOUtil.h" mitk::ComputeContourSetNormalsFilter::ComputeContourSetNormalsFilter() : m_SegmentationBinaryImage(NULL) , m_MaxSpacing(5) , m_NegativeNormalCounter(0) , m_PositiveNormalCounter(0) , m_UseProgressBar(false) , m_ProgressStepSize(1) { mitk::Surface::Pointer output = mitk::Surface::New(); this->SetNthOutput(0, output.GetPointer()); } mitk::ComputeContourSetNormalsFilter::~ComputeContourSetNormalsFilter() { } void mitk::ComputeContourSetNormalsFilter::GenerateData() { unsigned int numberOfInputs = this->GetNumberOfIndexedInputs(); this->CreateOutputsForAllInputs(numberOfInputs); //Iterating over each input for(unsigned int i = 0; i < numberOfInputs; i++) { //Getting the inputs polydata and polygons Surface* currentSurface = const_cast<Surface*>( this->GetInput(i) ); vtkPolyData* polyData = currentSurface->GetVtkPolyData(); vtkSmartPointer<vtkCellArray> existingPolys = polyData->GetPolys(); vtkSmartPointer<vtkPoints> existingPoints = polyData->GetPoints(); existingPolys->InitTraversal(); vtkIdType* cell (NULL); vtkIdType cellSize (0); //The array that contains all the vertex normals of the current polygon vtkSmartPointer<vtkDoubleArray> normals = vtkSmartPointer<vtkDoubleArray>::New(); normals->SetNumberOfComponents(3); normals->SetNumberOfTuples(polyData->GetNumberOfPoints()); //If the current contour is an inner contour then the direction is -1 //A contour lies inside another one if the pixel values in the direction of the normal is 1 m_NegativeNormalCounter = 0; m_PositiveNormalCounter = 0; vtkIdType offSet (0); //Iterating over each polygon for( existingPolys->InitTraversal(); existingPolys->GetNextCell(cellSize, cell);) { if(cellSize < 3)continue; //First we calculate the current polygon's normal double polygonNormal[3] = {0.0}; double p1[3]; double p2[3]; double v1[3]; double v2[3]; existingPoints->GetPoint(cell[0], p1); unsigned int index = cellSize*0.5; existingPoints->GetPoint(cell[index], p2); v1[0] = p2[0]-p1[0]; v1[1] = p2[1]-p1[1]; v1[2] = p2[2]-p1[2]; for (vtkIdType k = 2; k < cellSize; k++) { index = cellSize*0.25; existingPoints->GetPoint(cell[index], p1); index = cellSize*0.75; existingPoints->GetPoint(cell[index], p2); v2[0] = p2[0]-p1[0]; v2[1] = p2[1]-p1[1]; v2[2] = p2[2]-p1[2]; vtkMath::Cross(v1,v2,polygonNormal); if (vtkMath::Norm(polygonNormal) != 0) break; } vtkMath::Normalize(polygonNormal); //Now we start computing the normal for each vertex double vertexNormalTemp[3]; existingPoints->GetPoint(cell[0], p1); existingPoints->GetPoint(cell[1], p2); v1[0] = p2[0]-p1[0]; v1[1] = p2[1]-p1[1]; v1[2] = p2[2]-p1[2]; vtkMath::Cross(v1,polygonNormal,vertexNormalTemp); vtkMath::Normalize(vertexNormalTemp); double vertexNormal[3]; for (vtkIdType j = 0; j < cellSize-2; j++) { existingPoints->GetPoint(cell[j+1], p1); existingPoints->GetPoint(cell[j+2], p2); v1[0] = p2[0]-p1[0]; v1[1] = p2[1]-p1[1]; v1[2] = p2[2]-p1[2]; vtkMath::Cross(v1,polygonNormal,vertexNormal); vtkMath::Normalize(vertexNormal); double finalNormal[3]; finalNormal[0] = (vertexNormal[0] + vertexNormalTemp[0])*0.5; finalNormal[1] = (vertexNormal[1] + vertexNormalTemp[1])*0.5; finalNormal[2] = (vertexNormal[2] + vertexNormalTemp[2])*0.5; //Here we determine the direction of the normal if (m_SegmentationBinaryImage) { Point3D worldCoord; worldCoord[0] = p1[0]+finalNormal[0]*m_MaxSpacing; worldCoord[1] = p1[1]+finalNormal[1]*m_MaxSpacing; worldCoord[2] = p1[2]+finalNormal[2]*m_MaxSpacing; double val = 0.0; mitk::ImagePixelReadAccessor<unsigned char> readAccess(m_SegmentationBinaryImage); itk::Index<3> idx; m_SegmentationBinaryImage->GetGeometry()->WorldToIndex(worldCoord, idx); try { val = readAccess.GetPixelByIndexSafe(idx); } catch (mitk::Exception e) { // If value is outside the image's region ignore it } if (val == 0.0) { //MITK_INFO << "val equals zero."; ++m_PositiveNormalCounter; } else { //MITK_INFO << "val does not equal zero."; ++m_NegativeNormalCounter; } } vertexNormalTemp[0] = vertexNormal[0]; vertexNormalTemp[1] = vertexNormal[1]; vertexNormalTemp[2] = vertexNormal[2]; vtkIdType id = cell[j+1]; normals->SetTuple(id,finalNormal); } existingPoints->GetPoint(cell[0], p1); existingPoints->GetPoint(cell[1], p2); v1[0] = p2[0]-p1[0]; v1[1] = p2[1]-p1[1]; v1[2] = p2[2]-p1[2]; vtkMath::Cross(v1,polygonNormal,vertexNormal); vtkMath::Normalize(vertexNormal); vertexNormal[0] = (vertexNormal[0] + vertexNormalTemp[0])*0.5; vertexNormal[1] = (vertexNormal[1] + vertexNormalTemp[1])*0.5; vertexNormal[2] = (vertexNormal[2] + vertexNormalTemp[2])*0.5; vtkIdType id = cell[0]; normals->SetTuple(id,vertexNormal); id = cell[cellSize-1]; normals->SetTuple(id,vertexNormal); if(m_NegativeNormalCounter > m_PositiveNormalCounter) { for(vtkIdType n = 0; n < cellSize; n++) { double normal[3]; normals->GetTuple(offSet+n, normal); normal[0] = (-1)*normal[0]; normal[1] = (-1)*normal[1]; normal[2] = (-1)*normal[2]; normals->SetTuple(offSet+n, normal); } } m_NegativeNormalCounter = 0; m_PositiveNormalCounter = 0; offSet += cellSize; }//end for all cells Surface::Pointer surface = this->GetOutput(i); surface->GetVtkPolyData()->GetCellData()->SetNormals(normals); }//end for all inputs //Setting progressbar if (this->m_UseProgressBar) mitk::ProgressBar::GetInstance()->Progress(this->m_ProgressStepSize); } mitk::Surface::Pointer mitk::ComputeContourSetNormalsFilter::GetNormalsAsSurface() { //Just for debugging: vtkSmartPointer<vtkPolyData> newPolyData = vtkSmartPointer<vtkPolyData>::New(); vtkSmartPointer<vtkCellArray> newLines = vtkSmartPointer<vtkCellArray>::New(); vtkSmartPointer<vtkPoints> newPoints = vtkSmartPointer<vtkPoints>::New(); unsigned int idCounter (0); //Debug end for (unsigned int i = 0; i < this->GetNumberOfIndexedOutputs(); i++) { Surface* currentSurface = const_cast<Surface*>( this->GetOutput(i) ); vtkPolyData* polyData = currentSurface->GetVtkPolyData(); vtkSmartPointer<vtkDoubleArray> currentCellNormals = vtkDoubleArray::SafeDownCast(polyData->GetCellData()->GetNormals()); vtkSmartPointer<vtkCellArray> existingPolys = polyData->GetPolys(); vtkSmartPointer<vtkPoints> existingPoints = polyData->GetPoints(); existingPolys->InitTraversal(); vtkIdType* cell (NULL); vtkIdType cellSize (0); for( existingPolys->InitTraversal(); existingPolys->GetNextCell(cellSize, cell);) { for ( vtkIdType j = 0; j < cellSize; j++ ) { double currentNormal[3]; currentCellNormals->GetTuple(cell[j], currentNormal); vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New(); line->GetPointIds()->SetNumberOfIds(2); double newPoint[3]; double p0[3]; existingPoints->GetPoint(cell[j], p0); newPoint[0] = p0[0] + currentNormal[0]; newPoint[1] = p0[1] + currentNormal[1]; newPoint[2] = p0[2] + currentNormal[2]; line->GetPointIds()->SetId(0, idCounter); newPoints->InsertPoint(idCounter, p0); idCounter++; line->GetPointIds()->SetId(1, idCounter); newPoints->InsertPoint(idCounter, newPoint); idCounter++; newLines->InsertNextCell(line); }//end for all points }//end for all cells }//end for all outputs newPolyData->SetPoints(newPoints); newPolyData->SetLines(newLines); newPolyData->BuildCells(); mitk::Surface::Pointer surface = mitk::Surface::New(); surface->SetVtkPolyData(newPolyData); return surface; } void mitk::ComputeContourSetNormalsFilter::SetMaxSpacing(double maxSpacing) { m_MaxSpacing = maxSpacing; } void mitk::ComputeContourSetNormalsFilter::GenerateOutputInformation() { Superclass::GenerateOutputInformation(); } void mitk::ComputeContourSetNormalsFilter::Reset() { for (unsigned int i = 0; i < this->GetNumberOfIndexedInputs(); i++) { this->PopBackInput(); } this->SetNumberOfIndexedInputs(0); this->SetNumberOfIndexedOutputs(0); mitk::Surface::Pointer output = mitk::Surface::New(); this->SetNthOutput(0, output.GetPointer()); } void mitk::ComputeContourSetNormalsFilter::SetUseProgressBar(bool status) { this->m_UseProgressBar = status; } void mitk::ComputeContourSetNormalsFilter::SetProgressStepSize(unsigned int stepSize) { this->m_ProgressStepSize = stepSize; } <|endoftext|>
<commit_before><commit_msg>Fix loading screen_ratio_pixel_count lod strategy from mesh<commit_after><|endoftext|>
<commit_before>#include "../include/Slider.hpp" int main(int argc, char** argv) { Console::Init(argv); Lua::Init(Console::Path); printf("aldhaksdh"); bool instructions_closed; Lua::RunAsync(Console::Path+"..\\bin\\Lua\\instructions.lua", NULL, &instructions_closed); std::vector<char *> ellipses_anim = {".", ".", ".", "\b \b", "\b \b", "\b \b"}; while (!instructions_closed) { for (auto i:ellipses_anim) { printf(i); if (!instructions_closed) { std::this_thread::sleep_for(std::chrono::microseconds(200000)); } } } system("cls"); //Lua::RunSync(path+"..\\bin\\Lua\\rulesets.lua"); Console::PromptMenu("Main Menu", { {"Default", []() { printf("Test\n"); } }, {"Other", []() { } } }, []() { }); return 0; }<commit_msg>Accepted<commit_after>#include "../include/Slider.hpp" int main(int argc, char** argv) { Console::Init(argv); Lua::Init(Console::Path); printf("aldhaksdh"); bool instructions_closed; Lua::RunAsync(Console::Path+"..\\bin\\Lua\\instructions.lua", NULL, &instructions_closed); std::vector<char *> ellipses_anim = {".", ".", ".", "\b \b", "\b \b", "\b \b"}; while (!instructions_closed) { for (auto i:ellipses_anim) { printf(i); if (!instructions_closed) { std::this_thread::sleep_for(std::chrono::microseconds(200000)); } } } system("cls"); //Lua::RunSync(path+"..\\bin\\Lua\\rulesets.lua"); Console::PromptMenu("Main Menu", { {"Default", []() { printf("Test\n"); } }, {"Other", []() { } } }, []() { }); return 0; }<|endoftext|>
<commit_before>#include "solver.h" // Solver helper function static bool satisfyAlready(const vector<int> &cls) { unordered_set<int> checker; for(auto &v : cls) { if( checker.find(-v) != checker.end() ) return true; checker.insert(v); } return false; } // Init solver with cnf file void solver::init(const char *filename) { // Init with empty solver *this = solver(); // Get raw clause from cnf file vector< vector<int> > raw; parse_DIMACS_CNF(raw, maxVarIndex, filename); // Init assignment stack var = opStack(maxVarIndex+4); // Init database with all clause which has 2 or more literal in raw database // Eliminate all unit clause and check whether there is empty clause vector<int> unit; for(auto &cls : raw) { if( cls.empty() ) unsatAfterInit = 1; else if( cls.size() == 1 ) unit.emplace_back(cls[0]); else if( !satisfyAlready(cls) ) { clauses.push_back(Clause()); clauses.back().watcher[0] = 0; clauses.back().watcher[1] = (cls.size() >> 1); clauses.back().lit = move(cls); } } // Init two watching check list pos = vector< vector<WatcherInfo> >(maxVarIndex+4); neg = vector< vector<WatcherInfo> >(maxVarIndex+4); int cid = 0; for(auto &cls : clauses) { int id = cls.getWatchVar(0); if( cls.getWatchSign(0) ) pos[id].emplace_back(WatcherInfo(cid, 0)); else neg[id].emplace_back(WatcherInfo(cid, 0)); id = cls.getWatchVar(1); if( cls.getWatchSign(1) ) pos[id].emplace_back(WatcherInfo(cid, 1)); else neg[id].emplace_back(WatcherInfo(cid, 1)); ++cid; } // Assign and run BCP for all unit clause for(auto lit : unit) unsatAfterInit |= !set(abs(lit), lit>0); // Identify independent subproblem via disjoint set dset.init(maxVarIndex+4); for(auto &cls : clauses) { int id = 0; while( id<cls.size() && var.getVal(cls.getVar(id))!=2 ) ++id; for(int i=id+1; i<cls.size(); ++i) if( var.getVal(cls.getVar(i))==2 ) dset.unionSet(cls.getVar(i), cls.getVar(id)); } } // Assign id=val@nowLevel and run BCP recursively bool solver::set(int id, bool val, int src) { // If id is already set, check consistency if( var.getVal(id) != 2 ) { conflictingClsID = -1; return var.getVal(id) == val; } // Set id=val@nowLevel var.set(id, val, nowLevel, src); // Update 2 literal watching vector<WatcherInfo> &lst = (val ? neg[id] : pos[id]); for(int i=lst.size()-1; i>=0; --i) { // Update watcher updateClauseWatcher(lst[i]); if( getVal(lst[i]) == 2 || eval(lst[i]) ) { // Watcher reaches an pending/satisfied variable // Push this watcher to corresponding check list if( getSign(lst[i]) ) pos[getVar(lst[i])].emplace_back(lst[i]); else neg[getVar(lst[i])].emplace_back(lst[i]); // Delete this watcher from current check list swap(lst[i], lst.back()); lst.pop_back(); } else { // Watcher run through all clause back to original one // Can't find next literal to watch // b = alternative watcher in this clause WatcherInfo b(lst[i].clsid, lst[i].wid^1); if( getVal(b) == 2 ) { if( !set(getVar(b), getSign(b), lst[i].clsid) ) return false; } else if( !eval(b) ) { conflictingClsID = lst[i].clsid; return false; } } } // BCP done successfully without conflict return true; } bool solver::solve(int mode) { // Init statistic and start timer statistic.init(); if( unsatAfterInit ) return false; // Init DPLL litMarker.init(maxVarIndex+4); sat = true; nowLevel = 0; // Solve each independent subproblems for(int i=1; i<=maxVarIndex && sat; ++i) { if( dset.findRoot(i) != i ) continue; nowSetID = i; // Init for specific heuristic // This must be done before each subproblems if( mode == HEURISTIC_NO ) { heuristicInit_no(); pickUnassignedVar = &solver::heuristic_static; } else if( mode == HEURISTIC_MOM ) { heuristicInit_MOM(); pickUnassignedVar = &solver::heuristic_static; } else { fprintf(stderr, "Unknown solver mode\n"); exit(1); } sat &= _solve(); } statistic.stopTimer(); return sat; } bool solver::_solve() { // This subproblem startting stack index const int bound = nowLevel; // Main loop for DPLL while( true ) { ++nowLevel; statistic.maxDepth = max(statistic.maxDepth, nowLevel); staticOrderFrom = 0; pii decision = (this->*pickUnassignedVar)(); if( decision.first == -1 ) return true; int vid = decision.first; int sign = decision.second; while( !set(vid, sign) ) { if( conflictingClsID == -1 ) return false; vector<int> learnt = firstUIP(); if( learnt.empty() ) return false; // Determined cronological backtracking int backlv = bound; int towatch = -1; for(int i=learnt.size()-2; i>=0; --i) if( var.getLv(abs(learnt[i])) > backlv ) { backlv = var.getLv(abs(learnt[i])); towatch = i; } // Learn one assignment if( learnt.size() == 1 || backlv == bound ) { ++statistic.backtrackNum; ++statistic.learnAssignment; var.backToLevel(bound); statistic.maxJumpBack = max(statistic.maxJumpBack, nowLevel-bound); nowLevel = bound; int uip = learnt.back(); if( !set(abs(uip), uip>0) ) return false; break; } // Add conflict clause statistic.maxLearntSz = max(statistic.maxLearntSz, int(learnt.size())); clauses.push_back(Clause()); clauses.back().watcher[0] = towatch; clauses.back().watcher[1] = learnt.size() - 1; clauses.back().lit = move(learnt); int cid = clauses.size() - 1; int id = clauses.back().getWatchVar(0); if( clauses.back().getWatchSign(0) ) pos[id].emplace_back(WatcherInfo(cid, 0)); else neg[id].emplace_back(WatcherInfo(cid, 0)); id = clauses.back().getWatchVar(1); if( clauses.back().getWatchSign(1) ) pos[id].emplace_back(WatcherInfo(cid, 1)); else neg[id].emplace_back(WatcherInfo(cid, 1)); ++statistic.backtrackNum; ++statistic.learnCls; statistic.maxJumpBack = max(statistic.maxJumpBack, nowLevel-backlv); var.backToLevel(backlv-1); nowLevel = backlv; vid = var.topNext().var; sign = var.topNext().val; } } return false; } /****************************************************** Implementing Conflict Clause Learning Heuristic ******************************************************/ vector<int> solver::firstUIP() { // Init litMarker.clear(); vector<int> learnt; int todoNum = _resolve(conflictingClsID, -1, learnt); if( todoNum == -1 ) return vector<int>(); // Resolve and find 1UIP int top = var._top; while( todoNum > 1 ) { while( litMarker.get(var.stk[top].var) == -1 ) --top; int nowNum = _resolve(var.stk[top].src, var.stk[top].var, learnt); if( nowNum == -1 ) return vector<int>(); todoNum += nowNum - 1; --top; } while( litMarker.get(var.stk[top].var) == -1 ) --top; int uip = (var.stk[top].val > 0 ? -var.stk[top].var : var.stk[top].var); learnt.emplace_back(uip); return learnt; } /****************************************************** Implementing Branching Heuristic ******************************************************/ void solver::heuristicInit_no() { staticOrderFrom = 0; staticOrder.resize(maxVarIndex); for(int i=1; i<=maxVarIndex; ++i) staticOrder[i-1] = {i, 1}; } void solver::heuristicInit_MOM() { staticOrderFrom = 0; staticOrder.resize(maxVarIndex); for(int i=1; i<=maxVarIndex; ++i) staticOrder[i-1] = {i, 1}; vector<long long> scorePos(maxVarIndex + 4, 0); vector<long long> scoreNeg(maxVarIndex + 4, 0); vector<long long> score(maxVarIndex + 4, 0); for(auto &cls : clauses) { if( cls.size() > 3 ) continue; for(int i=0; i<cls.size(); ++i) if( cls.getSign(i) ) ++scorePos[cls.getVar(i)]; else ++scoreNeg[cls.getVar(i)]; } for(int i=1; i<=maxVarIndex; ++i) { if( dset.sameSet(i, nowSetID) ) score[i] = scorePos[i] + scoreNeg[i]; else score[i] = -1; } sort(staticOrder.begin(), staticOrder.end(), [&score](const pii &l, const pii &r) { return score[l.first] > score[r.first]; }); for(auto &v : staticOrder) if( scoreNeg[v.first] > scorePos[v.first] ) v.second = 0; } pair<int,int> solver::heuristic_static() { for(int i=staticOrderFrom; i<staticOrder.size(); ++i) if( var.getVal(staticOrder[i].first)==2 && dset.sameSet(staticOrder[i].first, nowSetID) ) { staticOrderFrom = i+1; return staticOrder[i]; } return {-1, 0}; } <commit_msg>Optimize ordering of bcp<commit_after>#include "solver.h" // Solver helper function static bool satisfyAlready(const vector<int> &cls) { unordered_set<int> checker; for(auto &v : cls) { if( checker.find(-v) != checker.end() ) return true; checker.insert(v); } return false; } // Init solver with cnf file void solver::init(const char *filename) { // Init with empty solver *this = solver(); // Get raw clause from cnf file vector< vector<int> > raw; parse_DIMACS_CNF(raw, maxVarIndex, filename); // Init assignment stack var = opStack(maxVarIndex+4); // Init database with all clause which has 2 or more literal in raw database // Eliminate all unit clause and check whether there is empty clause vector<int> unit; for(auto &cls : raw) { if( cls.empty() ) unsatAfterInit = 1; else if( cls.size() == 1 ) unit.emplace_back(cls[0]); else if( !satisfyAlready(cls) ) { clauses.push_back(Clause()); clauses.back().watcher[0] = 0; clauses.back().watcher[1] = (cls.size() >> 1); clauses.back().lit = move(cls); } } // Init two watching check list pos = vector< vector<WatcherInfo> >(maxVarIndex+4); neg = vector< vector<WatcherInfo> >(maxVarIndex+4); int cid = 0; for(auto &cls : clauses) { int id = cls.getWatchVar(0); if( cls.getWatchSign(0) ) pos[id].emplace_back(WatcherInfo(cid, 0)); else neg[id].emplace_back(WatcherInfo(cid, 0)); id = cls.getWatchVar(1); if( cls.getWatchSign(1) ) pos[id].emplace_back(WatcherInfo(cid, 1)); else neg[id].emplace_back(WatcherInfo(cid, 1)); ++cid; } // Assign and run BCP for all unit clause for(auto lit : unit) unsatAfterInit |= !set(abs(lit), lit>0); // Identify independent subproblem via disjoint set dset.init(maxVarIndex+4); for(auto &cls : clauses) { int id = 0; while( id<cls.size() && var.getVal(cls.getVar(id))!=2 ) ++id; for(int i=id+1; i<cls.size(); ++i) if( var.getVal(cls.getVar(i))==2 ) dset.unionSet(cls.getVar(i), cls.getVar(id)); } } // Assign id=val@nowLevel and run BCP recursively bool solver::set(int id, bool val, int src) { // If id is already set, check consistency if( var.getVal(id) != 2 ) { conflictingClsID = -1; return var.getVal(id) == val; } // Set id=val@nowLevel var.set(id, val, nowLevel, src); // Update 2 literal watching vector<WatcherInfo> &lst = (val ? neg[id] : pos[id]); int i = 0; while( i<lst.size() ) { // Update watcher updateClauseWatcher(lst[i]); if( getVal(lst[i]) == 2 || eval(lst[i]) ) { // Watcher reaches an pending/satisfied variable // Push this watcher to corresponding check list if( getSign(lst[i]) ) pos[getVar(lst[i])].emplace_back(lst[i]); else neg[getVar(lst[i])].emplace_back(lst[i]); // Delete this watcher from current check list swap(lst[i], lst.back()); lst.pop_back(); } else { // Watcher run through all clause back to original one // Can't find next literal to watch // b = alternative watcher in this clause WatcherInfo b(lst[i].clsid, lst[i].wid^1); if( getVal(b) == 2 ) { if( !set(getVar(b), getSign(b), lst[i].clsid) ) return false; } else if( !eval(b) ) { conflictingClsID = lst[i].clsid; return false; } ++i; } } // BCP done successfully without conflict return true; } bool solver::solve(int mode) { // Init statistic and start timer statistic.init(); if( unsatAfterInit ) return false; // Init DPLL litMarker.init(maxVarIndex+4); sat = true; nowLevel = 0; // Solve each independent subproblems for(int i=1; i<=maxVarIndex && sat; ++i) { if( dset.findRoot(i) != i ) continue; nowSetID = i; // Init for specific heuristic // This must be done before each subproblems if( mode == HEURISTIC_NO ) { heuristicInit_no(); pickUnassignedVar = &solver::heuristic_static; } else if( mode == HEURISTIC_MOM ) { heuristicInit_MOM(); pickUnassignedVar = &solver::heuristic_static; } else { fprintf(stderr, "Unknown solver mode\n"); exit(1); } sat &= _solve(); } statistic.stopTimer(); return sat; } bool solver::_solve() { // This subproblem startting stack index const int bound = nowLevel; // Main loop for DPLL while( true ) { ++nowLevel; statistic.maxDepth = max(statistic.maxDepth, nowLevel); staticOrderFrom = 0; pii decision = (this->*pickUnassignedVar)(); if( decision.first == -1 ) return true; int vid = decision.first; int sign = decision.second; while( !set(vid, sign) ) { if( conflictingClsID == -1 ) return false; vector<int> learnt = firstUIP(); if( learnt.empty() ) return false; // Determined cronological backtracking int backlv = bound; int towatch = -1; for(int i=learnt.size()-2; i>=0; --i) if( var.getLv(abs(learnt[i])) > backlv ) { backlv = var.getLv(abs(learnt[i])); towatch = i; } // Learn one assignment if( learnt.size() == 1 || backlv == bound ) { ++statistic.backtrackNum; ++statistic.learnAssignment; var.backToLevel(bound); statistic.maxJumpBack = max(statistic.maxJumpBack, nowLevel-bound); nowLevel = bound; int uip = learnt.back(); if( !set(abs(uip), uip>0) ) return false; break; } // Add conflict clause statistic.maxLearntSz = max(statistic.maxLearntSz, int(learnt.size())); clauses.push_back(Clause()); clauses.back().watcher[0] = towatch; clauses.back().watcher[1] = learnt.size() - 1; clauses.back().lit = move(learnt); int cid = clauses.size() - 1; int id = clauses.back().getWatchVar(0); if( clauses.back().getWatchSign(0) ) pos[id].emplace_back(WatcherInfo(cid, 0)); else neg[id].emplace_back(WatcherInfo(cid, 0)); id = clauses.back().getWatchVar(1); if( clauses.back().getWatchSign(1) ) pos[id].emplace_back(WatcherInfo(cid, 1)); else neg[id].emplace_back(WatcherInfo(cid, 1)); ++statistic.backtrackNum; ++statistic.learnCls; statistic.maxJumpBack = max(statistic.maxJumpBack, nowLevel-backlv); var.backToLevel(backlv-1); nowLevel = backlv; vid = var.topNext().var; sign = var.topNext().val; } } return false; } /****************************************************** Implementing Conflict Clause Learning Heuristic ******************************************************/ vector<int> solver::firstUIP() { // Init litMarker.clear(); vector<int> learnt; int todoNum = _resolve(conflictingClsID, -1, learnt); if( todoNum == -1 ) return vector<int>(); // Resolve and find 1UIP int top = var._top; while( todoNum > 1 ) { while( litMarker.get(var.stk[top].var) == -1 ) --top; int nowNum = _resolve(var.stk[top].src, var.stk[top].var, learnt); if( nowNum == -1 ) return vector<int>(); todoNum += nowNum - 1; --top; } while( litMarker.get(var.stk[top].var) == -1 ) --top; int uip = (var.stk[top].val > 0 ? -var.stk[top].var : var.stk[top].var); learnt.emplace_back(uip); return learnt; } /****************************************************** Implementing Branching Heuristic ******************************************************/ void solver::heuristicInit_no() { staticOrderFrom = 0; staticOrder.resize(maxVarIndex); for(int i=1; i<=maxVarIndex; ++i) staticOrder[i-1] = {i, 1}; } void solver::heuristicInit_MOM() { staticOrderFrom = 0; staticOrder.resize(maxVarIndex); for(int i=1; i<=maxVarIndex; ++i) staticOrder[i-1] = {i, 1}; vector<long long> scorePos(maxVarIndex + 4, 0); vector<long long> scoreNeg(maxVarIndex + 4, 0); vector<long long> score(maxVarIndex + 4, 0); for(auto &cls : clauses) { if( cls.size() > 3 ) continue; for(int i=0; i<cls.size(); ++i) if( cls.getSign(i) ) ++scorePos[cls.getVar(i)]; else ++scoreNeg[cls.getVar(i)]; } for(int i=1; i<=maxVarIndex; ++i) { if( dset.sameSet(i, nowSetID) ) score[i] = scorePos[i] + scoreNeg[i]; else score[i] = -1; } sort(staticOrder.begin(), staticOrder.end(), [&score](const pii &l, const pii &r) { return score[l.first] > score[r.first]; }); for(auto &v : staticOrder) if( scoreNeg[v.first] > scorePos[v.first] ) v.second = 0; } pair<int,int> solver::heuristic_static() { for(int i=staticOrderFrom; i<staticOrder.size(); ++i) if( var.getVal(staticOrder[i].first)==2 && dset.sameSet(staticOrder[i].first, nowSetID) ) { staticOrderFrom = i+1; return staticOrder[i]; } return {-1, 0}; } <|endoftext|>
<commit_before>#ifndef STREAM_H #define STREAM_H // from http://www.mail-archive.com/[email protected]/msg03417.html #include <cassert> #include <iostream> #include <fstream> #include <functional> #include <vector> #include <list> #include "google/protobuf/stubs/common.h" #include "google/protobuf/io/zero_copy_stream.h" #include "google/protobuf/io/zero_copy_stream_impl.h" #include "google/protobuf/io/gzip_stream.h" #include "google/protobuf/io/coded_stream.h" namespace stream { // write objects // count should be equal to the number of objects to write // count is written before the objects, but if it is 0, it is not written // if not all objects are written, return false, otherwise true template <typename T> bool write(std::ostream& out, uint64_t count, const std::function<T(uint64_t)>& lambda) { ::google::protobuf::io::ZeroCopyOutputStream *raw_out = new ::google::protobuf::io::OstreamOutputStream(&out); ::google::protobuf::io::GzipOutputStream *gzip_out = new ::google::protobuf::io::GzipOutputStream(raw_out); ::google::protobuf::io::CodedOutputStream *coded_out = new ::google::protobuf::io::CodedOutputStream(gzip_out); auto handle = [](bool ok) { if (!ok) throw std::runtime_error("stream::write: I/O error writing protobuf"); }; // prefix the chunk with the number of objects, if any objects are to be written if(count > 0) { coded_out->WriteVarint64(count); handle(!coded_out->HadError()); } std::string s; uint64_t written = 0; for (uint64_t n = 0; n < count; ++n, ++written) { handle(lambda(n).SerializeToString(&s)); // and prefix each object with its size coded_out->WriteVarint32(s.size()); handle(!coded_out->HadError()); coded_out->WriteRaw(s.data(), s.size()); handle(!coded_out->HadError()); } delete coded_out; delete gzip_out; delete raw_out; return !count || written == count; } template <typename T> bool write_buffered(std::ostream& out, std::vector<T>& buffer, uint64_t buffer_limit) { bool wrote = false; if (buffer.size() >= buffer_limit) { std::function<T(uint64_t)> lambda = [&buffer](uint64_t n) { return buffer.at(n); }; #pragma omp critical (stream_out) wrote = write(out, buffer.size(), lambda); buffer.clear(); } return wrote; } // deserialize the input stream into the objects // skips over groups of objects with count 0 // takes a callback function to be called on the objects, and another to be called per object group. template <typename T> void for_each(std::istream& in, const std::function<void(T&)>& lambda, const std::function<void(uint64_t)>& handle_count) { ::google::protobuf::io::ZeroCopyInputStream *raw_in = new ::google::protobuf::io::IstreamInputStream(&in); ::google::protobuf::io::GzipInputStream *gzip_in = new ::google::protobuf::io::GzipInputStream(raw_in); ::google::protobuf::io::CodedInputStream *coded_in = new ::google::protobuf::io::CodedInputStream(gzip_in); auto handle = [](bool ok) { if (!ok) { throw std::runtime_error("[stream::for_each] obsolete, invalid, or corrupt protobuf input"); } }; uint64_t count; // this loop handles a chunked file with many pieces // such as we might write in a multithreaded process while (coded_in->ReadVarint64((::google::protobuf::uint64*) &count)) { handle_count(count); std::string s; for (uint64_t i = 0; i < count; ++i) { uint32_t msgSize = 0; delete coded_in; coded_in = new ::google::protobuf::io::CodedInputStream(gzip_in); // the messages are prefixed by their size handle(coded_in->ReadVarint32(&msgSize)); if (msgSize) { handle(coded_in->ReadString(&s, msgSize)); T object; handle(object.ParseFromString(s)); lambda(object); } } } delete coded_in; delete gzip_in; delete raw_in; } template <typename T> void for_each(std::istream& in, const std::function<void(T&)>& lambda) { std::function<void(uint64_t)> noop = [](uint64_t) { }; for_each(in, lambda, noop); } template <typename T> void for_each_parallel(std::istream& in, const std::function<void(T&)>& lambda, const std::function<void(uint64_t)>& handle_count) { // objects will be handed off to worker threads in batches of this many const uint64_t batch_size = 1024; // max # of such batches to be holding in memory const uint64_t max_batches_outstanding = 256; // number of batches currently being processed uint64_t batches_outstanding = 0; // this loop handles a chunked file with many pieces // such as we might write in a multithreaded process #pragma omp parallel default(none) shared(in, lambda, handle_count, batches_outstanding) #pragma omp single { auto handle = [](bool retval) -> void { if (!retval) throw std::runtime_error("obsolete, invalid, or corrupt protobuf input"); }; ::google::protobuf::io::ZeroCopyInputStream *raw_in = new ::google::protobuf::io::IstreamInputStream(&in); ::google::protobuf::io::GzipInputStream *gzip_in = new ::google::protobuf::io::GzipInputStream(raw_in); ::google::protobuf::io::CodedInputStream *coded_in = new ::google::protobuf::io::CodedInputStream(gzip_in); std::vector<std::string> *batch = nullptr; // process chunks prefixed by message count uint64_t count; while (coded_in->ReadVarint64((::google::protobuf::uint64*) &count)) { handle_count(count); for (uint64_t i = 0; i < count; ++i) { if (!batch) { batch = new std::vector<std::string>(); batch->reserve(batch_size); } uint32_t msgSize = 0; // the messages are prefixed by their size handle(coded_in->ReadVarint32(&msgSize)); if (msgSize) { // pick off the message (serialized protobuf object) std::string s; handle(coded_in->ReadString(&s, msgSize)); batch->push_back(std::move(s)); } if (batch->size() >= batch_size) { // time to enqueue this batch for processing. first, block if // we've hit max_batches_outstanding. uint64_t b; #pragma omp atomic capture b = ++batches_outstanding; while (b >= max_batches_outstanding) { usleep(1000); #pragma omp atomic read b = batches_outstanding; } // spawn task to process this batch #pragma omp task default(none) firstprivate(batch) shared(batches_outstanding, lambda, handle) { { T object; for (const std::string& s_j : *batch) { // parse protobuf object and invoke lambda on it handle(object.ParseFromString(s_j)); lambda(object); } } // scope object delete batch; #pragma omp atomic update batches_outstanding--; } batch = nullptr; } // recycle the CodedInputStream in order to avoid its byte limit delete coded_in; coded_in = new ::google::protobuf::io::CodedInputStream(gzip_in); } } // process final batch if (batch) { { T object; for (const std::string& s_j : *batch) { handle(object.ParseFromString(s_j)); lambda(object); } } // scope object delete batch; } delete coded_in; delete gzip_in; delete raw_in; } // Don't clean up function locals before tasks finish using them #pragma omp taskwait } template <typename T> void for_each_parallel(std::istream& in, const std::function<void(T&)>& lambda) { std::function<void(uint64_t)> noop = [](uint64_t) { }; for_each_parallel(in, lambda, noop); } } #endif <commit_msg>Remove redundant barrier; it was actually the variable move that fixed things<commit_after>#ifndef STREAM_H #define STREAM_H // from http://www.mail-archive.com/[email protected]/msg03417.html #include <cassert> #include <iostream> #include <fstream> #include <functional> #include <vector> #include <list> #include "google/protobuf/stubs/common.h" #include "google/protobuf/io/zero_copy_stream.h" #include "google/protobuf/io/zero_copy_stream_impl.h" #include "google/protobuf/io/gzip_stream.h" #include "google/protobuf/io/coded_stream.h" namespace stream { // write objects // count should be equal to the number of objects to write // count is written before the objects, but if it is 0, it is not written // if not all objects are written, return false, otherwise true template <typename T> bool write(std::ostream& out, uint64_t count, const std::function<T(uint64_t)>& lambda) { ::google::protobuf::io::ZeroCopyOutputStream *raw_out = new ::google::protobuf::io::OstreamOutputStream(&out); ::google::protobuf::io::GzipOutputStream *gzip_out = new ::google::protobuf::io::GzipOutputStream(raw_out); ::google::protobuf::io::CodedOutputStream *coded_out = new ::google::protobuf::io::CodedOutputStream(gzip_out); auto handle = [](bool ok) { if (!ok) throw std::runtime_error("stream::write: I/O error writing protobuf"); }; // prefix the chunk with the number of objects, if any objects are to be written if(count > 0) { coded_out->WriteVarint64(count); handle(!coded_out->HadError()); } std::string s; uint64_t written = 0; for (uint64_t n = 0; n < count; ++n, ++written) { handle(lambda(n).SerializeToString(&s)); // and prefix each object with its size coded_out->WriteVarint32(s.size()); handle(!coded_out->HadError()); coded_out->WriteRaw(s.data(), s.size()); handle(!coded_out->HadError()); } delete coded_out; delete gzip_out; delete raw_out; return !count || written == count; } template <typename T> bool write_buffered(std::ostream& out, std::vector<T>& buffer, uint64_t buffer_limit) { bool wrote = false; if (buffer.size() >= buffer_limit) { std::function<T(uint64_t)> lambda = [&buffer](uint64_t n) { return buffer.at(n); }; #pragma omp critical (stream_out) wrote = write(out, buffer.size(), lambda); buffer.clear(); } return wrote; } // deserialize the input stream into the objects // skips over groups of objects with count 0 // takes a callback function to be called on the objects, and another to be called per object group. template <typename T> void for_each(std::istream& in, const std::function<void(T&)>& lambda, const std::function<void(uint64_t)>& handle_count) { ::google::protobuf::io::ZeroCopyInputStream *raw_in = new ::google::protobuf::io::IstreamInputStream(&in); ::google::protobuf::io::GzipInputStream *gzip_in = new ::google::protobuf::io::GzipInputStream(raw_in); ::google::protobuf::io::CodedInputStream *coded_in = new ::google::protobuf::io::CodedInputStream(gzip_in); auto handle = [](bool ok) { if (!ok) { throw std::runtime_error("[stream::for_each] obsolete, invalid, or corrupt protobuf input"); } }; uint64_t count; // this loop handles a chunked file with many pieces // such as we might write in a multithreaded process while (coded_in->ReadVarint64((::google::protobuf::uint64*) &count)) { handle_count(count); std::string s; for (uint64_t i = 0; i < count; ++i) { uint32_t msgSize = 0; delete coded_in; coded_in = new ::google::protobuf::io::CodedInputStream(gzip_in); // the messages are prefixed by their size handle(coded_in->ReadVarint32(&msgSize)); if (msgSize) { handle(coded_in->ReadString(&s, msgSize)); T object; handle(object.ParseFromString(s)); lambda(object); } } } delete coded_in; delete gzip_in; delete raw_in; } template <typename T> void for_each(std::istream& in, const std::function<void(T&)>& lambda) { std::function<void(uint64_t)> noop = [](uint64_t) { }; for_each(in, lambda, noop); } template <typename T> void for_each_parallel(std::istream& in, const std::function<void(T&)>& lambda, const std::function<void(uint64_t)>& handle_count) { // objects will be handed off to worker threads in batches of this many const uint64_t batch_size = 1024; // max # of such batches to be holding in memory const uint64_t max_batches_outstanding = 256; // number of batches currently being processed uint64_t batches_outstanding = 0; // this loop handles a chunked file with many pieces // such as we might write in a multithreaded process #pragma omp parallel default(none) shared(in, lambda, handle_count, batches_outstanding) #pragma omp single { auto handle = [](bool retval) -> void { if (!retval) throw std::runtime_error("obsolete, invalid, or corrupt protobuf input"); }; ::google::protobuf::io::ZeroCopyInputStream *raw_in = new ::google::protobuf::io::IstreamInputStream(&in); ::google::protobuf::io::GzipInputStream *gzip_in = new ::google::protobuf::io::GzipInputStream(raw_in); ::google::protobuf::io::CodedInputStream *coded_in = new ::google::protobuf::io::CodedInputStream(gzip_in); std::vector<std::string> *batch = nullptr; // process chunks prefixed by message count uint64_t count; while (coded_in->ReadVarint64((::google::protobuf::uint64*) &count)) { handle_count(count); for (uint64_t i = 0; i < count; ++i) { if (!batch) { batch = new std::vector<std::string>(); batch->reserve(batch_size); } uint32_t msgSize = 0; // the messages are prefixed by their size handle(coded_in->ReadVarint32(&msgSize)); if (msgSize) { // pick off the message (serialized protobuf object) std::string s; handle(coded_in->ReadString(&s, msgSize)); batch->push_back(std::move(s)); } if (batch->size() >= batch_size) { // time to enqueue this batch for processing. first, block if // we've hit max_batches_outstanding. uint64_t b; #pragma omp atomic capture b = ++batches_outstanding; while (b >= max_batches_outstanding) { usleep(1000); #pragma omp atomic read b = batches_outstanding; } // spawn task to process this batch #pragma omp task default(none) firstprivate(batch) shared(batches_outstanding, lambda, handle) { { T object; for (const std::string& s_j : *batch) { // parse protobuf object and invoke lambda on it handle(object.ParseFromString(s_j)); lambda(object); } } // scope object delete batch; #pragma omp atomic update batches_outstanding--; } batch = nullptr; } // recycle the CodedInputStream in order to avoid its byte limit delete coded_in; coded_in = new ::google::protobuf::io::CodedInputStream(gzip_in); } } // process final batch if (batch) { { T object; for (const std::string& s_j : *batch) { handle(object.ParseFromString(s_j)); lambda(object); } } // scope object delete batch; } delete coded_in; delete gzip_in; delete raw_in; } } template <typename T> void for_each_parallel(std::istream& in, const std::function<void(T&)>& lambda) { std::function<void(uint64_t)> noop = [](uint64_t) { }; for_each_parallel(in, lambda, noop); } } #endif <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ /// \file string.cpp //------------------------------------------------------------------------------ /// \brief Implementation of general purpose functions for string processing //------------------------------------------------------------------------------ // Copyright (c) 2010 Serge Aleynikov <[email protected]> // Created: 2010-05-06 //------------------------------------------------------------------------------ /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2010 Serge Aleynikov <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #include <utxx/string.hpp> #include <utxx/print_opts.hpp> namespace utxx { std::string to_bin_string(const char* a_buf, size_t a_sz, bool a_hex, bool a_readable, bool a_eol) { std::stringstream out; const char* begin = a_buf, *end = a_buf + a_sz; print_opts opts = a_hex ? (a_readable ? print_opts::printable_or_hex : print_opts::hex) : (a_readable ? print_opts::printable_or_dec : print_opts::dec); output(out, begin, end, opts, ",", "", "\"", "<<", ">>"); if (a_eol) out << std::endl; return out.str(); } bool wildcard_match(const char* a_input, const char* a_pattern) { // Pattern match a_input against a_pattern, and exit // at the end of the input string for(const char* ip = nullptr, *pp = nullptr; *a_input;) if (*a_pattern == '*') { if (!*++a_pattern) return true; // Reached '*' at the end of pattern pp = a_pattern; // Store matching state right after '*' ip = a_input; } else if ((*a_pattern == *a_input) || (*a_pattern == '?')) { a_pattern++; // Continue successful input match a_input++; } else if (pp) { a_pattern = pp; // Match failed - restore state of pattern after '*' a_input = ++ip; // Advance the input on every match failure } else return false; // Match failed before the first '*' is found // Skip trailing '*' in the pattern, since they don't affect the outcome: while (*a_pattern == '*') a_pattern++; // This point is reached only when the a_input string was fully // exhaused. If at this point the a_pattern is exhaused too ('\0'), // there's a match, otherwise pattern match is incomplete. return !*a_pattern; } } // namespace utxx <commit_msg>Cleanup<commit_after>//------------------------------------------------------------------------------ /// \file string.cpp //------------------------------------------------------------------------------ /// \brief Implementation of general purpose functions for string processing //------------------------------------------------------------------------------ // Copyright (c) 2010 Serge Aleynikov <[email protected]> // Created: 2010-05-06 //------------------------------------------------------------------------------ /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2010 Serge Aleynikov <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #include <utxx/string.hpp> #include <utxx/print_opts.hpp> namespace utxx { std::string to_bin_string(const char* a_buf, size_t a_sz, bool a_hex, bool a_readable, bool a_eol) { std::stringstream out; const char* begin = a_buf, *end = a_buf + a_sz; print_opts opts = a_hex ? (a_readable ? print_opts::printable_or_hex : print_opts::hex) : (a_readable ? print_opts::printable_or_dec : print_opts::dec); output(out, begin, end, opts, ",", "", "\"", "<<", ">>"); if (a_eol) out << std::endl; return out.str(); } bool wildcard_match(const char* a_input, const char* a_pattern) { // Pattern match a_input against a_pattern, and exit // at the end of the input string for(const char* ip = nullptr, *pp = nullptr; *a_input;) if (*a_pattern == '*') { if (!*++a_pattern) return true; // Reached '*' at the end of pattern pp = a_pattern; // Store matching state right after '*' ip = a_input; } else if ((*a_pattern == *a_input) || (*a_pattern == '?')) { a_pattern++; // Continue successful input match a_input++; } else if (pp) { a_pattern = pp; // Match failed - restore state of pattern after '*' a_input = ++ip; // Advance the input on every match failure } else return false; // Match failed before the first '*' is found // Skip trailing '*' in the pattern, since they don't affect the outcome: while (*a_pattern == '*') a_pattern++; // This point is reached only when the a_input string was fully // exhaused. If at this point the a_pattern is exhaused too ('\0'), // there's a match, otherwise pattern match is incomplete. return !*a_pattern; } } // namespace utxx <|endoftext|>
<commit_before>/** * A class which describes the properties and actions of an SSL server socket. * * @date August 22, 2014 * @author Joeri HERMANS * @version 0.1 * * Copyright 2014 Joeri HERMANS * * 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. */ // BEGIN Includes. /////////////////////////////////////////////////// // System dependencies. #include <arpa/inet.h> #include <cassert> #include <cstring> #include <ctime> #include <unistd.h> #include <sys/socket.h> #include <sys/types.h> #include <netdb.h> #include <netinet/in.h> // Application dependencies. #include <ias/network/posix/ssl/posix_ssl_server_socket.h> #include <ias/network/posix/ssl/posix_ssl_socket.h> #include <ias/logger/logger.h> // END Includes. ///////////////////////////////////////////////////// inline void PosixSslServerSocket::initialize( void ) { mSslContext = nullptr; } void PosixSslServerSocket::setFileDescriptor( const int fd ) { mFileDescriptor = fd; } void PosixSslServerSocket::loadCertificates( const std::string & certificateFile, const std::string & keyFile ) { SSL_CTX * sslContext; int rc; sslContext = SSL_CTX_new(SSLv3_server_method()); rc = SSL_CTX_load_verify_locations(sslContext,certificateFile.c_str(),keyFile.c_str()); if( rc <= 0 ) ERR_print_errors_fp(stdout); rc = SSL_CTX_set_default_verify_paths(sslContext); if( rc <= 0 ) ERR_print_errors_fp(stdout); rc = SSL_CTX_use_certificate_file(sslContext,certificateFile.c_str(),SSL_FILETYPE_PEM); if( rc <= 0 ) ERR_print_errors_fp(stdout); rc = SSL_CTX_use_PrivateKey_file(sslContext,keyFile.c_str(),SSL_FILETYPE_PEM); if( rc <= 0 ) ERR_print_errors_fp(stdout); setSslContext(sslContext); } void PosixSslServerSocket::setSslContext( SSL_CTX * sslContext ) { // Checking the precondition. assert( sslContext != nullptr ); mSslContext = sslContext; } Socket * PosixSslServerSocket::allocateSocket( const int fd ) const { Socket * socket; SSL * ssl; // Checking the precondition. assert( fd >= 0 ); ssl = SSL_new(mSslContext); SSL_set_fd(ssl, fd); if( SSL_accept(ssl) <= 0 ) { SSL_free(ssl); close(fd); socket = nullptr; } else { socket = new PosixSslSocket(ssl); } return ( socket ); } PosixSslServerSocket::PosixSslServerSocket( const unsigned int port, SSL_CTX * sslContext ) : ServerSocket(port) { initialize(); setFileDescriptor(-1); setSslContext(sslContext); } PosixSslServerSocket::PosixSslServerSocket( const unsigned int port, const std::string & certificatFile, const std::string & keyFile ) : ServerSocket(port) { initialize(); setFileDescriptor(-1); loadCertificates(certificatFile,keyFile); } PosixSslServerSocket::~PosixSslServerSocket( void ) { stopListening(); } void PosixSslServerSocket::stopListening( void ) { if( isBound() ) { close(mFileDescriptor); setFileDescriptor(-1); SSL_CTX_free(mSslContext); mSslContext = nullptr; } } bool PosixSslServerSocket::bindToPort( void ) { struct addrinfo hints; struct addrinfo * serverInfo; std::string portString; bool bound; int fd; if( isBound() ) { bound = true; } else { bound = false; memset(&hints,0,sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; portString = std::to_string(getPort()); if( getaddrinfo(nullptr,portString.c_str(),&hints,&serverInfo) == 0 ) { fd = socket(serverInfo->ai_family,serverInfo->ai_socktype, serverInfo->ai_protocol); if( fd >= 0 ) { int yes = 1; setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof yes); if( bind(fd,serverInfo->ai_addr,serverInfo->ai_addrlen) == 0 && listen(fd,20) == 0 ) { bound = true; FD_ZERO(&mRfds); FD_SET(fd,&mRfds); setFileDescriptor(fd); } } freeaddrinfo(serverInfo); } } return ( bound ); } bool PosixSslServerSocket::isBound( void ) const { return ( mFileDescriptor >= 0 ); } Socket * PosixSslServerSocket::acceptSocket( void ) { struct sockaddr addr; socklen_t addrLength; Socket * socket; int fd; socket = nullptr; if( isBound() ) { memset(&addr,0,sizeof addr); memset(&addrLength,0,sizeof addrLength); fd = accept(mFileDescriptor,&addr,&addrLength); if( fd >= 0 ) { socket = allocateSocket(fd); } } return ( socket ); } Socket * PosixSslServerSocket::acceptSocket( const std::time_t seconds ) { struct sockaddr addr; socklen_t addrLength; timeval tv; Socket * socket; int fd; socket = nullptr; tv.tv_sec = seconds; tv.tv_usec = 0; FD_ZERO(&mRfds); FD_SET(mFileDescriptor,&mRfds); if( isBound() && select(mFileDescriptor + 1,&mRfds,nullptr,nullptr,&tv) > 0 ) { memset(&addr,0,sizeof addr); memset(&addrLength,0,sizeof addrLength); fd = accept(mFileDescriptor,&addr,&addrLength); if( fd >= 0 ) { socket = allocateSocket(fd); } } return ( socket ); } <commit_msg>Add debugging information.<commit_after>/** * A class which describes the properties and actions of an SSL server socket. * * @date August 22, 2014 * @author Joeri HERMANS * @version 0.1 * * Copyright 2014 Joeri HERMANS * * 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. */ // BEGIN Includes. /////////////////////////////////////////////////// // System dependencies. #include <arpa/inet.h> #include <cassert> #include <cstring> #include <ctime> #include <unistd.h> #include <sys/socket.h> #include <sys/types.h> #include <netdb.h> #include <netinet/in.h> // Application dependencies. #include <ias/network/posix/ssl/posix_ssl_server_socket.h> #include <ias/network/posix/ssl/posix_ssl_socket.h> #include <ias/logger/logger.h> // END Includes. ///////////////////////////////////////////////////// inline void PosixSslServerSocket::initialize( void ) { mSslContext = nullptr; } void PosixSslServerSocket::setFileDescriptor( const int fd ) { mFileDescriptor = fd; } void PosixSslServerSocket::loadCertificates( const std::string & certificateFile, const std::string & keyFile ) { SSL_CTX * sslContext; int rc; sslContext = SSL_CTX_new(SSLv3_server_method()); rc = SSL_CTX_load_verify_locations(sslContext,certificateFile.c_str(),keyFile.c_str()); if( rc <= 0 ) ERR_print_errors_fp(stdout); rc = SSL_CTX_set_default_verify_paths(sslContext); if( rc <= 0 ) ERR_print_errors_fp(stdout); rc = SSL_CTX_use_certificate_file(sslContext,certificateFile.c_str(),SSL_FILETYPE_PEM); if( rc <= 0 ) ERR_print_errors_fp(stdout); rc = SSL_CTX_use_PrivateKey_file(sslContext,keyFile.c_str(),SSL_FILETYPE_PEM); if( rc <= 0 ) ERR_print_errors_fp(stdout); setSslContext(sslContext); } void PosixSslServerSocket::setSslContext( SSL_CTX * sslContext ) { // Checking the precondition. assert( sslContext != nullptr ); mSslContext = sslContext; } Socket * PosixSslServerSocket::allocateSocket( const int fd ) const { Socket * socket; SSL * ssl; // Checking the precondition. assert( fd >= 0 ); ssl = SSL_new(mSslContext); SSL_set_fd(ssl, fd); if( SSL_accept(ssl) <= 0 ) { SSL_free(ssl); close(fd); socket = nullptr; } else { socket = new PosixSslSocket(ssl); } return ( socket ); } PosixSslServerSocket::PosixSslServerSocket( const unsigned int port, SSL_CTX * sslContext ) : ServerSocket(port) { initialize(); setFileDescriptor(-1); setSslContext(sslContext); } PosixSslServerSocket::PosixSslServerSocket( const unsigned int port, const std::string & certificatFile, const std::string & keyFile ) : ServerSocket(port) { initialize(); setFileDescriptor(-1); loadCertificates(certificatFile,keyFile); } PosixSslServerSocket::~PosixSslServerSocket( void ) { stopListening(); } void PosixSslServerSocket::stopListening( void ) { if( isBound() ) { close(mFileDescriptor); setFileDescriptor(-1); SSL_CTX_free(mSslContext); mSslContext = nullptr; } } #include <iostream> bool PosixSslServerSocket::bindToPort( void ) { struct addrinfo hints; struct addrinfo * serverInfo; std::string portString; bool bound; int fd; if( isBound() ) { bound = true; } else { bound = false; memset(&hints,0,sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; portString = std::to_string(getPort()); if( getaddrinfo(nullptr,portString.c_str(),&hints,&serverInfo) == 0 ) { fd = socket(serverInfo->ai_family,serverInfo->ai_socktype, serverInfo->ai_protocol); if( fd >= 0 ) { int yes = 1; setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof yes); if( bind(fd,serverInfo->ai_addr,serverInfo->ai_addrlen) == 0 && listen(fd,20) == 0 ) { bound = true; FD_ZERO(&mRfds); FD_SET(fd,&mRfds); setFileDescriptor(fd); } else { std::cout << "Could not bind to port." << std::endl; } } else { std::cout << "Could not allocate socket." << std::endl; } freeaddrinfo(serverInfo); } } return ( bound ); } bool PosixSslServerSocket::isBound( void ) const { return ( mFileDescriptor >= 0 ); } Socket * PosixSslServerSocket::acceptSocket( void ) { struct sockaddr addr; socklen_t addrLength; Socket * socket; int fd; socket = nullptr; if( isBound() ) { memset(&addr,0,sizeof addr); memset(&addrLength,0,sizeof addrLength); fd = accept(mFileDescriptor,&addr,&addrLength); if( fd >= 0 ) { socket = allocateSocket(fd); } } return ( socket ); } Socket * PosixSslServerSocket::acceptSocket( const std::time_t seconds ) { struct sockaddr addr; socklen_t addrLength; timeval tv; Socket * socket; int fd; socket = nullptr; tv.tv_sec = seconds; tv.tv_usec = 0; FD_ZERO(&mRfds); FD_SET(mFileDescriptor,&mRfds); if( isBound() && select(mFileDescriptor + 1,&mRfds,nullptr,nullptr,&tv) > 0 ) { memset(&addr,0,sizeof addr); memset(&addrLength,0,sizeof addrLength); fd = accept(mFileDescriptor,&addr,&addrLength); if( fd >= 0 ) { socket = allocateSocket(fd); } } return ( socket ); } <|endoftext|>
<commit_before>/* * Copyright (C) 2013 The Android Open Source Project * * 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 "object_registry.h" #include "scoped_thread_state_change.h" namespace art { mirror::Object* const ObjectRegistry::kInvalidObject = reinterpret_cast<mirror::Object*>(1); std::ostream& operator<<(std::ostream& os, const ObjectRegistryEntry& rhs) { os << "ObjectRegistryEntry[" << rhs.jni_reference_type << ",reference=" << rhs.jni_reference << ",count=" << rhs.reference_count << ",id=" << rhs.id << "]"; return os; } ObjectRegistry::ObjectRegistry() : lock_("ObjectRegistry lock", kJdwpObjectRegistryLock), next_id_(1) { } JDWP::RefTypeId ObjectRegistry::AddRefType(mirror::Class* c) { return InternalAdd(c); } JDWP::ObjectId ObjectRegistry::Add(mirror::Object* o) { return InternalAdd(o); } JDWP::ObjectId ObjectRegistry::InternalAdd(mirror::Object* o) { if (o == nullptr) { return 0; } // Call IdentityHashCode here to avoid a lock level violation between lock_ and monitor_lock. int32_t identity_hash_code = o->IdentityHashCode(); ScopedObjectAccessUnchecked soa(Thread::Current()); MutexLock mu(soa.Self(), lock_); ObjectRegistryEntry* entry = nullptr; if (ContainsLocked(soa.Self(), o, identity_hash_code, &entry)) { // This object was already in our map. ++entry->reference_count; } else { entry = new ObjectRegistryEntry; entry->jni_reference_type = JNIWeakGlobalRefType; entry->jni_reference = nullptr; entry->reference_count = 0; entry->id = 0; entry->identity_hash_code = identity_hash_code; object_to_entry_.insert(std::make_pair(identity_hash_code, entry)); // This object isn't in the registry yet, so add it. JNIEnv* env = soa.Env(); jobject local_reference = soa.AddLocalReference<jobject>(o); entry->jni_reference_type = JNIWeakGlobalRefType; entry->jni_reference = env->NewWeakGlobalRef(local_reference); entry->reference_count = 1; entry->id = next_id_++; id_to_entry_.Put(entry->id, entry); env->DeleteLocalRef(local_reference); } return entry->id; } bool ObjectRegistry::Contains(mirror::Object* o, ObjectRegistryEntry** out_entry) { if (o == nullptr) { return false; } // Call IdentityHashCode here to avoid a lock level violation between lock_ and monitor_lock. int32_t identity_hash_code = o->IdentityHashCode(); Thread* self = Thread::Current(); MutexLock mu(self, lock_); return ContainsLocked(self, o, identity_hash_code, out_entry); } bool ObjectRegistry::ContainsLocked(Thread* self, mirror::Object* o, int32_t identity_hash_code, ObjectRegistryEntry** out_entry) { DCHECK(o != nullptr); for (auto it = object_to_entry_.lower_bound(identity_hash_code), end = object_to_entry_.end(); it != end && it->first == identity_hash_code; ++it) { ObjectRegistryEntry* entry = it->second; if (o == self->DecodeJObject(entry->jni_reference)) { if (out_entry != nullptr) { *out_entry = entry; } return true; } } return false; } void ObjectRegistry::Clear() { Thread* self = Thread::Current(); MutexLock mu(self, lock_); VLOG(jdwp) << "Object registry contained " << object_to_entry_.size() << " entries"; // Delete all the JNI references. JNIEnv* env = self->GetJniEnv(); for (const auto& pair : object_to_entry_) { const ObjectRegistryEntry& entry = *pair.second; if (entry.jni_reference_type == JNIWeakGlobalRefType) { env->DeleteWeakGlobalRef(entry.jni_reference); } else { env->DeleteGlobalRef(entry.jni_reference); } } // Clear the maps. object_to_entry_.clear(); id_to_entry_.clear(); } mirror::Object* ObjectRegistry::InternalGet(JDWP::ObjectId id) { Thread* self = Thread::Current(); MutexLock mu(self, lock_); auto it = id_to_entry_.find(id); if (it == id_to_entry_.end()) { return kInvalidObject; } ObjectRegistryEntry& entry = *it->second; return self->DecodeJObject(entry.jni_reference); } jobject ObjectRegistry::GetJObject(JDWP::ObjectId id) { if (id == 0) { return NULL; } Thread* self = Thread::Current(); MutexLock mu(self, lock_); auto it = id_to_entry_.find(id); CHECK(it != id_to_entry_.end()) << id; ObjectRegistryEntry& entry = *it->second; return entry.jni_reference; } void ObjectRegistry::DisableCollection(JDWP::ObjectId id) { Thread* self = Thread::Current(); MutexLock mu(self, lock_); auto it = id_to_entry_.find(id); CHECK(it != id_to_entry_.end()); Promote(*it->second); } void ObjectRegistry::EnableCollection(JDWP::ObjectId id) { Thread* self = Thread::Current(); MutexLock mu(self, lock_); auto it = id_to_entry_.find(id); CHECK(it != id_to_entry_.end()); Demote(*it->second); } void ObjectRegistry::Demote(ObjectRegistryEntry& entry) { if (entry.jni_reference_type == JNIGlobalRefType) { Thread* self = Thread::Current(); JNIEnv* env = self->GetJniEnv(); jobject global = entry.jni_reference; entry.jni_reference = env->NewWeakGlobalRef(entry.jni_reference); entry.jni_reference_type = JNIWeakGlobalRefType; env->DeleteGlobalRef(global); } } void ObjectRegistry::Promote(ObjectRegistryEntry& entry) { if (entry.jni_reference_type == JNIWeakGlobalRefType) { Thread* self = Thread::Current(); JNIEnv* env = self->GetJniEnv(); jobject weak = entry.jni_reference; entry.jni_reference = env->NewGlobalRef(entry.jni_reference); entry.jni_reference_type = JNIGlobalRefType; env->DeleteWeakGlobalRef(weak); } } bool ObjectRegistry::IsCollected(JDWP::ObjectId id) { Thread* self = Thread::Current(); MutexLock mu(self, lock_); auto it = id_to_entry_.find(id); CHECK(it != id_to_entry_.end()); ObjectRegistryEntry& entry = *it->second; if (entry.jni_reference_type == JNIWeakGlobalRefType) { JNIEnv* env = self->GetJniEnv(); return env->IsSameObject(entry.jni_reference, NULL); // Has the jweak been collected? } else { return false; // We hold a strong reference, so we know this is live. } } void ObjectRegistry::DisposeObject(JDWP::ObjectId id, uint32_t reference_count) { Thread* self = Thread::Current(); MutexLock mu(self, lock_); auto it = id_to_entry_.find(id); if (it == id_to_entry_.end()) { return; } ObjectRegistryEntry* entry = it->second; entry->reference_count -= reference_count; if (entry->reference_count <= 0) { JNIEnv* env = self->GetJniEnv(); // Erase the object from the maps. Note object may be null if it's // a weak ref and the GC has cleared it. int32_t hash_code = entry->identity_hash_code; for (auto it = object_to_entry_.lower_bound(hash_code), end = object_to_entry_.end(); it != end && it->first == hash_code; ++it) { if (entry == it->second) { object_to_entry_.erase(it); break; } } if (entry->jni_reference_type == JNIWeakGlobalRefType) { env->DeleteWeakGlobalRef(entry->jni_reference); } else { env->DeleteGlobalRef(entry->jni_reference); } id_to_entry_.erase(id); delete entry; } } } // namespace art <commit_msg>am 0c173466: Merge "Fix memory leak in JDWP object registry"<commit_after>/* * Copyright (C) 2013 The Android Open Source Project * * 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 "object_registry.h" #include "scoped_thread_state_change.h" namespace art { mirror::Object* const ObjectRegistry::kInvalidObject = reinterpret_cast<mirror::Object*>(1); std::ostream& operator<<(std::ostream& os, const ObjectRegistryEntry& rhs) { os << "ObjectRegistryEntry[" << rhs.jni_reference_type << ",reference=" << rhs.jni_reference << ",count=" << rhs.reference_count << ",id=" << rhs.id << "]"; return os; } ObjectRegistry::ObjectRegistry() : lock_("ObjectRegistry lock", kJdwpObjectRegistryLock), next_id_(1) { } JDWP::RefTypeId ObjectRegistry::AddRefType(mirror::Class* c) { return InternalAdd(c); } JDWP::ObjectId ObjectRegistry::Add(mirror::Object* o) { return InternalAdd(o); } JDWP::ObjectId ObjectRegistry::InternalAdd(mirror::Object* o) { if (o == nullptr) { return 0; } // Call IdentityHashCode here to avoid a lock level violation between lock_ and monitor_lock. int32_t identity_hash_code = o->IdentityHashCode(); ScopedObjectAccessUnchecked soa(Thread::Current()); MutexLock mu(soa.Self(), lock_); ObjectRegistryEntry* entry = nullptr; if (ContainsLocked(soa.Self(), o, identity_hash_code, &entry)) { // This object was already in our map. ++entry->reference_count; } else { entry = new ObjectRegistryEntry; entry->jni_reference_type = JNIWeakGlobalRefType; entry->jni_reference = nullptr; entry->reference_count = 0; entry->id = 0; entry->identity_hash_code = identity_hash_code; object_to_entry_.insert(std::make_pair(identity_hash_code, entry)); // This object isn't in the registry yet, so add it. JNIEnv* env = soa.Env(); jobject local_reference = soa.AddLocalReference<jobject>(o); entry->jni_reference_type = JNIWeakGlobalRefType; entry->jni_reference = env->NewWeakGlobalRef(local_reference); entry->reference_count = 1; entry->id = next_id_++; id_to_entry_.Put(entry->id, entry); env->DeleteLocalRef(local_reference); } return entry->id; } bool ObjectRegistry::Contains(mirror::Object* o, ObjectRegistryEntry** out_entry) { if (o == nullptr) { return false; } // Call IdentityHashCode here to avoid a lock level violation between lock_ and monitor_lock. int32_t identity_hash_code = o->IdentityHashCode(); Thread* self = Thread::Current(); MutexLock mu(self, lock_); return ContainsLocked(self, o, identity_hash_code, out_entry); } bool ObjectRegistry::ContainsLocked(Thread* self, mirror::Object* o, int32_t identity_hash_code, ObjectRegistryEntry** out_entry) { DCHECK(o != nullptr); for (auto it = object_to_entry_.lower_bound(identity_hash_code), end = object_to_entry_.end(); it != end && it->first == identity_hash_code; ++it) { ObjectRegistryEntry* entry = it->second; if (o == self->DecodeJObject(entry->jni_reference)) { if (out_entry != nullptr) { *out_entry = entry; } return true; } } return false; } void ObjectRegistry::Clear() { Thread* self = Thread::Current(); MutexLock mu(self, lock_); VLOG(jdwp) << "Object registry contained " << object_to_entry_.size() << " entries"; // Delete all the JNI references. JNIEnv* env = self->GetJniEnv(); for (const auto& pair : object_to_entry_) { const ObjectRegistryEntry* entry = pair.second; if (entry->jni_reference_type == JNIWeakGlobalRefType) { env->DeleteWeakGlobalRef(entry->jni_reference); } else { env->DeleteGlobalRef(entry->jni_reference); } delete entry; } // Clear the maps. object_to_entry_.clear(); id_to_entry_.clear(); } mirror::Object* ObjectRegistry::InternalGet(JDWP::ObjectId id) { Thread* self = Thread::Current(); MutexLock mu(self, lock_); auto it = id_to_entry_.find(id); if (it == id_to_entry_.end()) { return kInvalidObject; } ObjectRegistryEntry& entry = *it->second; return self->DecodeJObject(entry.jni_reference); } jobject ObjectRegistry::GetJObject(JDWP::ObjectId id) { if (id == 0) { return NULL; } Thread* self = Thread::Current(); MutexLock mu(self, lock_); auto it = id_to_entry_.find(id); CHECK(it != id_to_entry_.end()) << id; ObjectRegistryEntry& entry = *it->second; return entry.jni_reference; } void ObjectRegistry::DisableCollection(JDWP::ObjectId id) { Thread* self = Thread::Current(); MutexLock mu(self, lock_); auto it = id_to_entry_.find(id); CHECK(it != id_to_entry_.end()); Promote(*it->second); } void ObjectRegistry::EnableCollection(JDWP::ObjectId id) { Thread* self = Thread::Current(); MutexLock mu(self, lock_); auto it = id_to_entry_.find(id); CHECK(it != id_to_entry_.end()); Demote(*it->second); } void ObjectRegistry::Demote(ObjectRegistryEntry& entry) { if (entry.jni_reference_type == JNIGlobalRefType) { Thread* self = Thread::Current(); JNIEnv* env = self->GetJniEnv(); jobject global = entry.jni_reference; entry.jni_reference = env->NewWeakGlobalRef(entry.jni_reference); entry.jni_reference_type = JNIWeakGlobalRefType; env->DeleteGlobalRef(global); } } void ObjectRegistry::Promote(ObjectRegistryEntry& entry) { if (entry.jni_reference_type == JNIWeakGlobalRefType) { Thread* self = Thread::Current(); JNIEnv* env = self->GetJniEnv(); jobject weak = entry.jni_reference; entry.jni_reference = env->NewGlobalRef(entry.jni_reference); entry.jni_reference_type = JNIGlobalRefType; env->DeleteWeakGlobalRef(weak); } } bool ObjectRegistry::IsCollected(JDWP::ObjectId id) { Thread* self = Thread::Current(); MutexLock mu(self, lock_); auto it = id_to_entry_.find(id); CHECK(it != id_to_entry_.end()); ObjectRegistryEntry& entry = *it->second; if (entry.jni_reference_type == JNIWeakGlobalRefType) { JNIEnv* env = self->GetJniEnv(); return env->IsSameObject(entry.jni_reference, NULL); // Has the jweak been collected? } else { return false; // We hold a strong reference, so we know this is live. } } void ObjectRegistry::DisposeObject(JDWP::ObjectId id, uint32_t reference_count) { Thread* self = Thread::Current(); MutexLock mu(self, lock_); auto it = id_to_entry_.find(id); if (it == id_to_entry_.end()) { return; } ObjectRegistryEntry* entry = it->second; entry->reference_count -= reference_count; if (entry->reference_count <= 0) { JNIEnv* env = self->GetJniEnv(); // Erase the object from the maps. Note object may be null if it's // a weak ref and the GC has cleared it. int32_t hash_code = entry->identity_hash_code; for (auto it = object_to_entry_.lower_bound(hash_code), end = object_to_entry_.end(); it != end && it->first == hash_code; ++it) { if (entry == it->second) { object_to_entry_.erase(it); break; } } if (entry->jni_reference_type == JNIWeakGlobalRefType) { env->DeleteWeakGlobalRef(entry->jni_reference); } else { env->DeleteGlobalRef(entry->jni_reference); } id_to_entry_.erase(id); delete entry; } } } // namespace art <|endoftext|>
<commit_before>#include "SpikeAndSlabPrior.h" #include <SmurffCpp/IO/MatrixIO.h> #include <SmurffCpp/IO/GenericIO.h> #include <SmurffCpp/Utils/Error.h> using namespace smurff; using namespace Eigen; SpikeAndSlabPrior::SpikeAndSlabPrior(std::shared_ptr<Session> session, uint32_t mode) : NormalOnePrior(session, mode, "SpikeAndSlabPrior") { } void SpikeAndSlabPrior::init() { NormalOnePrior::init(); const int K = num_latent(); const int D = num_cols(); const int nview = data().nview(m_mode); THROWERROR_ASSERT(D > 0); Zcol.init(MatrixXd::Zero(K,nview)); W2col.init(MatrixXd::Zero(K,nview)); //-- prior params alpha = ArrayXXd::Ones(K,nview); Zkeep = ArrayXXd::Constant(K, nview, D); r = ArrayXXd::Constant(K,nview,.5); log_alpha = alpha.log(); log_r = - r.log() + (ArrayXXd::Ones(K, nview) - r).log(); } void SpikeAndSlabPrior::update_prior() { const int nview = data().nview(m_mode); const int K = num_latent(); Zkeep = Zcol.combine(); auto W2c = W2col.combine(); // update hyper params (alpha and r) (per view) for(int v=0; v<nview; ++v) { const int D = data().view_size(m_mode, v); r.col(v) = ( Zkeep.col(v).array() + prior_beta ) / ( D + prior_beta * D ) ; auto ww = W2c.col(v).array() / 2 + prior_beta_0; auto tmpz = Zkeep.col(v).array() / 2 + prior_alpha_0 ; alpha.col(v) = tmpz.binaryExpr(ww, [](double a, double b)->double { return rgamma(a, 1/b) + 1e-7; }); } Zcol.reset(); W2col.reset(); log_alpha = alpha.log(); log_r = - r.log() + (ArrayXXd::Ones(K, nview) - r).log(); } void SpikeAndSlabPrior::restore(std::shared_ptr<const StepFile> sf) { const int K = num_latent(); const int nview = data().nview(m_mode); NormalOnePrior::restore(sf); //compute Zcol int d = 0; ArrayXXd Z(ArrayXXd::Zero(K,nview)); ArrayXXd W2(ArrayXXd::Zero(K,nview)); for(int v=0; v<data().nview(m_mode); ++v) { for(int i=0; i<data().view_size(m_mode, v); ++i, ++d) { for(int k=0; k<K; ++k) if (U()(k,d) != 0) Z(k,v)++; W2.col(v) += U().col(d).array().square(); } } THROWERROR_ASSERT(d == num_cols()); Zcol.reset(); W2col.reset(); Zcol.local() = Z; W2col.local() = W2; update_prior(); } std::pair<double, double> SpikeAndSlabPrior::sample_latent(int d, int k, const MatrixXd& XX, const VectorXd& yX) { const int v = data().view(m_mode, d); double mu, lambda; MatrixXd aXX = alpha.matrix().col(v).asDiagonal(); aXX += XX; std::tie(mu, lambda) = NormalOnePrior::sample_latent(d, k, aXX, yX); auto Ucol = U().col(d); double z1 = log_r(k,v) - 0.5 * (lambda * mu * mu - std::log(lambda) + log_alpha(k,v)); double z = 1 / (1 + exp(z1)); double p = rand_unif(0,1); if (Zkeep(k,v) > 0 && p < z) { Zcol.local()(k,v)++; W2col.local()(k,v) += Ucol(k) * Ucol(k); } else { Ucol(k) = .0; } return std::make_pair(mu, lambda); } std::ostream &SpikeAndSlabPrior::status(std::ostream &os, std::string indent) const { const int V = data().nview(m_mode); for(int v=0; v<V; ++v) { int Zcount = (Zkeep.col(v).array() > 0).count(); os << indent << m_name << ": Z[" << v << "] = " << Zcount << "/" << num_latent() << std::endl; } return os; } <commit_msg>FIX: SpikeAndSlab: resize log_alpha and log_r properly<commit_after>#include "SpikeAndSlabPrior.h" #include <SmurffCpp/IO/MatrixIO.h> #include <SmurffCpp/IO/GenericIO.h> #include <SmurffCpp/Utils/Error.h> using namespace smurff; using namespace Eigen; SpikeAndSlabPrior::SpikeAndSlabPrior(std::shared_ptr<Session> session, uint32_t mode) : NormalOnePrior(session, mode, "SpikeAndSlabPrior") { } void SpikeAndSlabPrior::init() { NormalOnePrior::init(); const int K = num_latent(); const int D = num_cols(); const int nview = data().nview(m_mode); THROWERROR_ASSERT(D > 0); Zcol.init(MatrixXd::Zero(K,nview)); W2col.init(MatrixXd::Zero(K,nview)); //-- prior params Zkeep = ArrayXXd::Constant(K, nview, D); alpha = ArrayXXd::Ones(K,nview); log_alpha.resize(K, nview); log_alpha = alpha.log(); r = ArrayXXd::Constant(K,nview,.5); log_r.resize(K, nview); log_r = - r.log() + (ArrayXXd::Ones(K, nview) - r).log(); } void SpikeAndSlabPrior::update_prior() { const int nview = data().nview(m_mode); const int K = num_latent(); Zkeep = Zcol.combine(); auto W2c = W2col.combine(); // update hyper params (alpha and r) (per view) for(int v=0; v<nview; ++v) { const int D = data().view_size(m_mode, v); r.col(v) = ( Zkeep.col(v).array() + prior_beta ) / ( D + prior_beta * D ) ; auto ww = W2c.col(v).array() / 2 + prior_beta_0; auto tmpz = Zkeep.col(v).array() / 2 + prior_alpha_0 ; alpha.col(v) = tmpz.binaryExpr(ww, [](double a, double b)->double { return rgamma(a, 1/b) + 1e-7; }); } Zcol.reset(); W2col.reset(); log_alpha = alpha.log(); log_r = - r.log() + (ArrayXXd::Ones(K, nview) - r).log(); } void SpikeAndSlabPrior::restore(std::shared_ptr<const StepFile> sf) { const int K = num_latent(); const int nview = data().nview(m_mode); NormalOnePrior::restore(sf); //compute Zcol int d = 0; ArrayXXd Z(ArrayXXd::Zero(K,nview)); ArrayXXd W2(ArrayXXd::Zero(K,nview)); for(int v=0; v<data().nview(m_mode); ++v) { for(int i=0; i<data().view_size(m_mode, v); ++i, ++d) { for(int k=0; k<K; ++k) if (U()(k,d) != 0) Z(k,v)++; W2.col(v) += U().col(d).array().square(); } } THROWERROR_ASSERT(d == num_cols()); Zcol.reset(); W2col.reset(); Zcol.local() = Z; W2col.local() = W2; update_prior(); } std::pair<double, double> SpikeAndSlabPrior::sample_latent(int d, int k, const MatrixXd& XX, const VectorXd& yX) { const int v = data().view(m_mode, d); double mu, lambda; MatrixXd aXX = alpha.matrix().col(v).asDiagonal(); aXX += XX; std::tie(mu, lambda) = NormalOnePrior::sample_latent(d, k, aXX, yX); auto Ucol = U().col(d); double z1 = log_r(k,v) - 0.5 * (lambda * mu * mu - std::log(lambda) + log_alpha(k,v)); double z = 1 / (1 + exp(z1)); double p = rand_unif(0,1); if (Zkeep(k,v) > 0 && p < z) { Zcol.local()(k,v)++; W2col.local()(k,v) += Ucol(k) * Ucol(k); } else { Ucol(k) = .0; } return std::make_pair(mu, lambda); } std::ostream &SpikeAndSlabPrior::status(std::ostream &os, std::string indent) const { const int V = data().nview(m_mode); for(int v=0; v<V; ++v) { int Zcount = (Zkeep.col(v).array() > 0).count(); os << indent << m_name << ": Z[" << v << "] = " << Zcount << "/" << num_latent() << std::endl; } return os; } <|endoftext|>
<commit_before><commit_msg>coverity#1266492 Untrusted value as argument<commit_after><|endoftext|>
<commit_before>#/***************************************************************************** * SV_Bedpe.cpp * (c) 2012 - Ryan M. Layer * Hall Laboratory * Quinlan Laboratory * Department of Computer Science * Department of Biochemistry and Molecular Genetics * Department of Public Health Sciences and Center for Public Health Genomics, * University of Virginia * [email protected] * * Licenced under the GNU General Public License 2.0 license. * ***************************************************************************/ #include "BamAncillary.h" using namespace BamTools; #include "SV_BedpeReader.h" #include "SV_BreakPoint.h" #include "SV_Bedpe.h" #include "log_space.h" #include "bedFilePE.h" #include <iostream> #include <algorithm> #include <string> #include <math.h> using namespace std; //{{{ SV_Bedpe:: SV_Bedpe(const BEDPE *bedpeEntry) SV_Bedpe:: SV_Bedpe(const BEDPE *bedpeEntry, int _weight, int _ev_id, SV_BedpeReader *_reader) { reader = _reader; ev_id = _ev_id; struct interval tmp_a, tmp_b; tmp_a.start = bedpeEntry->start1; tmp_a.end = bedpeEntry->end1 - 1; tmp_a.chr = bedpeEntry->chrom1; tmp_a.strand = bedpeEntry->strand1[0]; tmp_b.start = bedpeEntry->start2; tmp_b.end = bedpeEntry->end2 - 1; tmp_b.chr = bedpeEntry->chrom2; tmp_b.strand = bedpeEntry->strand2[0]; if ( tmp_a.chr.compare(tmp_b.chr) > 0 ) { side_l = tmp_a; side_r = tmp_b; } else if ( tmp_a.chr.compare(tmp_b.chr) < 0 ) { side_l = tmp_b; side_r = tmp_a; } else { // == if (tmp_a.start > tmp_b.start) { side_l = tmp_b; side_r = tmp_a; } else { side_l = tmp_a; side_r = tmp_b; } } vector<string>::const_iterator it; type = -1; for (it = bedpeEntry->fields.begin(); it != bedpeEntry->fields.end(); ++it) { if ( it->find("TYPE:") == 0 ) { string type_string = it->substr(5,it->length() - 5); if (type_string.compare("DELETION") == 0) { type = SV_BreakPoint::DELETION; } else if (type_string.compare("DUPLICATION") == 0) { type = SV_BreakPoint::DUPLICATION; } else if (type_string.compare("INVERSION") == 0) { type = SV_BreakPoint::INVERSION; } else { cerr << "ERROR IN BEDPE FILE. TYPE \""<< type_string << "\" not supported (DELETION,DUPLICATION,INVERSION)" << endl; abort(); } } } if (type == -1) { cerr << "ERROR IN BEDPE FILE. Either no TYPE field. " << endl; abort(); } weight = _weight; } //}}} //{{{ ostream& operator << (ostream& out, const SV_Pair& p) ostream& operator << (ostream& out, const SV_Bedpe& p) { out << p.side_l.chr << "," << p.side_l.start << "," << p.side_l.end << "," << p.side_l.strand << "\t" << p.side_r.chr << "," << p.side_r.start << "," << p.side_r.end << "," << p.side_r.strand; return out; } //}}} //{{{ SV_BreakPoint* SV_Pair:: get_bp() SV_BreakPoint* SV_Bedpe:: get_bp() { // Make a new break point SV_BreakPoint *new_bp = new SV_BreakPoint(this); set_bp_interval_start_end(&(new_bp->interval_l), &side_l, &side_r, 0, reader->distro_size); set_bp_interval_start_end(&(new_bp->interval_r), &side_r, &side_l, 0, reader->distro_size); //set_bp_interval_probability(&(new_bp->interval_l)); //set_bp_interval_probability(&(new_bp->interval_r)); new_bp->interval_r.p = NULL; new_bp->interval_l.p = NULL; new_bp->type = type; new_bp->weight = weight; return new_bp; } //}}} //{{{ void SV_Bedpe:: set_bp_interval_start_end(struct breakpoint_interval *i, void SV_Bedpe:: set_bp_interval_start_end(struct breakpoint_interval *i, struct interval *target_interval, struct interval *target_pair, int back_distance, int distro_size) { i->i.chr = target_interval->chr; i->i.strand = target_interval->strand; i->i.start = target_interval->start; i->i.end = target_interval->end; i->i.start_clip = 0; } //}}} //{{{ log_space* SV_Bedpe:: get_bp_interval_probability(char strand) log_space* SV_Bedpe:: get_bp_interval_probability(char strand, int distro_size, double *distro) { CHR_POS size = distro_size; log_space *tmp_p = (log_space *) malloc(size * sizeof(log_space)); CHR_POS j; for (j = 0; j < size; ++j) { if (strand == '+') tmp_p[j] = get_ls(distro[j]); else tmp_p[(size - 1) - j] = get_ls(distro[j]); } return tmp_p; } //}}} //{{{ void SV_Pair:: print_evidence() void SV_Bedpe:: print_evidence() { print_bedpe(0); } //}}} //{{{ void SV_Bedpe:: print_bedpe(int score) void SV_Bedpe:: print_bedpe(int score) { // use the address of the current object as the id string sep = "\t"; cout << side_l.chr << sep << side_l.start << sep << (side_l.end + 1) << sep << side_r.chr << sep << side_r.start << sep<< (side_r.end + 1) << sep<< this << sep << score << sep << side_l.strand << "\t" << side_r.strand << endl; } //}}} //{{{ void SV_Bedpe:: process_bedpe(const BEDPE *bedpeEntry, void SV_Bedpe:: process_bedpe(const BEDPE *bedpeEntry, UCSCBins<SV_BreakPoint*> &r_bin, int weight, int ev_id, SV_BedpeReader *reader) { SV_Bedpe *new_bedpe = new SV_Bedpe(bedpeEntry, weight, ev_id, reader); SV_BreakPoint *new_bp = new_bedpe->get_bp(); new_bp->cluster(r_bin); } //}}} //{{{ string SV_Bedpe:: evidence_type() string SV_Bedpe:: evidence_type() { return "bedpe"; } //}}} //{{{ void SV_Pair:: set_interval_probability() void SV_Bedpe:: set_bp_interval_probability(struct breakpoint_interval *i) { CHR_POS size = i->i.end - i->i.start + 1; log_space *tmp_p = (log_space *) malloc(size * sizeof(log_space)); //log_space *src_p; double v = 1.0 / ((double )size); //int offset = i->i.start_clip; CHR_POS j; for (j = 0; j < size; ++j) { //tmp_p[j] = src_p[j + offset]; tmp_p[j] = get_ls(v); } i->p = tmp_p; } //}}} <commit_msg>Add translocations to BEDPE<commit_after>#/***************************************************************************** * SV_Bedpe.cpp * (c) 2012 - Ryan M. Layer * Hall Laboratory * Quinlan Laboratory * Department of Computer Science * Department of Biochemistry and Molecular Genetics * Department of Public Health Sciences and Center for Public Health Genomics, * University of Virginia * [email protected] * * Licenced under the GNU General Public License 2.0 license. * ***************************************************************************/ #include "BamAncillary.h" using namespace BamTools; #include "SV_BedpeReader.h" #include "SV_BreakPoint.h" #include "SV_Bedpe.h" #include "log_space.h" #include "bedFilePE.h" #include <iostream> #include <algorithm> #include <string> #include <math.h> using namespace std; //{{{ SV_Bedpe:: SV_Bedpe(const BEDPE *bedpeEntry) SV_Bedpe:: SV_Bedpe(const BEDPE *bedpeEntry, int _weight, int _ev_id, SV_BedpeReader *_reader) { reader = _reader; ev_id = _ev_id; struct interval tmp_a, tmp_b; tmp_a.start = bedpeEntry->start1; tmp_a.end = bedpeEntry->end1 - 1; tmp_a.chr = bedpeEntry->chrom1; tmp_a.strand = bedpeEntry->strand1[0]; tmp_b.start = bedpeEntry->start2; tmp_b.end = bedpeEntry->end2 - 1; tmp_b.chr = bedpeEntry->chrom2; tmp_b.strand = bedpeEntry->strand2[0]; if ( tmp_a.chr.compare(tmp_b.chr) > 0 ) { side_l = tmp_a; side_r = tmp_b; } else if ( tmp_a.chr.compare(tmp_b.chr) < 0 ) { side_l = tmp_b; side_r = tmp_a; } else { // == if (tmp_a.start > tmp_b.start) { side_l = tmp_b; side_r = tmp_a; } else { side_l = tmp_a; side_r = tmp_b; } } vector<string>::const_iterator it; type = -1; for (it = bedpeEntry->fields.begin(); it != bedpeEntry->fields.end(); ++it) { if ( it->find("TYPE:") == 0 ) { string type_string = it->substr(5,it->length() - 5); if (type_string.compare("DELETION") == 0) { type = SV_BreakPoint::DELETION; } else if (type_string.compare("DUPLICATION") == 0) { type = SV_BreakPoint::DUPLICATION; } else if (type_string.compare("INVERSION") == 0) { type = SV_BreakPoint::INVERSION; } else if (type_string.compare("TRANSLOCATION") == 0) { type = SV_BreakPoint::TRANSLOCATION; } else { cerr << "ERROR IN BEDPE FILE. TYPE \""<< type_string << "\" not supported " << "(DELETION,DUPLICATION,INVERSION,TRANSLOCATION)" << endl; abort(); } } } if (type == -1) { cerr << "ERROR IN BEDPE FILE. Either no TYPE field. " << endl; abort(); } weight = _weight; } //}}} //{{{ ostream& operator << (ostream& out, const SV_Pair& p) ostream& operator << (ostream& out, const SV_Bedpe& p) { out << p.side_l.chr << "," << p.side_l.start << "," << p.side_l.end << "," << p.side_l.strand << "\t" << p.side_r.chr << "," << p.side_r.start << "," << p.side_r.end << "," << p.side_r.strand; return out; } //}}} //{{{ SV_BreakPoint* SV_Pair:: get_bp() SV_BreakPoint* SV_Bedpe:: get_bp() { // Make a new break point SV_BreakPoint *new_bp = new SV_BreakPoint(this); set_bp_interval_start_end(&(new_bp->interval_l), &side_l, &side_r, 0, reader->distro_size); set_bp_interval_start_end(&(new_bp->interval_r), &side_r, &side_l, 0, reader->distro_size); //set_bp_interval_probability(&(new_bp->interval_l)); //set_bp_interval_probability(&(new_bp->interval_r)); new_bp->interval_r.p = NULL; new_bp->interval_l.p = NULL; new_bp->type = type; new_bp->weight = weight; return new_bp; } //}}} //{{{ void SV_Bedpe:: set_bp_interval_start_end(struct breakpoint_interval *i, void SV_Bedpe:: set_bp_interval_start_end(struct breakpoint_interval *i, struct interval *target_interval, struct interval *target_pair, int back_distance, int distro_size) { i->i.chr = target_interval->chr; i->i.strand = target_interval->strand; i->i.start = target_interval->start; i->i.end = target_interval->end; i->i.start_clip = 0; } //}}} //{{{ log_space* SV_Bedpe:: get_bp_interval_probability(char strand) log_space* SV_Bedpe:: get_bp_interval_probability(char strand, int distro_size, double *distro) { CHR_POS size = distro_size; log_space *tmp_p = (log_space *) malloc(size * sizeof(log_space)); CHR_POS j; for (j = 0; j < size; ++j) { if (strand == '+') tmp_p[j] = get_ls(distro[j]); else tmp_p[(size - 1) - j] = get_ls(distro[j]); } return tmp_p; } //}}} //{{{ void SV_Pair:: print_evidence() void SV_Bedpe:: print_evidence() { print_bedpe(0); } //}}} //{{{ void SV_Bedpe:: print_bedpe(int score) void SV_Bedpe:: print_bedpe(int score) { // use the address of the current object as the id string sep = "\t"; cout << side_l.chr << sep << side_l.start << sep << (side_l.end + 1) << sep << side_r.chr << sep << side_r.start << sep<< (side_r.end + 1) << sep<< this << sep << score << sep << side_l.strand << "\t" << side_r.strand << endl; } //}}} //{{{ void SV_Bedpe:: process_bedpe(const BEDPE *bedpeEntry, void SV_Bedpe:: process_bedpe(const BEDPE *bedpeEntry, UCSCBins<SV_BreakPoint*> &r_bin, int weight, int ev_id, SV_BedpeReader *reader) { SV_Bedpe *new_bedpe = new SV_Bedpe(bedpeEntry, weight, ev_id, reader); SV_BreakPoint *new_bp = new_bedpe->get_bp(); new_bp->cluster(r_bin); } //}}} //{{{ string SV_Bedpe:: evidence_type() string SV_Bedpe:: evidence_type() { return "bedpe"; } //}}} //{{{ void SV_Pair:: set_interval_probability() void SV_Bedpe:: set_bp_interval_probability(struct breakpoint_interval *i) { CHR_POS size = i->i.end - i->i.start + 1; log_space *tmp_p = (log_space *) malloc(size * sizeof(log_space)); //log_space *src_p; double v = 1.0 / ((double )size); //int offset = i->i.start_clip; CHR_POS j; for (j = 0; j < size; ++j) { //tmp_p[j] = src_p[j + offset]; tmp_p[j] = get_ls(v); } i->p = tmp_p; } //}}} <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <stdint.h> #include <math.h> // For lightweight communication with the FPGA: #define FPGA_MANAGER_BASE 0xFF706000 #define FPGA_GPO_OFFSET 0x10 #define FPGA_GPI_OFFSET 0x14 // HPS-to-FPGA: #define H2F_DATA_READY (1 << 0) // FPGA-to-HPS: #define F2H_BUSY (1 << 0) // Shared memory addresses: #define BASE 0x38000000 #define RAM_SIZE 0x40000000 #define COLOR_BUFFER_1_OFFSET 0 #define BUFFER_SIZE (800*480*4) #define COLOR_BUFFER_2_OFFSET (COLOR_BUFFER_1_OFFSET + BUFFER_SIZE) #define Z_BUFFER_OFFSET (COLOR_BUFFER_2_OFFSET + BUFFER_SIZE) #define PROTOCOL_BUFFER_OFFSET (Z_BUFFER_OFFSET + BUFFER_SIZE) // Protocol command number: #define CMD_CLEAR 1 #define CMD_ZCLEAR 2 #define CMD_PATTERN 3 #define CMD_DRAW 4 #define CMD_BITMAP 5 #define CMD_SWAP 6 #define CMD_END 7 // Draw type: #define DRAW_TRIANGLES 0 #define DRAW_LINES 1 #define DRAW_POINTS 2 #define DRAW_LINE_STRIP 3 #define DRAW_TRIANGLE_STRIP 5 #define DRAW_TRIANGLE_FAN 6 void cmd_clear(volatile uint64_t **p, uint8_t red, uint8_t green, uint8_t blue) { *(*p)++ = CMD_CLEAR | ((uint64_t) red << 56) | ((uint64_t) green << 48) | ((uint64_t) blue << 40); } void cmd_draw(volatile uint64_t **p, int type, int count) { *(*p)++ = CMD_DRAW | ((uint64_t) type << 8) | ((uint64_t) count << 16); } void vertex(volatile uint64_t **p, int x, int y, int z, uint8_t red, uint8_t green, uint8_t blue) { *(*p)++ = ((uint64_t) x << 2) | ((uint64_t) y << 15) | ((uint64_t) red << 56) | ((uint64_t) green << 48) | ((uint64_t) blue << 40); } void cmd_swap(volatile uint64_t **p) { *(*p)++ = CMD_SWAP; } void cmd_end(volatile uint64_t **p) { *(*p)++ = CMD_END; } int main() { int dev_mem = open("/dev/mem", O_RDWR); if(dev_mem == 0) { perror("open"); exit(EXIT_FAILURE); } // Get access to lightweight FPGA communication. uint8_t *fpga_manager_base = (uint8_t *) mmap(0, 64, PROT_READ | PROT_WRITE, MAP_SHARED, dev_mem, FPGA_MANAGER_BASE); if(fpga_manager_base == 0) { perror("mmap for fpga manager base"); exit(EXIT_FAILURE); } volatile uint32_t *gpo = (uint32_t*)(fpga_manager_base + FPGA_GPO_OFFSET); volatile uint32_t *gpi = (uint32_t*)(fpga_manager_base + FPGA_GPI_OFFSET); // Get access to the various RAM buffers. uint8_t *buffers_base = (uint8_t *) mmap(0, RAM_SIZE - BASE, PROT_READ | PROT_WRITE, MAP_SHARED, dev_mem, BASE); if(buffers_base == 0) { perror("mmap for buffers"); exit(EXIT_FAILURE); } volatile uint64_t *protocol_buffer = (uint64_t *) (buffers_base + PROTOCOL_BUFFER_OFFSET); *gpo = 0; int counter = 0; while (1) { // Start of frame. // Write protocol buffer. printf("Writing protocol buffer.\n"); volatile uint64_t *p = protocol_buffer; cmd_clear(&p, (counter & 0x04) ? 32 : 0, (counter & 0x02) ? 32 : 0, (counter & 0x01) ? 32 : 0); cmd_draw(&p, DRAW_TRIANGLES, 1); vertex(&p, 800/2 + (int) (200*sin(counter/10.0)), 450/2 + (int) (200*cos(counter/10.0)), 0, 50, 100, 150); vertex(&p, 800/2 + (int) (200*sin(counter/10.0 + M_PI*2/3)), 450/2 + (int) (200*cos(counter/10.0 + M_PI*2/3)), 0, 50, 100, 150); vertex(&p, 800/2 + (int) (200*sin(counter/10.0 + M_PI*4/3)), 450/2 + (int) (200*cos(counter/10.0 + M_PI*4/3)), 0, 50, 100, 150); cmd_swap(&p); cmd_end(&p); printf(" Wrote %d words:\n", p - protocol_buffer); for (volatile uint64_t *t = protocol_buffer; t < p; t++) { printf(" 0x%016llX\n", *t); } // Tell FPGA that our data is ready. printf("Telling FPGA that the data is ready.\n"); *gpo |= H2F_DATA_READY; // Wait until we find out that it has heard us. printf("Waiting for FPGA to get busy.\n"); while ((*gpi & F2H_BUSY) == 0) { // Busy loop. } // Let FPGA know that we know that it's busy. printf("Telling FPGA that we know it's busy.\n"); *gpo &= ~H2F_DATA_READY; // Wait until it's done rasterizing. printf("Waiting for FPGA to finish rasterizing.\n"); while ((*gpi & F2H_BUSY) != 0) { // Busy loop. } usleep(1000*100); counter++; } exit(EXIT_SUCCESS); } <commit_msg>Turn of debug printf and usleep() now that we block on swap buffers.<commit_after>#include <cstdio> #include <cstdlib> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <stdint.h> #include <math.h> #undef DEBUG_PRINT // For lightweight communication with the FPGA: #define FPGA_MANAGER_BASE 0xFF706000 #define FPGA_GPO_OFFSET 0x10 #define FPGA_GPI_OFFSET 0x14 // HPS-to-FPGA: #define H2F_DATA_READY (1 << 0) // FPGA-to-HPS: #define F2H_BUSY (1 << 0) // Shared memory addresses: #define BASE 0x38000000 #define RAM_SIZE 0x40000000 #define COLOR_BUFFER_1_OFFSET 0 #define BUFFER_SIZE (800*480*4) #define COLOR_BUFFER_2_OFFSET (COLOR_BUFFER_1_OFFSET + BUFFER_SIZE) #define Z_BUFFER_OFFSET (COLOR_BUFFER_2_OFFSET + BUFFER_SIZE) #define PROTOCOL_BUFFER_OFFSET (Z_BUFFER_OFFSET + BUFFER_SIZE) // Protocol command number: #define CMD_CLEAR 1 #define CMD_ZCLEAR 2 #define CMD_PATTERN 3 #define CMD_DRAW 4 #define CMD_BITMAP 5 #define CMD_SWAP 6 #define CMD_END 7 // Draw type: #define DRAW_TRIANGLES 0 #define DRAW_LINES 1 #define DRAW_POINTS 2 #define DRAW_LINE_STRIP 3 #define DRAW_TRIANGLE_STRIP 5 #define DRAW_TRIANGLE_FAN 6 void cmd_clear(volatile uint64_t **p, uint8_t red, uint8_t green, uint8_t blue) { *(*p)++ = CMD_CLEAR | ((uint64_t) red << 56) | ((uint64_t) green << 48) | ((uint64_t) blue << 40); } void cmd_draw(volatile uint64_t **p, int type, int count) { *(*p)++ = CMD_DRAW | ((uint64_t) type << 8) | ((uint64_t) count << 16); } void vertex(volatile uint64_t **p, int x, int y, int z, uint8_t red, uint8_t green, uint8_t blue) { *(*p)++ = ((uint64_t) x << 2) | ((uint64_t) y << 15) | ((uint64_t) red << 56) | ((uint64_t) green << 48) | ((uint64_t) blue << 40); } void cmd_swap(volatile uint64_t **p) { *(*p)++ = CMD_SWAP; } void cmd_end(volatile uint64_t **p) { *(*p)++ = CMD_END; } int main() { int dev_mem = open("/dev/mem", O_RDWR); if(dev_mem == 0) { perror("open"); exit(EXIT_FAILURE); } // Get access to lightweight FPGA communication. uint8_t *fpga_manager_base = (uint8_t *) mmap(0, 64, PROT_READ | PROT_WRITE, MAP_SHARED, dev_mem, FPGA_MANAGER_BASE); if(fpga_manager_base == 0) { perror("mmap for fpga manager base"); exit(EXIT_FAILURE); } volatile uint32_t *gpo = (uint32_t*)(fpga_manager_base + FPGA_GPO_OFFSET); volatile uint32_t *gpi = (uint32_t*)(fpga_manager_base + FPGA_GPI_OFFSET); // Get access to the various RAM buffers. uint8_t *buffers_base = (uint8_t *) mmap(0, RAM_SIZE - BASE, PROT_READ | PROT_WRITE, MAP_SHARED, dev_mem, BASE); if(buffers_base == 0) { perror("mmap for buffers"); exit(EXIT_FAILURE); } volatile uint64_t *protocol_buffer = (uint64_t *) (buffers_base + PROTOCOL_BUFFER_OFFSET); *gpo = 0; int counter = 0; while (1) { // Start of frame. // Write protocol buffer. #ifdef DEBUG_PRINT printf("Writing protocol buffer.\n"); #endif volatile uint64_t *p = protocol_buffer; if (0) { cmd_clear(&p, (counter & 0x04) ? 255 : 0, (counter & 0x02) ? 255 : 0, (counter & 0x01) ? 255 : 0); } else { cmd_clear(&p, 0, 0, 0); } cmd_draw(&p, DRAW_TRIANGLES, 1); vertex(&p, 800/2 + (int) (200*sin(counter/10.0)), 450/2 + (int) (200*cos(counter/10.0)), 0, 50, 100, 150); vertex(&p, 800/2 + (int) (200*sin(counter/10.0 + M_PI*2/3)), 450/2 + (int) (200*cos(counter/10.0 + M_PI*2/3)), 0, 50, 100, 150); vertex(&p, 800/2 + (int) (200*sin(counter/10.0 + M_PI*4/3)), 450/2 + (int) (200*cos(counter/10.0 + M_PI*4/3)), 0, 50, 100, 150); cmd_swap(&p); cmd_end(&p); #ifdef DEBUG_PRINT printf(" Wrote %d words:\n", p - protocol_buffer); for (volatile uint64_t *t = protocol_buffer; t < p; t++) { printf(" 0x%016llX\n", *t); } #endif // Tell FPGA that our data is ready. #ifdef DEBUG_PRINT printf("Telling FPGA that the data is ready.\n"); #endif *gpo |= H2F_DATA_READY; // Wait until we find out that it has heard us. #ifdef DEBUG_PRINT printf("Waiting for FPGA to get busy.\n"); #endif while ((*gpi & F2H_BUSY) == 0) { // Busy loop. } // Let FPGA know that we know that it's busy. #ifdef DEBUG_PRINT printf("Telling FPGA that we know it's busy.\n"); #endif *gpo &= ~H2F_DATA_READY; // Wait until it's done rasterizing. #ifdef DEBUG_PRINT printf("Waiting for FPGA to finish rasterizing.\n"); #endif while ((*gpi & F2H_BUSY) != 0) { // Busy loop. } // usleep(1000*100); counter++; } exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <iostream> #include "Stroika/Foundation/Characters/String2Float.h" #include "Stroika/Foundation/DataExchange/JSON/Writer.h" #include "Stroika/Foundation/Execution/CommandLine.h" #if qPlatform_POSIX #include "Stroika/Foundation/Execution/SignalHandlers.h" #endif #include "Stroika/Foundation/Execution/WaitableEvent.h" #include "Stroika/Foundation/Memory/Optional.h" #include "Stroika/Foundation/Streams/BasicBinaryOutputStream.h" #include "Stroika/Frameworks/SystemPerformance/AllInstruments.h" #include "Stroika/Frameworks/SystemPerformance/Capturer.h" #include "Stroika/Frameworks/SystemPerformance/Measurement.h" using namespace std; using namespace Stroika::Foundation; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::SystemPerformance; using Characters::Character; using Characters::String; using Containers::Sequence; using Memory::Optional; namespace { string Serialize_ (VariantValue v, bool oneLineMode) { Streams::BasicBinaryOutputStream out; DataExchange::JSON::Writer ().Write (v, out); // strip CRLF - so shows up on one line String result = String::FromUTF8 (out.As<string> ()); if (oneLineMode) { result = result.StripAll ([] (Character c)-> bool { return c == '\n' or c == '\r';}); } return result.AsNarrowSDKString (); } } int main (int argc, const char* argv[]) { #if qPlatform_POSIX // Many performance instruments use pipes // @todo - REVIEW IF REALLY NEEDED AND WHY? SO LONG AS NO FAIL SHOULDNT BE? // --LGP 2014-02-05 Execution::SignalHandlerRegistry::Get ().SetSignalHandlers (SIGPIPE, Execution::SignalHandlerRegistry::kIGNORED); #endif bool printUsage = false; bool printNames = false; bool oneLineMode = false; Time::DurationSecondsType runFor = 30.0; Set<InstrumentNameType> run; Sequence<String> args = Execution::ParseCommandLine (argc, argv); for (auto argi = args.begin (); argi != args.end(); ++argi) { if (Execution::MatchesCommandLineArgument (*argi, L"h")) { printUsage = true; } if (Execution::MatchesCommandLineArgument (*argi, L"l")) { printNames = true; } if (Execution::MatchesCommandLineArgument (*argi, L"o")) { oneLineMode = true; } if (Execution::MatchesCommandLineArgument (*argi, L"r")) { ++argi; if (argi != args.end ()) { run.Add (*argi); } else { cerr << "Expected arg to -r" << endl; return EXIT_FAILURE; } } if (Execution::MatchesCommandLineArgument (*argi, L"t")) { ++argi; if (argi != args.end ()) { runFor = Characters::String2Float<Time::DurationSecondsType> (*argi); } else { cerr << "Expected arg to -t" << endl; return EXIT_FAILURE; } } } if (printUsage) { cerr << "Usage: SystemPerformanceClient [-h] [-l] [-f] [-r RUN-INSTRUMENT]*" << endl; cerr << " -h prints this help" << endl; cerr << " -o prints instrument results (with newlines stripped)" << endl; cerr << " -l prints only the instrument names" << endl; cerr << " -r runs the given instrument (it can be repeated)" << endl; cerr << " -t time to run for (if zero dont use capturer code)" << endl; return EXIT_SUCCESS; } try { if (printNames) { cout << "Instrument:" << endl; for (Instrument i : SystemPerformance::GetAllInstruments ()) { cout << " " << i.fInstrumentName.GetPrintName ().AsNarrowSDKString () << endl; // print measurements too? } return EXIT_SUCCESS; } bool useCapturer = runFor > 0; if (useCapturer) { /* * Demo using capturer */ Capturer capturer; { CaptureSet cs; cs.SetRunPeriod (Duration (15)); for (Instrument i : SystemPerformance::GetAllInstruments ()) { if (not run.empty ()) { if (not run.Contains (i.fInstrumentName)) { continue; } } cs.AddInstrument (i); } capturer.AddCaptureSet (cs); } capturer.AddMeasurementsCallback ([oneLineMode] (MeasurementSet ms) { cout << " Measured-At: " << ms.fMeasuredAt.Format ([] (DateTime dt) { return dt.Format (); }).AsNarrowSDKString () << endl; for (Measurement mi : ms.fMeasurements) { cout << " " << mi.fType.GetPrintName ().AsNarrowSDKString () << ": " << Serialize_ (mi.fValue, oneLineMode) << endl; } }); // run til timeout and then fall out... IgnoreExceptionsForCall (Execution::WaitableEvent (Execution::WaitableEvent::eAutoReset).Wait (runFor)); } else { /* * Demo NOT using capturer */ cout << "Results for each instrument:" << endl; for (Instrument i : SystemPerformance::GetAllInstruments ()) { if (not run.empty ()) { if (not run.Contains (i.fInstrumentName)) { continue; } } cout << " " << i.fInstrumentName.GetPrintName ().AsNarrowSDKString () << endl; MeasurementSet m = i.Capture (); if (m.fMeasurements.empty ()) { cout << " NO DATA"; } else { cout << " Measured-At: " << m.fMeasuredAt.Format ([] (DateTime dt) { return dt.Format (); }).AsNarrowSDKString () << endl; for (Measurement mi : m.fMeasurements) { cout << " " << mi.fType.GetPrintName ().AsNarrowSDKString () << ": " << Serialize_ (mi.fValue, oneLineMode) << endl; } } } } } catch (...) { cerr << "Exception - terminating..." << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>undid hack to Samples/SystemPerformanceClient for recent Range<>::Format() change - now default arg works fine<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <iostream> #include "Stroika/Foundation/Characters/String2Float.h" #include "Stroika/Foundation/DataExchange/JSON/Writer.h" #include "Stroika/Foundation/Execution/CommandLine.h" #if qPlatform_POSIX #include "Stroika/Foundation/Execution/SignalHandlers.h" #endif #include "Stroika/Foundation/Execution/WaitableEvent.h" #include "Stroika/Foundation/Memory/Optional.h" #include "Stroika/Foundation/Streams/BasicBinaryOutputStream.h" #include "Stroika/Frameworks/SystemPerformance/AllInstruments.h" #include "Stroika/Frameworks/SystemPerformance/Capturer.h" #include "Stroika/Frameworks/SystemPerformance/Measurement.h" using namespace std; using namespace Stroika::Foundation; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::SystemPerformance; using Characters::Character; using Characters::String; using Containers::Sequence; using Memory::Optional; namespace { string Serialize_ (VariantValue v, bool oneLineMode) { Streams::BasicBinaryOutputStream out; DataExchange::JSON::Writer ().Write (v, out); // strip CRLF - so shows up on one line String result = String::FromUTF8 (out.As<string> ()); if (oneLineMode) { result = result.StripAll ([] (Character c)-> bool { return c == '\n' or c == '\r';}); } return result.AsNarrowSDKString (); } } int main (int argc, const char* argv[]) { #if qPlatform_POSIX // Many performance instruments use pipes // @todo - REVIEW IF REALLY NEEDED AND WHY? SO LONG AS NO FAIL SHOULDNT BE? // --LGP 2014-02-05 Execution::SignalHandlerRegistry::Get ().SetSignalHandlers (SIGPIPE, Execution::SignalHandlerRegistry::kIGNORED); #endif bool printUsage = false; bool printNames = false; bool oneLineMode = false; Time::DurationSecondsType runFor = 30.0; Set<InstrumentNameType> run; Sequence<String> args = Execution::ParseCommandLine (argc, argv); for (auto argi = args.begin (); argi != args.end(); ++argi) { if (Execution::MatchesCommandLineArgument (*argi, L"h")) { printUsage = true; } if (Execution::MatchesCommandLineArgument (*argi, L"l")) { printNames = true; } if (Execution::MatchesCommandLineArgument (*argi, L"o")) { oneLineMode = true; } if (Execution::MatchesCommandLineArgument (*argi, L"r")) { ++argi; if (argi != args.end ()) { run.Add (*argi); } else { cerr << "Expected arg to -r" << endl; return EXIT_FAILURE; } } if (Execution::MatchesCommandLineArgument (*argi, L"t")) { ++argi; if (argi != args.end ()) { runFor = Characters::String2Float<Time::DurationSecondsType> (*argi); } else { cerr << "Expected arg to -t" << endl; return EXIT_FAILURE; } } } if (printUsage) { cerr << "Usage: SystemPerformanceClient [-h] [-l] [-f] [-r RUN-INSTRUMENT]*" << endl; cerr << " -h prints this help" << endl; cerr << " -o prints instrument results (with newlines stripped)" << endl; cerr << " -l prints only the instrument names" << endl; cerr << " -r runs the given instrument (it can be repeated)" << endl; cerr << " -t time to run for (if zero dont use capturer code)" << endl; return EXIT_SUCCESS; } try { if (printNames) { cout << "Instrument:" << endl; for (Instrument i : SystemPerformance::GetAllInstruments ()) { cout << " " << i.fInstrumentName.GetPrintName ().AsNarrowSDKString () << endl; // print measurements too? } return EXIT_SUCCESS; } bool useCapturer = runFor > 0; if (useCapturer) { /* * Demo using capturer */ Capturer capturer; { CaptureSet cs; cs.SetRunPeriod (Duration (15)); for (Instrument i : SystemPerformance::GetAllInstruments ()) { if (not run.empty ()) { if (not run.Contains (i.fInstrumentName)) { continue; } } cs.AddInstrument (i); } capturer.AddCaptureSet (cs); } capturer.AddMeasurementsCallback ([oneLineMode] (MeasurementSet ms) { cout << " Measured-At: " << ms.fMeasuredAt.Format ().AsNarrowSDKString () << endl; for (Measurement mi : ms.fMeasurements) { cout << " " << mi.fType.GetPrintName ().AsNarrowSDKString () << ": " << Serialize_ (mi.fValue, oneLineMode) << endl; } }); // run til timeout and then fall out... IgnoreExceptionsForCall (Execution::WaitableEvent (Execution::WaitableEvent::eAutoReset).Wait (runFor)); } else { /* * Demo NOT using capturer */ cout << "Results for each instrument:" << endl; for (Instrument i : SystemPerformance::GetAllInstruments ()) { if (not run.empty ()) { if (not run.Contains (i.fInstrumentName)) { continue; } } cout << " " << i.fInstrumentName.GetPrintName ().AsNarrowSDKString () << endl; MeasurementSet m = i.Capture (); if (m.fMeasurements.empty ()) { cout << " NO DATA"; } else { cout << " Measured-At: " << m.fMeasuredAt.Format ().AsNarrowSDKString () << endl; for (Measurement mi : m.fMeasurements) { cout << " " << mi.fType.GetPrintName ().AsNarrowSDKString () << ": " << Serialize_ (mi.fValue, oneLineMode) << endl; } } } } } catch (...) { cerr << "Exception - terminating..." << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "CullWorker.h" #include "layers/Layer.h" #include "renderers/MapRenderer.h" #include "utils/Const.h" #include "utils/GeomUtils.h" #include "utils/Log.h" #include "utils/ThreadUtils.h" namespace carto { CullWorker::CullWorker() : _layerWakeupMap(), _firstCull(true), _envelope(), _viewState(), _mapRenderer(), _stop(false), _idle(false), _condition(), _mutex() { } CullWorker::~CullWorker() { } void CullWorker::setComponents(const std::weak_ptr<MapRenderer>& mapRenderer, const std::shared_ptr<CullWorker>& worker) { _mapRenderer = mapRenderer; // When the map component gets destroyed all threads get detatched. Detatched threads need their worker objects to be alive, // so worker objects need to keep references to themselves, until the loop finishes. _worker = worker; } void CullWorker::init(const std::shared_ptr<Layer>& layer, int delayTime) { { std::lock_guard<std::mutex> lock(_mutex); std::chrono::steady_clock::time_point wakeupTime = std::chrono::steady_clock::now() + std::chrono::milliseconds(delayTime); if (_layerWakeupMap.find(layer) != _layerWakeupMap.end()) { if (_layerWakeupMap[layer] <= wakeupTime) return; } _layerWakeupMap[layer] = wakeupTime; } std::lock_guard<std::mutex> lock(_mutex); _idle = false; _condition.notify_one(); } void CullWorker::stop() { std::lock_guard<std::mutex> lock(_mutex); _stop = true; _condition.notify_all(); } bool CullWorker::isIdle() const { std::lock_guard<std::mutex> lock(_mutex); return _idle; } void CullWorker::operator ()() { run(); _worker.reset(); } void CullWorker::run() { ThreadUtils::SetThreadPriority(ThreadPriority::LOW); while (true) { std::vector<std::shared_ptr<Layer> > layers; { std::unique_lock<std::mutex> lock(_mutex); if (_stop) { return; } std::chrono::steady_clock::time_point currentTime = std::chrono::steady_clock::now(); std::chrono::steady_clock::time_point wakeupTime = std::chrono::steady_clock::now() + std::chrono::hours(24); for (auto it = _layerWakeupMap.begin(); it != _layerWakeupMap.end(); ) { if (it->second - currentTime < std::chrono::milliseconds(1)) { layers.push_back(it->first); _layerWakeupMap.erase(it++); } else { wakeupTime = std::min(wakeupTime, it->second); it++; } } if (layers.empty()) { _idle = _layerWakeupMap.empty(); _condition.wait_for(lock, wakeupTime - std::chrono::steady_clock::now()); _idle = false; } } if (!layers.empty()) { const std::shared_ptr<MapRenderer>& mapRenderer = _mapRenderer.lock(); if (!mapRenderer) { return; } // Get view state const ViewState& viewState = mapRenderer->getViewState(); // Check if view state has changed if (_firstCull || viewState.getModelviewProjectionMat() != _viewState.getModelviewProjectionMat()) { _firstCull = false; _viewState = viewState; // Calculate tiles calculateCullState(); } // Update layers updateLayers(layers); } } } void CullWorker::calculateCullState() { // Calculate envelope for the visible frustum calculateEnvelope(); } void CullWorker::calculateEnvelope() { cglib::mat4x4<double> invMVPMat = cglib::inverse(_viewState.getModelviewProjectionMat()); // Iterate over all edges and find intersection with ground plane std::vector<MapPos> hullPoints; hullPoints.reserve(12); for (int i = 0; i < 12; i++) { int ax = (i >> 2) & 3; int as = (4-ax) >> 2; int bs = (5-ax) >> 2; int va = ((i&1) << as) | ((i&2) << bs); int vb = va | (1 << ax); // Calculate vertex 0 double xa = (va & 1) == 0 ? VIEWPORT_SCALE : -VIEWPORT_SCALE; double ya = (va & 2) == 0 ? VIEWPORT_SCALE : -VIEWPORT_SCALE; double za = (va & 4) == 0 ? 1 : -1; cglib::vec3<double> p0 = cglib::transform_point(cglib::vec3<double>(xa, ya, za), invMVPMat); // Calculate vertex 1 double xb = (vb & 1) == 0 ? VIEWPORT_SCALE : -VIEWPORT_SCALE; double yb = (vb & 2) == 0 ? VIEWPORT_SCALE : -VIEWPORT_SCALE; double zb = (vb & 4) == 0 ? 1 : -1; cglib::vec3<double> p1 = cglib::transform_point(cglib::vec3<double>(xb, yb, zb), invMVPMat); // Calculate intersection between z=0 plane and line p0<->p1 cglib::vec3<double> dp = p1 - p0; if (dp(2) != 0) { double t = -p0(2) / dp(2); // If the intersection point is inside of the frustum, add it to the list of candidate points if (t >= 0 && t <= 1) { cglib::vec3<double> hullPoint = p0 + dp * t; hullPoints.emplace_back(hullPoint(0), hullPoint(1), 0); } } } // Calculate convex hull of the resulting point set std::vector<MapPos> convexHull = GeomUtils::CalculateConvexHull(hullPoints); _envelope = MapEnvelope(convexHull); } void CullWorker::updateLayers(const std::vector<std::shared_ptr<Layer> >& layers) { for (const std::shared_ptr<Layer>& layer : layers) { layer->update(std::make_shared<CullState>(_envelope, _viewState)); } } const float CullWorker::VIEWPORT_SCALE = 1.1f; // enlarge viewport envelope by approx. 10% } <commit_msg>Tweaks<commit_after>#include "CullWorker.h" #include "layers/Layer.h" #include "renderers/MapRenderer.h" #include "utils/Const.h" #include "utils/GeomUtils.h" #include "utils/Log.h" #include "utils/ThreadUtils.h" namespace carto { CullWorker::CullWorker() : _layerWakeupMap(), _firstCull(true), _envelope(), _viewState(), _mapRenderer(), _stop(false), _idle(false), _condition(), _mutex() { } CullWorker::~CullWorker() { } void CullWorker::setComponents(const std::weak_ptr<MapRenderer>& mapRenderer, const std::shared_ptr<CullWorker>& worker) { _mapRenderer = mapRenderer; // When the map component gets destroyed all threads get detatched. Detatched threads need their worker objects to be alive, // so worker objects need to keep references to themselves, until the loop finishes. _worker = worker; } void CullWorker::init(const std::shared_ptr<Layer>& layer, int delayTime) { std::lock_guard<std::mutex> lock(_mutex); std::chrono::steady_clock::time_point wakeupTime = std::chrono::steady_clock::now() + std::chrono::milliseconds(delayTime); if (_layerWakeupMap.find(layer) != _layerWakeupMap.end()) { if (_layerWakeupMap[layer] <= wakeupTime) { return; } } _layerWakeupMap[layer] = wakeupTime; _idle = false; _condition.notify_one(); } void CullWorker::stop() { std::lock_guard<std::mutex> lock(_mutex); _stop = true; _condition.notify_all(); } bool CullWorker::isIdle() const { std::lock_guard<std::mutex> lock(_mutex); return _idle; } void CullWorker::operator ()() { run(); _worker.reset(); } void CullWorker::run() { ThreadUtils::SetThreadPriority(ThreadPriority::LOW); while (true) { std::vector<std::shared_ptr<Layer> > layers; { std::unique_lock<std::mutex> lock(_mutex); if (_stop) { return; } std::chrono::steady_clock::time_point currentTime = std::chrono::steady_clock::now(); std::chrono::steady_clock::time_point wakeupTime = std::chrono::steady_clock::now() + std::chrono::hours(24); for (auto it = _layerWakeupMap.begin(); it != _layerWakeupMap.end(); ) { if (it->second - currentTime < std::chrono::milliseconds(1)) { layers.push_back(it->first); it = _layerWakeupMap.erase(it); } else { wakeupTime = std::min(wakeupTime, it->second); it++; } } if (layers.empty()) { _idle = _layerWakeupMap.empty(); _condition.wait_for(lock, wakeupTime - std::chrono::steady_clock::now()); _idle = false; } } if (!layers.empty()) { const std::shared_ptr<MapRenderer>& mapRenderer = _mapRenderer.lock(); if (!mapRenderer) { return; } // Get view state const ViewState& viewState = mapRenderer->getViewState(); // Check if view state has changed if (_firstCull || viewState.getModelviewProjectionMat() != _viewState.getModelviewProjectionMat()) { _firstCull = false; _viewState = viewState; // Calculate tiles calculateCullState(); } // Update layers updateLayers(layers); } } } void CullWorker::calculateCullState() { // Calculate envelope for the visible frustum calculateEnvelope(); } void CullWorker::calculateEnvelope() { cglib::mat4x4<double> invMVPMat = cglib::inverse(_viewState.getModelviewProjectionMat()); // Iterate over all edges and find intersection with ground plane std::vector<MapPos> hullPoints; hullPoints.reserve(12); for (int i = 0; i < 12; i++) { int ax = (i >> 2) & 3; int as = (4-ax) >> 2; int bs = (5-ax) >> 2; int va = ((i&1) << as) | ((i&2) << bs); int vb = va | (1 << ax); // Calculate vertex 0 double xa = (va & 1) == 0 ? VIEWPORT_SCALE : -VIEWPORT_SCALE; double ya = (va & 2) == 0 ? VIEWPORT_SCALE : -VIEWPORT_SCALE; double za = (va & 4) == 0 ? 1 : -1; cglib::vec3<double> p0 = cglib::transform_point(cglib::vec3<double>(xa, ya, za), invMVPMat); // Calculate vertex 1 double xb = (vb & 1) == 0 ? VIEWPORT_SCALE : -VIEWPORT_SCALE; double yb = (vb & 2) == 0 ? VIEWPORT_SCALE : -VIEWPORT_SCALE; double zb = (vb & 4) == 0 ? 1 : -1; cglib::vec3<double> p1 = cglib::transform_point(cglib::vec3<double>(xb, yb, zb), invMVPMat); // Calculate intersection between z=0 plane and line p0<->p1 cglib::vec3<double> dp = p1 - p0; if (dp(2) != 0) { double t = -p0(2) / dp(2); // If the intersection point is inside of the frustum, add it to the list of candidate points if (t >= 0 && t <= 1) { cglib::vec3<double> hullPoint = p0 + dp * t; hullPoints.emplace_back(hullPoint(0), hullPoint(1), 0); } } } // Calculate convex hull of the resulting point set std::vector<MapPos> convexHull = GeomUtils::CalculateConvexHull(hullPoints); _envelope = MapEnvelope(convexHull); } void CullWorker::updateLayers(const std::vector<std::shared_ptr<Layer> >& layers) { for (const std::shared_ptr<Layer>& layer : layers) { layer->update(std::make_shared<CullState>(_envelope, _viewState)); } } const float CullWorker::VIEWPORT_SCALE = 1.1f; // enlarge viewport envelope by approx. 10% } <|endoftext|>
<commit_before>#include "cookiejar.h" CookieJar::CookieJar(QObject *parent) : QNetworkCookieJar(parent) { jarfile = new QFile("/tmp/test", this); if (jarfile->open(QIODevice::ReadWrite | QIODevice::Append | QIODevice::Text)) { //Lägg till en massa cookies //QNetworkCookie nc() } } bool CookieJar::setCookiesFromUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url) { if (jarfile->isOpen()) { QTextStream jf(jarfile); jf << "----\n"; foreach(QNetworkCookie nc, cookieList) { if (!nc.isSessionCookie()) { //QString data(nc.toRawForm()); //jf << data << "\n"; } } } return QNetworkCookieJar::setCookiesFromUrl(cookieList, url); } <commit_msg>kakor<commit_after>#include "cookiejar.h" CookieJar::CookieJar(QObject *parent) : QNetworkCookieJar(parent) { jarfile = new QFile("/tmp/kaktuskakor", this); if (jarfile->open(QIODevice::ReadWrite | QIODevice::Text)) { //Lägg till en massa cookies QTextStream jf(jarfile); setAllCookies(QNetworkCookie::parseCookies(jf.readAll().toAscii())); } } bool CookieJar::setCookiesFromUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url) { if (jarfile->isOpen()) { QTextStream jf(jarfile); foreach(QNetworkCookie nc, cookieList) { if (!nc.isSessionCookie()) { QString data(nc.toRawForm()); jf << data << "\n"; } } } return QNetworkCookieJar::setCookiesFromUrl(cookieList, url); } <|endoftext|>
<commit_before>/* This file is part of the ORK library. Full copyright and license terms can be found in the LICENSE.txt file. */ #include "ork/geometry.hpp" #include "ork/test/catch_include.hpp" #include "glm/vec3.hpp" using namespace ork; TEST_CASE("Length conversion", "[geometry]") { const double dmm = 50.8; const double din = 3.0; const double rin = 2.0; const double rmm = 76.2; REQUIRE(mm2inch(dmm) == rin); REQUIRE(inch2mm(din) == rmm); } TEST_CASE("Simple angles", "[geometry]") { const double angle1 = 136.0; const double angle2 = 395.0; const double angle3 = -172.0; const double sangle1 = 136.0; const double sangle2 = 35.0; const double sangle3 = 188.0; REQUIRE(simple_angle(angle1) == sangle1); REQUIRE(simple_angle(angle2) == sangle2); REQUIRE(simple_angle(angle3) == sangle3); } <commit_msg>Changed FP comparisons to approx<commit_after>/* This file is part of the ORK library. Full copyright and license terms can be found in the LICENSE.txt file. */ #include "ork/geometry.hpp" #include "ork/glm.hpp" #include "ork/test/catch_include.hpp" #include "glm/vec3.hpp" using namespace ork; TEST_CASE("Length conversion", "[geometry]") { const double dmm = 50.8; const double din = 3.0; const double rin = 2.0; const double rmm = 76.2; REQUIRE(ork::GLM::equal(mm2inch(dmm), rin)); REQUIRE(ork::GLM::equal(inch2mm(din), rmm)); } TEST_CASE("Simple angles", "[geometry]") { const double angle1 = 136.0; const double angle2 = 395.0; const double angle3 = -172.0; const double angle4 = 2.6 * M_PI; const double sangle1 = 136.0; const double sangle2 = 35.0; const double sangle3 = 188.0; const double sangle4 = 0.6 * M_PI; REQUIRE(ork::GLM::equal(simple_angle<angle::degree>(angle1), sangle1)); REQUIRE(ork::GLM::equal(simple_angle<angle::degree>(angle2), sangle2)); REQUIRE(ork::GLM::equal(simple_angle(angle3, angle::degree), sangle3)); REQUIRE(ork::GLM::equal(simple_angle(angle4, angle::radian), sangle4)); } } <|endoftext|>
<commit_before>/* This file is part of VROOM. Copyright (c) 2015-2022, Julien Coupey. All rights reserved (see LICENSE). */ #include <mutex> #include <set> #include <thread> #include "algorithms/heuristics/heuristics.h" #include "algorithms/local_search/local_search.h" #include "problems/vrptw/operators/cross_exchange.h" #include "problems/vrptw/operators/intra_cross_exchange.h" #include "problems/vrptw/operators/intra_exchange.h" #include "problems/vrptw/operators/intra_mixed_exchange.h" #include "problems/vrptw/operators/intra_or_opt.h" #include "problems/vrptw/operators/intra_relocate.h" #include "problems/vrptw/operators/intra_two_opt.h" #include "problems/vrptw/operators/mixed_exchange.h" #include "problems/vrptw/operators/or_opt.h" #include "problems/vrptw/operators/pd_shift.h" #include "problems/vrptw/operators/relocate.h" #include "problems/vrptw/operators/reverse_two_opt.h" #include "problems/vrptw/operators/route_exchange.h" #include "problems/vrptw/operators/swap_star.h" #include "problems/vrptw/operators/two_opt.h" #include "problems/vrptw/operators/unassigned_exchange.h" #include "problems/vrptw/vrptw.h" #include "utils/helpers.h" namespace vroom { using TWSolution = std::vector<TWRoute>; namespace vrptw { using LocalSearch = ls::LocalSearch<TWRoute, vrptw::UnassignedExchange, vrptw::SwapStar, vrptw::CrossExchange, vrptw::MixedExchange, vrptw::TwoOpt, vrptw::ReverseTwoOpt, vrptw::Relocate, vrptw::OrOpt, vrptw::IntraExchange, vrptw::IntraCrossExchange, vrptw::IntraMixedExchange, vrptw::IntraRelocate, vrptw::IntraOrOpt, vrptw::IntraTwoOpt, vrptw::PDShift, vrptw::RouteExchange>; } // namespace vrptw const std::vector<HeuristicParameters> VRPTW::homogeneous_parameters = {HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.3), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.4), HeuristicParameters(HEURISTIC::BASIC, INIT::EARLIEST_DEADLINE, 0.2), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.3), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.4), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.5), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.4), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.5), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.1), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.6), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.2), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.7), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.2), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.7), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.4), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.1), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.1), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.3), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.8), HeuristicParameters(HEURISTIC::BASIC, INIT::EARLIEST_DEADLINE, 0.5), HeuristicParameters(HEURISTIC::BASIC, INIT::EARLIEST_DEADLINE, 0.8), HeuristicParameters(HEURISTIC::BASIC, INIT::EARLIEST_DEADLINE, 2.4), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 1.2), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.3), HeuristicParameters(HEURISTIC::BASIC, INIT::EARLIEST_DEADLINE, 0), HeuristicParameters(HEURISTIC::BASIC, INIT::EARLIEST_DEADLINE, 0.3), HeuristicParameters(HEURISTIC::BASIC, INIT::EARLIEST_DEADLINE, 2), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.9), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 1)}; const std::vector<HeuristicParameters> VRPTW::heterogeneous_parameters = {HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.5), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.9), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 0.4), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.4), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.8), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 0.6), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 0.9), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.6), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1.8), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 1.1), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 1.4), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.7), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 1.3), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 2.4), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 0.3), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 1.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 1.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.6), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1.6), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 0.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 1.7), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.5), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 1.5), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 1.5), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 2.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 2.1), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 0.5), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 1.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.1), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.9), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 1.1)}; VRPTW::VRPTW(const Input& input) : VRP(input) { } Solution VRPTW::solve(unsigned exploration_level, unsigned nb_threads, const Timeout& timeout, const std::vector<HeuristicParameters>& h_param) const { // Use vector of parameters when passed for debugging, else use // predefined parameter set. const auto& parameters = (!h_param.empty()) ? h_param : (_input.has_homogeneous_locations()) ? homogeneous_parameters : heterogeneous_parameters; unsigned max_nb_jobs_removal = exploration_level; unsigned nb_init_solutions = h_param.size(); if (nb_init_solutions == 0) { // Local search parameter. nb_init_solutions = 4 * (exploration_level + 1); if (exploration_level >= 4) { nb_init_solutions += 4; } if (exploration_level >= 5) { nb_init_solutions += 4; } } assert(nb_init_solutions <= parameters.size()); std::vector<TWSolution> tw_solutions(nb_init_solutions); // Split the heuristic parameters among threads. std::vector<std::vector<std::size_t>> thread_ranks(nb_threads, std::vector<std::size_t>()); for (std::size_t i = 0; i < nb_init_solutions; ++i) { thread_ranks[i % nb_threads].push_back(i); } std::exception_ptr ep = nullptr; std::mutex ep_m; auto run_heuristics = [&](const std::vector<std::size_t>& param_ranks) { try { for (auto rank : param_ranks) { auto& p = parameters[rank]; switch (p.heuristic) { case HEURISTIC::INIT_ROUTES: tw_solutions[rank] = heuristics::initial_routes<TWSolution>(_input); break; case HEURISTIC::BASIC: tw_solutions[rank] = heuristics::basic<TWSolution>(_input, p.init, p.regret_coeff); break; case HEURISTIC::DYNAMIC: tw_solutions[rank] = heuristics::dynamic_vehicle_choice<TWSolution>(_input, p.init, p.regret_coeff); break; } } } catch (...) { ep_m.lock(); ep = std::current_exception(); ep_m.unlock(); } }; std::vector<std::thread> heuristics_threads; for (const auto& param_ranks : thread_ranks) { if (!param_ranks.empty()) { heuristics_threads.emplace_back(run_heuristics, param_ranks); } } for (auto& t : heuristics_threads) { t.join(); } if (ep != nullptr) { std::rethrow_exception(ep); } // Filter out duplicate heuristics solutions. std::set<utils::SolutionIndicators<TWRoute>> unique_indicators; std::vector<unsigned> to_remove; for (unsigned i = 0; i < tw_solutions.size(); ++i) { const auto result = unique_indicators.emplace(_input, tw_solutions[i]); if (!result.second) { // No insertion means an equivalent solution already exists. to_remove.push_back(i); } } for (auto remove_rank = to_remove.rbegin(); remove_rank != to_remove.rend(); remove_rank++) { tw_solutions.erase(tw_solutions.begin() + *remove_rank); } // Split local searches across threads. unsigned nb_solutions = tw_solutions.size(); std::vector<utils::SolutionIndicators<TWRoute>> sol_indicators(nb_solutions); #ifdef LOG_LS_OPERATORS std::vector<std::array<ls::OperatorStats, OperatorName::MAX>> ls_stats( nb_solutions); #endif std::fill(thread_ranks.begin(), thread_ranks.end(), std::vector<std::size_t>()); for (std::size_t i = 0; i < nb_solutions; ++i) { thread_ranks[i % nb_threads].push_back(i); } auto run_ls = [&](const std::vector<std::size_t>& sol_ranks) { try { // Decide time allocated for each search. Timeout search_time; if (timeout.has_value()) { search_time = timeout.value() / sol_ranks.size(); } for (auto rank : sol_ranks) { // Local search phase. vrptw::LocalSearch ls(_input, tw_solutions[rank], max_nb_jobs_removal, search_time); ls.run(); // Store solution indicators. sol_indicators[rank] = ls.indicators(); #ifdef LOG_LS_OPERATORS ls_stats[rank] = ls.get_stats(); #endif } } catch (...) { ep_m.lock(); ep = std::current_exception(); ep_m.unlock(); } }; std::vector<std::thread> ls_threads; for (const auto& sol_ranks : thread_ranks) { if (!sol_ranks.empty()) { ls_threads.emplace_back(run_ls, sol_ranks); } } for (auto& t : ls_threads) { t.join(); } if (ep != nullptr) { std::rethrow_exception(ep); } #ifdef LOG_LS_OPERATORS utils::log_LS_operators(ls_stats); #endif auto best_indic = std::min_element(sol_indicators.cbegin(), sol_indicators.cend()); return utils::format_solution(_input, tw_solutions[std::distance(sol_indicators .cbegin(), best_indic)]); } } // namespace vroom <commit_msg>Change VRPTW to use VRP::solve()<commit_after>/* This file is part of VROOM. Copyright (c) 2015-2022, Julien Coupey. All rights reserved (see LICENSE). */ #include <mutex> #include <set> #include <thread> #include "algorithms/heuristics/heuristics.h" #include "algorithms/local_search/local_search.h" #include "problems/vrptw/operators/cross_exchange.h" #include "problems/vrptw/operators/intra_cross_exchange.h" #include "problems/vrptw/operators/intra_exchange.h" #include "problems/vrptw/operators/intra_mixed_exchange.h" #include "problems/vrptw/operators/intra_or_opt.h" #include "problems/vrptw/operators/intra_relocate.h" #include "problems/vrptw/operators/intra_two_opt.h" #include "problems/vrptw/operators/mixed_exchange.h" #include "problems/vrptw/operators/or_opt.h" #include "problems/vrptw/operators/pd_shift.h" #include "problems/vrptw/operators/relocate.h" #include "problems/vrptw/operators/reverse_two_opt.h" #include "problems/vrptw/operators/route_exchange.h" #include "problems/vrptw/operators/swap_star.h" #include "problems/vrptw/operators/two_opt.h" #include "problems/vrptw/operators/unassigned_exchange.h" #include "problems/vrptw/vrptw.h" #include "utils/helpers.h" namespace vroom { using TWSolution = std::vector<TWRoute>; namespace vrptw { using LocalSearch = ls::LocalSearch<TWRoute, vrptw::UnassignedExchange, vrptw::SwapStar, vrptw::CrossExchange, vrptw::MixedExchange, vrptw::TwoOpt, vrptw::ReverseTwoOpt, vrptw::Relocate, vrptw::OrOpt, vrptw::IntraExchange, vrptw::IntraCrossExchange, vrptw::IntraMixedExchange, vrptw::IntraRelocate, vrptw::IntraOrOpt, vrptw::IntraTwoOpt, vrptw::PDShift, vrptw::RouteExchange>; } // namespace vrptw const std::vector<HeuristicParameters> VRPTW::homogeneous_parameters = {HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.3), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.4), HeuristicParameters(HEURISTIC::BASIC, INIT::EARLIEST_DEADLINE, 0.2), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.3), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.4), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.5), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.4), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.5), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.1), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.6), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.2), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.7), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.2), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.7), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.4), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.1), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.1), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.3), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.8), HeuristicParameters(HEURISTIC::BASIC, INIT::EARLIEST_DEADLINE, 0.5), HeuristicParameters(HEURISTIC::BASIC, INIT::EARLIEST_DEADLINE, 0.8), HeuristicParameters(HEURISTIC::BASIC, INIT::EARLIEST_DEADLINE, 2.4), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 1.2), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.3), HeuristicParameters(HEURISTIC::BASIC, INIT::EARLIEST_DEADLINE, 0), HeuristicParameters(HEURISTIC::BASIC, INIT::EARLIEST_DEADLINE, 0.3), HeuristicParameters(HEURISTIC::BASIC, INIT::EARLIEST_DEADLINE, 2), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.9), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 1)}; const std::vector<HeuristicParameters> VRPTW::heterogeneous_parameters = {HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.5), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.9), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 0.4), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.4), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.8), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 0.6), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 0.9), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.6), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1.8), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 1.1), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 1.4), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.7), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 1.3), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 2.4), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 0.3), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 1.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 1.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.6), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1.6), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 0.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 1.7), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.5), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 1.5), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 1.5), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 2.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 2.1), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 0.5), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::EARLIEST_DEADLINE, 1.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.1), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.9), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 1.1)}; VRPTW::VRPTW(const Input& input) : VRP(input) { } Solution VRPTW::solve(unsigned exploration_level, unsigned nb_threads, const Timeout& timeout, const std::vector<HeuristicParameters>& h_param) const { return VRP::solve<TWRoute, TWSolution, vrptw::LocalSearch>(exploration_level, nb_threads, timeout, h_param, homogeneous_parameters, heterogeneous_parameters); } } // namespace vroom <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkDummyImageToListAdaptorTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <time.h> #include "itkFixedArray.h" #include "itkImage.h" #include "itkImageAdaptor.h" #include "itkImageRegionIterator.h" #include "itkPixelTraits.h" #include "itkListSampleBase.h" #include "itkImageToListAdaptor.h" #include "itkScalarToArrayCastImageFilter.h" #include "itkImage.h" #include "itkObject.h" #include "itkMacro.h" #include "itkPixelTraits.h" template < class TImage, class TMeasurementVector = ITK_TYPENAME TImage::PixelType > class ITK_EXPORT DummyImageToListAdaptor : public itk::Statistics::ListSampleBase< TMeasurementVector > { public: typedef DummyImageToListAdaptor Self ; typedef itk::Statistics::ListSampleBase< TMeasurementVector > Superclass ; typedef itk::SmartPointer< Self > Pointer ; typedef itk::SmartPointer< const Self > ConstPointer ; itkTypeMacro( DummyImageToListAdaptor, Object ) ; itkNewMacro( Self ) ; typedef typename TImage::PixelType PixelType ; typedef typename itk::PixelTraits< PixelType >::ValueType MeasurementType ; itkStaticConstMacro( MeasurementVectorSize, unsigned int, itk::PixelTraits< PixelType >::Dimension ) ; typedef TMeasurementVector MeasurementVectorType ; unsigned int Size() const { return 1 ;} float GetTotalFrequency() const { return 1 ;} float GetFrequency(const unsigned long& id) const { return id ; } virtual MeasurementVectorType GetMeasurementVector(const unsigned long& id) { if( m_UseBuffer ) { return *(reinterpret_cast< MeasurementVectorType* > (&(*m_ImageBuffer)[id])) ; } else { return *(reinterpret_cast< MeasurementVectorType* > (&(m_Image->GetPixel( m_Image->ComputeIndex( id ))) ) ) ; } } void SetImage( TImage* image ) { m_Image = image ; m_ImageBuffer = m_Image->GetPixelContainer() ; if ( strcmp( m_Image->GetNameOfClass(), "Image" ) != 0 ) { m_UseBuffer = false ; } else { m_UseBuffer = true ; } } protected: DummyImageToListAdaptor() { m_Image = 0 ; } virtual ~DummyImageToListAdaptor() {} typename TImage::Pointer m_Image ; typename TImage::PixelContainer* m_ImageBuffer ; MeasurementVectorType m_TempVector ; bool m_UseBuffer ; private: DummyImageToListAdaptor(const Self&) ; void operator=(const Self&) ; } ; template < class TImage > class ITK_EXPORT DummyScalarImageToListAdaptor : public DummyImageToListAdaptor< TImage, itk::FixedArray< typename TImage::PixelType, 1> > { public: typedef DummyScalarImageToListAdaptor Self ; typedef DummyImageToListAdaptor< TImage, itk::FixedArray< typename TImage::PixelType, 1> > Superclass ; typedef itk::SmartPointer< Self > Pointer ; typedef itk::SmartPointer< const Self > ConstPointer ; itkTypeMacro( DummyScalarImageToListAdaptor, DummyImageToListAdaptor ) ; itkNewMacro( Self ) ; typedef typename Superclass::MeasurementVectorType MeasurementVectorType ; MeasurementVectorType GetMeasurementVector(const unsigned long& id) { if( m_UseBuffer ) { m_TempVector[0] = (*m_ImageBuffer)[id] ; } else { m_TempVector[0] = m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ; } return m_TempVector ; } protected: DummyScalarImageToListAdaptor() {} virtual ~DummyScalarImageToListAdaptor() {} } ; // end of class template< class TImage, class TCoordRep > struct ImageJointDomainTraits { typedef ImageJointDomainTraits Self ; typedef itk::PixelTraits< typename TImage::PixelType > PixelTraitsType ; itkStaticConstMacro(Size, unsigned int, TImage::ImageDimension + PixelTraitsType::Dimension ) ; typedef itk::JoinTraits< TCoordRep, PixelTraitsType::ValueType > JoinTraitsType ; typedef JoinTraitsType::ValueType MeasurementType ; typedef itk::FixedArray< MeasurementType, itkGetStaticConstMacro(Size) > MeasurementVectorType ; } ; // end of ImageJointDomainTraits template < class TImage, class TCoordRep > class ITK_EXPORT DummyJointDomainImageToListAdaptor : public DummyImageToListAdaptor< TImage, ImageJointDomainTraits< TImage, TCoordRep >::MeasurementVectorType > { public: typedef DummyJointDomainImageToListAdaptor Self ; typedef DummyImageToListAdaptor< TImage, ImageJointDomainTraits< TImage, TCoordRep >::MeasurementVectorType > Superclass ; typedef itk::SmartPointer< Self > Pointer ; typedef itk::SmartPointer< const Self > ConstPointer ; itkTypeMacro( DummyJointDomainImageToListAdaptor, DummyImageToListAdaptor ) ; itkNewMacro( Self ) ; typedef typename Superclass::MeasurementType MeasurementType ; typedef typename Superclass::MeasurementVectorType MeasurementVectorType ; itkStaticConstMacro(RangeDomainDimension, unsigned int, itk::PixelTraits< typename TImage::PixelType >::Dimension) ; typedef typename itk::FixedArray< MeasurementType, itkGetStaticConstMacro( RangeDomainDimension ) > RangeDomainMeasurementVectorType ; MeasurementVectorType GetMeasurementVector(const unsigned long& id) { typename itk::Point<MeasurementType, TImage::ImageDimension> point ; typename TImage::IndexType index = m_Image->ComputeIndex( id ) ; m_Image->TransformIndexToPhysicalPoint( index, point ) ; for ( unsigned int i = 0 ; i < TImage::ImageDimension ; ++i ) { m_TempVector[i] = point[i] ; } if( m_UseBuffer ) { m_TempVector2 = *(reinterpret_cast< RangeDomainMeasurementVectorType* > (&(*m_ImageBuffer)[id])) ; } else { m_TempVector2 = *(reinterpret_cast< RangeDomainMeasurementVectorType* > (&(m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ) ) ) ; } for ( unsigned int i = TImage::ImageDimension ; i < MeasurementVectorType::Length ; ++i ) { m_TempVector[i]= m_TempVector2[i - TImage::ImageDimension] ; } return m_TempVector ; } protected: DummyJointDomainImageToListAdaptor() {} virtual ~DummyJointDomainImageToListAdaptor() {} RangeDomainMeasurementVectorType m_TempVector2 ; } ; // end of class int itkDummyImageToListAdaptorTest(int, char* [] ) { typedef int ScalarPixelType ; typedef itk::FixedArray< ScalarPixelType, 1 > ArrayPixelType ; typedef itk::Vector< ScalarPixelType, 2 > VectorPixelType ; typedef itk::Image< ScalarPixelType, 3 > ScalarImageType ; typedef itk::Image< ArrayPixelType, 3 > ArrayImageType ; typedef itk::Image< VectorPixelType, 3 > VectorImageType ; typedef itk::ImageRegionIterator< ScalarImageType > ScalarImageIteratorType ; typedef itk::ImageRegionIterator< ArrayImageType > ArrayImageIteratorType ; typedef itk::ImageRegionIterator< VectorImageType > VectorImageIteratorType ; itk::Size< 3 > size ; size.Fill(10) ; ScalarImageType::Pointer scalarImage = ScalarImageType::New() ; scalarImage->SetRegions(size) ; scalarImage->Allocate() ; int count = 0 ; ScalarImageIteratorType s_iter = ScalarImageIteratorType(scalarImage, scalarImage->GetLargestPossibleRegion() ) ; while ( !s_iter.IsAtEnd() ) { s_iter.Set(count) ; ++count ; ++s_iter ; } VectorImageType::Pointer vectorImage = VectorImageType::New() ; vectorImage->SetRegions(size) ; vectorImage->Allocate() ; count = 0 ; VectorImageType::PixelType vPixel ; VectorImageIteratorType v_iter = VectorImageIteratorType(vectorImage, vectorImage->GetLargestPossibleRegion()) ; while ( !v_iter.IsAtEnd() ) { vPixel[0] = count ; vPixel[1] = count ; v_iter.Set( vPixel ) ; ++count ; ++v_iter ; } typedef DummyScalarImageToListAdaptor< ScalarImageType > ScalarListType ; ScalarListType::Pointer sList = ScalarListType::New() ; sList->SetImage( scalarImage ) ; typedef DummyImageToListAdaptor< VectorImageType > VectorListType ; VectorListType::Pointer vList = VectorListType::New() ; vList->SetImage( vectorImage ) ; typedef itk::ScalarToArrayCastImageFilter< ScalarImageType, ArrayImageType > CasterType ; CasterType::Pointer caster = CasterType::New() ; caster->SetInput( scalarImage ) ; caster->Update() ; typedef itk::Statistics::ImageToListAdaptor< ArrayImageType > ImageListType ; ImageListType::Pointer imageList = ImageListType::New() ; imageList->SetImage( caster->GetOutput() ) ; typedef DummyJointDomainImageToListAdaptor< VectorImageType, float > JointDomainImageListType ; JointDomainImageListType::Pointer jointDomainImageList = JointDomainImageListType::New() ; jointDomainImageList->SetImage( vectorImage ) ; std::cout << "Testing the each measurement values:" << std::endl ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { if ( sList->GetMeasurementVector( i )[0] != vList->GetMeasurementVector( i )[0] || sList->GetMeasurementVector( i )[0] != imageList->GetMeasurementVector( i )[0] || sList->GetMeasurementVector( i )[0] != jointDomainImageList->GetMeasurementVector( i )[3] ) { std::cout << "ERROR: measurement mismatch!!!" << std::endl ; return EXIT_FAILURE ; } } std::cout << std::endl ; std::cout << "Scalar image (casted) pixel access performance test:" << std::endl ; time_t begin = clock() ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { imageList->GetMeasurementVector( i ) ; } time_t end = clock() ; std::cout << "time: " << (double(end - begin) /CLOCKS_PER_SEC) << " seconds" << std::endl ; std::cout << "Scalar image pixel access performance test:" << std::endl ; begin = clock() ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { sList->GetMeasurementVector( i ) ; } end = clock() ; std::cout << "time: " << (double(end - begin) /CLOCKS_PER_SEC) << " seconds" << std::endl ; std::cout << "Vector image pixel access performance test:" << std::endl ; begin = clock() ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { vList->GetMeasurementVector( i ) ; } end = clock() ; std::cout << "time: " << (double(end - begin) /CLOCKS_PER_SEC) << " seconds" << std::endl ; std::cout << "Joint Domain Vector image pixel access performance test:" << std::endl ; begin = clock() ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { std::cout << jointDomainImageList->GetMeasurementVector( i ) << std::endl ; } end = clock() ; std::cout << "time: " << (double(end - begin) /CLOCKS_PER_SEC) << " seconds" << std::endl ; return EXIT_SUCCESS ; } <commit_msg><commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkDummyImageToListAdaptorTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <time.h> #include "itkFixedArray.h" #include "itkImage.h" #include "itkImageAdaptor.h" #include "itkImageRegionIterator.h" #include "itkPixelTraits.h" #include "itkListSampleBase.h" #include "itkImageToListAdaptor.h" #include "itkScalarToArrayCastImageFilter.h" #include "itkImage.h" #include "itkObject.h" #include "itkMacro.h" #include "itkPixelTraits.h" template < class TImage, class TMeasurementVector = ITK_TYPENAME TImage::PixelType > class ITK_EXPORT DummyImageToListAdaptor : public itk::Statistics::ListSampleBase< TMeasurementVector > { public: typedef DummyImageToListAdaptor Self ; typedef itk::Statistics::ListSampleBase< TMeasurementVector > Superclass ; typedef itk::SmartPointer< Self > Pointer ; typedef itk::SmartPointer< const Self > ConstPointer ; itkTypeMacro( DummyImageToListAdaptor, Object ) ; itkNewMacro( Self ) ; typedef typename TImage::PixelType PixelType ; typedef typename itk::PixelTraits< PixelType >::ValueType MeasurementType ; itkStaticConstMacro( MeasurementVectorSize, unsigned int, itk::PixelTraits< PixelType >::Dimension ) ; typedef TMeasurementVector MeasurementVectorType ; unsigned int Size() const { return 1 ;} float GetTotalFrequency() const { return 1 ;} float GetFrequency(const unsigned long& id) const { return id ; } virtual MeasurementVectorType GetMeasurementVector(const unsigned long& id) { if( m_UseBuffer ) { return *(reinterpret_cast< MeasurementVectorType* > (&(*m_ImageBuffer)[id])) ; } else { return *(reinterpret_cast< MeasurementVectorType* > (&(m_Image->GetPixel( m_Image->ComputeIndex( id ))) ) ) ; } } void SetImage( TImage* image ) { m_Image = image ; m_ImageBuffer = m_Image->GetPixelContainer() ; if ( strcmp( m_Image->GetNameOfClass(), "Image" ) != 0 ) { m_UseBuffer = false ; } else { m_UseBuffer = true ; } } protected: DummyImageToListAdaptor() { m_Image = 0 ; } virtual ~DummyImageToListAdaptor() {} typename TImage::Pointer m_Image ; typename TImage::PixelContainer* m_ImageBuffer ; MeasurementVectorType m_TempVector ; bool m_UseBuffer ; private: DummyImageToListAdaptor(const Self&) ; void operator=(const Self&) ; } ; template < class TImage > class ITK_EXPORT DummyScalarImageToListAdaptor : public DummyImageToListAdaptor< TImage, itk::FixedArray< typename TImage::PixelType, 1> > { public: typedef DummyScalarImageToListAdaptor Self ; typedef DummyImageToListAdaptor< TImage, itk::FixedArray< typename TImage::PixelType, 1> > Superclass ; typedef itk::SmartPointer< Self > Pointer ; typedef itk::SmartPointer< const Self > ConstPointer ; itkTypeMacro( DummyScalarImageToListAdaptor, DummyImageToListAdaptor ) ; itkNewMacro( Self ) ; typedef typename Superclass::MeasurementVectorType MeasurementVectorType ; MeasurementVectorType GetMeasurementVector(const unsigned long& id) { if( m_UseBuffer ) { m_TempVector[0] = (*m_ImageBuffer)[id] ; } else { m_TempVector[0] = m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ; } return m_TempVector ; } protected: DummyScalarImageToListAdaptor() {} virtual ~DummyScalarImageToListAdaptor() {} } ; // end of class template< class TImage, class TCoordRep > struct ImageJointDomainTraits { typedef ImageJointDomainTraits Self ; typedef itk::PixelTraits< typename TImage::PixelType > PixelTraitsType ; itkStaticConstMacro(Size, unsigned int, TImage::ImageDimension + PixelTraitsType::Dimension ) ; typedef itk::JoinTraits< TCoordRep, typename PixelTraitsType::ValueType > JoinTraitsType ; typedef typename JoinTraitsType::ValueType MeasurementType ; typedef itk::FixedArray< MeasurementType, itkGetStaticConstMacro(Size) > MeasurementVectorType ; } ; // end of ImageJointDomainTraits template < class TImage, class TCoordRep > class ITK_EXPORT DummyJointDomainImageToListAdaptor : public DummyImageToListAdaptor< TImage, typename ImageJointDomainTraits< TImage, TCoordRep >::MeasurementVectorType > { public: typedef DummyJointDomainImageToListAdaptor Self ; typedef DummyImageToListAdaptor< TImage, typename ImageJointDomainTraits< TImage, TCoordRep >::MeasurementVectorType > Superclass ; typedef itk::SmartPointer< Self > Pointer ; typedef itk::SmartPointer< const Self > ConstPointer ; itkTypeMacro( DummyJointDomainImageToListAdaptor, DummyImageToListAdaptor ) ; itkNewMacro( Self ) ; typedef typename Superclass::MeasurementType MeasurementType ; typedef typename Superclass::MeasurementVectorType MeasurementVectorType ; itkStaticConstMacro(RangeDomainDimension, unsigned int, itk::PixelTraits< typename TImage::PixelType >::Dimension) ; typedef typename itk::FixedArray< MeasurementType, itkGetStaticConstMacro( RangeDomainDimension ) > RangeDomainMeasurementVectorType ; MeasurementVectorType GetMeasurementVector(const unsigned long& id) { typename itk::Point<MeasurementType, TImage::ImageDimension> point ; typename TImage::IndexType index = m_Image->ComputeIndex( id ) ; m_Image->TransformIndexToPhysicalPoint( index, point ) ; for ( unsigned int i = 0 ; i < TImage::ImageDimension ; ++i ) { m_TempVector[i] = point[i] ; } if( m_UseBuffer ) { m_TempVector2 = *(reinterpret_cast< RangeDomainMeasurementVectorType* > (&(*m_ImageBuffer)[id])) ; } else { m_TempVector2 = *(reinterpret_cast< RangeDomainMeasurementVectorType* > (&(m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ) ) ) ; } for ( unsigned int i = TImage::ImageDimension ; i < MeasurementVectorType::Length ; ++i ) { m_TempVector[i]= m_TempVector2[i - TImage::ImageDimension] ; } return m_TempVector ; } protected: DummyJointDomainImageToListAdaptor() {} virtual ~DummyJointDomainImageToListAdaptor() {} RangeDomainMeasurementVectorType m_TempVector2 ; } ; // end of class int itkDummyImageToListAdaptorTest(int, char* [] ) { typedef int ScalarPixelType ; typedef itk::FixedArray< ScalarPixelType, 1 > ArrayPixelType ; typedef itk::Vector< ScalarPixelType, 2 > VectorPixelType ; typedef itk::Image< ScalarPixelType, 3 > ScalarImageType ; typedef itk::Image< ArrayPixelType, 3 > ArrayImageType ; typedef itk::Image< VectorPixelType, 3 > VectorImageType ; typedef itk::ImageRegionIterator< ScalarImageType > ScalarImageIteratorType ; typedef itk::ImageRegionIterator< ArrayImageType > ArrayImageIteratorType ; typedef itk::ImageRegionIterator< VectorImageType > VectorImageIteratorType ; itk::Size< 3 > size ; size.Fill(10) ; ScalarImageType::Pointer scalarImage = ScalarImageType::New() ; scalarImage->SetRegions(size) ; scalarImage->Allocate() ; int count = 0 ; ScalarImageIteratorType s_iter = ScalarImageIteratorType(scalarImage, scalarImage->GetLargestPossibleRegion() ) ; while ( !s_iter.IsAtEnd() ) { s_iter.Set(count) ; ++count ; ++s_iter ; } VectorImageType::Pointer vectorImage = VectorImageType::New() ; vectorImage->SetRegions(size) ; vectorImage->Allocate() ; count = 0 ; VectorImageType::PixelType vPixel ; VectorImageIteratorType v_iter = VectorImageIteratorType(vectorImage, vectorImage->GetLargestPossibleRegion()) ; while ( !v_iter.IsAtEnd() ) { vPixel[0] = count ; vPixel[1] = count ; v_iter.Set( vPixel ) ; ++count ; ++v_iter ; } typedef DummyScalarImageToListAdaptor< ScalarImageType > ScalarListType ; ScalarListType::Pointer sList = ScalarListType::New() ; sList->SetImage( scalarImage ) ; typedef DummyImageToListAdaptor< VectorImageType > VectorListType ; VectorListType::Pointer vList = VectorListType::New() ; vList->SetImage( vectorImage ) ; typedef itk::ScalarToArrayCastImageFilter< ScalarImageType, ArrayImageType > CasterType ; CasterType::Pointer caster = CasterType::New() ; caster->SetInput( scalarImage ) ; caster->Update() ; typedef itk::Statistics::ImageToListAdaptor< ArrayImageType > ImageListType ; ImageListType::Pointer imageList = ImageListType::New() ; imageList->SetImage( caster->GetOutput() ) ; typedef DummyJointDomainImageToListAdaptor< VectorImageType, float > JointDomainImageListType ; JointDomainImageListType::Pointer jointDomainImageList = JointDomainImageListType::New() ; jointDomainImageList->SetImage( vectorImage ) ; std::cout << "Testing the each measurement values:" << std::endl ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { if ( sList->GetMeasurementVector( i )[0] != vList->GetMeasurementVector( i )[0] || sList->GetMeasurementVector( i )[0] != imageList->GetMeasurementVector( i )[0] || sList->GetMeasurementVector( i )[0] != jointDomainImageList->GetMeasurementVector( i )[3] ) { std::cout << "ERROR: measurement mismatch!!!" << std::endl ; return EXIT_FAILURE ; } } std::cout << std::endl ; std::cout << "Scalar image (casted) pixel access performance test:" << std::endl ; time_t begin = clock() ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { imageList->GetMeasurementVector( i ) ; } time_t end = clock() ; std::cout << "time: " << (double(end - begin) /CLOCKS_PER_SEC) << " seconds" << std::endl ; std::cout << "Scalar image pixel access performance test:" << std::endl ; begin = clock() ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { sList->GetMeasurementVector( i ) ; } end = clock() ; std::cout << "time: " << (double(end - begin) /CLOCKS_PER_SEC) << " seconds" << std::endl ; std::cout << "Vector image pixel access performance test:" << std::endl ; begin = clock() ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { vList->GetMeasurementVector( i ) ; } end = clock() ; std::cout << "time: " << (double(end - begin) /CLOCKS_PER_SEC) << " seconds" << std::endl ; std::cout << "Joint Domain Vector image pixel access performance test:" << std::endl ; begin = clock() ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { std::cout << jointDomainImageList->GetMeasurementVector( i ) << std::endl ; } end = clock() ; std::cout << "time: " << (double(end - begin) /CLOCKS_PER_SEC) << " seconds" << std::endl ; return EXIT_SUCCESS ; } <|endoftext|>
<commit_before>#include <blackhole/formatter/string.hpp> #include <blackhole/log.hpp> #include <blackhole/logger.hpp> #include <blackhole/logger/wrapper.hpp> #include <blackhole/record.hpp> #include <blackhole/sink/stream.hpp> #include "global.hpp" using namespace blackhole; namespace { class logger_factory_t { public: template<class Logger> static Logger create() { Logger logger; auto formatter = utils::make_unique< formatter::string_t >("[%(timestamp)s]: %(message)s"); auto sink = utils::make_unique< sink::stream_t >(sink::stream_t::output_t::stdout); auto frontend = utils::make_unique< frontend_t< formatter::string_t, sink::stream_t > >(std::move(formatter), std::move(sink)); logger.add_frontend(std::move(frontend)); return logger; } }; } // namespace TEST(Wrapper, Class) { verbose_logger_t<testing::level> log; wrapper_t<verbose_logger_t<testing::level>> wrapper(log, log::attributes_t({ attribute::make("answer", 42) })); UNUSED(wrapper); } TEST(Wrapper, Usage) { auto log = logger_factory_t::create<logger_base_t>(); log.add_attribute(attribute::make("id", 100500)); { wrapper_t<logger_base_t> wrapper(log, log::attributes_t({ attribute::make("answer", 42) })); auto record = log.open_record(); ASSERT_EQ(1, record.attributes.count("id")); EXPECT_EQ(log::attribute_value_t(100500), record.attributes["id"].value); EXPECT_EQ(0, record.attributes.count("answer")); record = wrapper.open_record(); ASSERT_EQ(1, record.attributes.count("id")); EXPECT_EQ(log::attribute_value_t(100500), record.attributes["id"].value); ASSERT_EQ(1, record.attributes.count("answer")); EXPECT_EQ(log::attribute_value_t(42), record.attributes["answer"].value); } auto record = log.open_record(); ASSERT_EQ(1, record.attributes.count("id")); EXPECT_EQ(log::attribute_value_t(100500), record.attributes["id"].value); EXPECT_EQ(0, record.attributes.count("answer")); } TEST(Wrapper, UsageWithVerboseLogger) { auto log = logger_factory_t::create<verbose_logger_t<testing::level>>(); log.add_attribute(attribute::make("id", 100500)); { wrapper_t<verbose_logger_t<testing::level>> wrapper( log, log::attributes_t({ attribute::make("answer", 42) }) ); auto record = log.open_record(testing::info); ASSERT_EQ(1, record.attributes.count("id")); EXPECT_EQ(log::attribute_value_t(100500), record.attributes["id"].value); ASSERT_EQ(1, record.attributes.count("severity")); EXPECT_EQ(testing::info, boost::get< aux::underlying_type<testing::level>::type >(record.attributes["severity"].value) ); EXPECT_EQ(0, record.attributes.count("answer")); record = wrapper.open_record(testing::info); ASSERT_EQ(1, record.attributes.count("id")); EXPECT_EQ(log::attribute_value_t(100500), record.attributes["id"].value); ASSERT_EQ(1, record.attributes.count("severity")); EXPECT_EQ(testing::info, boost::get< aux::underlying_type<testing::level>::type >(record.attributes["severity"].value) ); ASSERT_EQ(1, record.attributes.count("answer")); EXPECT_EQ(log::attribute_value_t(42), record.attributes["answer"].value); } auto record = log.open_record(testing::info); ASSERT_EQ(1, record.attributes.count("id")); EXPECT_EQ(log::attribute_value_t(100500), record.attributes["id"].value); ASSERT_EQ(1, record.attributes.count("severity")); EXPECT_EQ(testing::info, boost::get< aux::underlying_type<testing::level>::type >(record.attributes["severity"].value) ); EXPECT_EQ(0, record.attributes.count("answer")); } TEST(Wrapper, MacroUsage) { auto log = logger_factory_t::create<verbose_logger_t<testing::level>>(); log.add_attribute(attribute::make("id", 100500)); { wrapper_t<verbose_logger_t<testing::level>> wrapper( log, log::attributes_t({ attribute::make("answer", 42) }) ); BH_LOG(wrapper, testing::info, "everything is bad"); } } <commit_msg>[Unit Testing] No more spam from testing logger.<commit_after>#include <blackhole/formatter/string.hpp> #include <blackhole/log.hpp> #include <blackhole/logger.hpp> #include <blackhole/logger/wrapper.hpp> #include <blackhole/record.hpp> #include <blackhole/sink/null.hpp> #include "global.hpp" using namespace blackhole; namespace { class logger_factory_t { public: template<class Logger> static Logger create() { Logger logger; auto formatter = utils::make_unique< formatter::string_t >("[%(timestamp)s]: %(message)s"); auto sink = utils::make_unique< sink::null_t >(); auto frontend = utils::make_unique< frontend_t< formatter::string_t, sink::null_t > >(std::move(formatter), std::move(sink)); logger.add_frontend(std::move(frontend)); return logger; } }; } // namespace TEST(Wrapper, Class) { verbose_logger_t<testing::level> log; wrapper_t<verbose_logger_t<testing::level>> wrapper(log, log::attributes_t({ attribute::make("answer", 42) })); UNUSED(wrapper); } TEST(Wrapper, Usage) { auto log = logger_factory_t::create<logger_base_t>(); log.add_attribute(attribute::make("id", 100500)); { wrapper_t<logger_base_t> wrapper(log, log::attributes_t({ attribute::make("answer", 42) })); auto record = log.open_record(); ASSERT_EQ(1, record.attributes.count("id")); EXPECT_EQ(log::attribute_value_t(100500), record.attributes["id"].value); EXPECT_EQ(0, record.attributes.count("answer")); record = wrapper.open_record(); ASSERT_EQ(1, record.attributes.count("id")); EXPECT_EQ(log::attribute_value_t(100500), record.attributes["id"].value); ASSERT_EQ(1, record.attributes.count("answer")); EXPECT_EQ(log::attribute_value_t(42), record.attributes["answer"].value); } auto record = log.open_record(); ASSERT_EQ(1, record.attributes.count("id")); EXPECT_EQ(log::attribute_value_t(100500), record.attributes["id"].value); EXPECT_EQ(0, record.attributes.count("answer")); } TEST(Wrapper, UsageWithVerboseLogger) { auto log = logger_factory_t::create<verbose_logger_t<testing::level>>(); log.add_attribute(attribute::make("id", 100500)); { wrapper_t<verbose_logger_t<testing::level>> wrapper( log, log::attributes_t({ attribute::make("answer", 42) }) ); auto record = log.open_record(testing::info); ASSERT_EQ(1, record.attributes.count("id")); EXPECT_EQ(log::attribute_value_t(100500), record.attributes["id"].value); ASSERT_EQ(1, record.attributes.count("severity")); EXPECT_EQ(testing::info, boost::get< aux::underlying_type<testing::level>::type >(record.attributes["severity"].value) ); EXPECT_EQ(0, record.attributes.count("answer")); record = wrapper.open_record(testing::info); ASSERT_EQ(1, record.attributes.count("id")); EXPECT_EQ(log::attribute_value_t(100500), record.attributes["id"].value); ASSERT_EQ(1, record.attributes.count("severity")); EXPECT_EQ(testing::info, boost::get< aux::underlying_type<testing::level>::type >(record.attributes["severity"].value) ); ASSERT_EQ(1, record.attributes.count("answer")); EXPECT_EQ(log::attribute_value_t(42), record.attributes["answer"].value); } auto record = log.open_record(testing::info); ASSERT_EQ(1, record.attributes.count("id")); EXPECT_EQ(log::attribute_value_t(100500), record.attributes["id"].value); ASSERT_EQ(1, record.attributes.count("severity")); EXPECT_EQ(testing::info, boost::get< aux::underlying_type<testing::level>::type >(record.attributes["severity"].value) ); EXPECT_EQ(0, record.attributes.count("answer")); } TEST(Wrapper, MacroUsage) { auto log = logger_factory_t::create<verbose_logger_t<testing::level>>(); log.add_attribute(attribute::make("id", 100500)); { wrapper_t<verbose_logger_t<testing::level>> wrapper( log, log::attributes_t({ attribute::make("answer", 42) }) ); BH_LOG(wrapper, testing::info, "everything is bad"); } } <|endoftext|>
<commit_before>#include <possumwood_sdk/node_implementation.h> #include <CGAL/squared_distance_3.h> #include <CGAL/Surface_mesh_simplification/edge_collapse.h> #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Count_stop_predicate.h> #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Count_ratio_stop_predicate.h> #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Edge_length_stop_predicate.h> #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Edge_length_cost.h> #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/LindstromTurk_cost.h> #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Midpoint_placement.h> #include "possumwood_sdk/datatypes/enum.h" #include "datatypes/polyhedron.h" #include "cgal.h" namespace SMS = CGAL::Surface_mesh_simplification; using namespace std::placeholders; namespace { dependency_graph::InAttr<std::shared_ptr<const possumwood::CGALPolyhedron>> a_inMesh; dependency_graph::InAttr<float> a_stopParam; dependency_graph::InAttr<possumwood::Enum> a_stopCondition, a_cost; dependency_graph::OutAttr<std::shared_ptr<const possumwood::CGALPolyhedron>> a_outMesh; dependency_graph::State compute(dependency_graph::Values& data) { std::shared_ptr<const possumwood::CGALPolyhedron> inMesh = data.get(a_inMesh); const float stopCondition = data.get(a_stopParam); const unsigned algorithmId = data.get(a_stopCondition).intValue() + data.get(a_cost).intValue(); if(inMesh) { std::unique_ptr<possumwood::CGALPolyhedron> mesh(new possumwood::CGALPolyhedron(*inMesh)); switch(algorithmId) { case 11: SMS::edge_collapse(*mesh, SMS::Count_stop_predicate<possumwood::CGALPolyhedron>(stopCondition), CGAL::parameters::get_cost(SMS::Edge_length_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::Midpoint_placement<possumwood::CGALPolyhedron>())); break; case 12: SMS::edge_collapse(*mesh, SMS::Count_ratio_stop_predicate<possumwood::CGALPolyhedron>(stopCondition), CGAL::parameters::get_cost(SMS::Edge_length_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::Midpoint_placement<possumwood::CGALPolyhedron>())); break; case 13: SMS::edge_collapse(*mesh, SMS::Edge_length_stop_predicate<float>(stopCondition), CGAL::parameters::get_cost(SMS::Edge_length_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::Midpoint_placement<possumwood::CGALPolyhedron>())); break; case 21: SMS::edge_collapse(*mesh, SMS::Count_stop_predicate<possumwood::CGALPolyhedron>(stopCondition), CGAL::parameters::get_cost(SMS::LindstromTurk_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::Midpoint_placement<possumwood::CGALPolyhedron>())); break; case 22: SMS::edge_collapse(*mesh, SMS::Count_ratio_stop_predicate<possumwood::CGALPolyhedron>(stopCondition), CGAL::parameters::get_cost(SMS::LindstromTurk_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::Midpoint_placement<possumwood::CGALPolyhedron>())); break; case 23: SMS::edge_collapse(*mesh, SMS::Edge_length_stop_predicate<float>(stopCondition), CGAL::parameters::get_cost(SMS::LindstromTurk_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::Midpoint_placement<possumwood::CGALPolyhedron>())); break; } data.set(a_outMesh, std::shared_ptr<const possumwood::CGALPolyhedron>(mesh.release())); } else data.set(a_outMesh, std::shared_ptr<const possumwood::CGALPolyhedron>()); return dependency_graph::State(); } void init(possumwood::Metadata& meta) { meta.addAttribute(a_inMesh, "input"); meta.addAttribute( a_stopCondition, "stop_condition", possumwood::Enum({std::make_pair("Count_stop_predicate", 1), std::make_pair("Count_ratio_stop_predicate", 2), std::make_pair("Edge_length_stop_predicate", 3)})); meta.addAttribute(a_cost, "cost", possumwood::Enum({std::make_pair("Edge_length_cost", 10), std::make_pair("LindstromTurk_cost", 20)})); meta.addAttribute(a_stopParam, "stop_parameter", 1000.0f); meta.addAttribute(a_outMesh, "output"); meta.addInfluence(a_inMesh, a_outMesh); meta.addInfluence(a_stopCondition, a_outMesh); meta.addInfluence(a_cost, a_outMesh); meta.addInfluence(a_stopParam, a_outMesh); meta.setCompute(compute); } possumwood::NodeImplementation s_impl("cgal/simplification/simplification", init); } <commit_msg>Added placement dropdown to CGAL mesh simplification<commit_after>#include <possumwood_sdk/node_implementation.h> #include <CGAL/squared_distance_3.h> #include <CGAL/Surface_mesh_simplification/edge_collapse.h> #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Count_stop_predicate.h> #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Count_ratio_stop_predicate.h> #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Edge_length_stop_predicate.h> #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Edge_length_cost.h> #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/LindstromTurk_cost.h> #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Midpoint_placement.h> #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/LindstromTurk_placement.h> // #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Constrained_placement.h> // #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Bounded_normal_change_placement.h> #include "possumwood_sdk/datatypes/enum.h" #include "datatypes/polyhedron.h" #include "cgal.h" namespace SMS = CGAL::Surface_mesh_simplification; using namespace std::placeholders; namespace { dependency_graph::InAttr<std::shared_ptr<const possumwood::CGALPolyhedron>> a_inMesh; dependency_graph::InAttr<float> a_stopParam; dependency_graph::InAttr<possumwood::Enum> a_stopCondition, a_cost, a_placement; dependency_graph::OutAttr<std::shared_ptr<const possumwood::CGALPolyhedron>> a_outMesh; dependency_graph::State compute(dependency_graph::Values& data) { std::shared_ptr<const possumwood::CGALPolyhedron> inMesh = data.get(a_inMesh); const float stopCondition = data.get(a_stopParam); const unsigned algorithmId = data.get(a_stopCondition).intValue() + data.get(a_cost).intValue() + data.get(a_placement).intValue(); if(inMesh) { std::unique_ptr<possumwood::CGALPolyhedron> mesh(new possumwood::CGALPolyhedron(*inMesh)); // this is just horrible - need to find a better way switch(algorithmId) { case 111: SMS::edge_collapse(*mesh, SMS::Count_stop_predicate<possumwood::CGALPolyhedron>(stopCondition), CGAL::parameters::get_cost(SMS::Edge_length_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::Midpoint_placement<possumwood::CGALPolyhedron>())); break; case 112: SMS::edge_collapse(*mesh, SMS::Count_ratio_stop_predicate<possumwood::CGALPolyhedron>(stopCondition), CGAL::parameters::get_cost(SMS::Edge_length_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::Midpoint_placement<possumwood::CGALPolyhedron>())); break; case 113: SMS::edge_collapse(*mesh, SMS::Edge_length_stop_predicate<float>(stopCondition), CGAL::parameters::get_cost(SMS::Edge_length_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::Midpoint_placement<possumwood::CGALPolyhedron>())); break; case 121: SMS::edge_collapse(*mesh, SMS::Count_stop_predicate<possumwood::CGALPolyhedron>(stopCondition), CGAL::parameters::get_cost(SMS::LindstromTurk_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::Midpoint_placement<possumwood::CGALPolyhedron>())); break; case 122: SMS::edge_collapse(*mesh, SMS::Count_ratio_stop_predicate<possumwood::CGALPolyhedron>(stopCondition), CGAL::parameters::get_cost(SMS::LindstromTurk_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::Midpoint_placement<possumwood::CGALPolyhedron>())); break; case 123: SMS::edge_collapse(*mesh, SMS::Edge_length_stop_predicate<float>(stopCondition), CGAL::parameters::get_cost(SMS::LindstromTurk_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::Midpoint_placement<possumwood::CGALPolyhedron>())); break; case 211: SMS::edge_collapse(*mesh, SMS::Count_stop_predicate<possumwood::CGALPolyhedron>(stopCondition), CGAL::parameters::get_cost(SMS::Edge_length_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::LindstromTurk_placement<possumwood::CGALPolyhedron>())); break; case 212: SMS::edge_collapse(*mesh, SMS::Count_ratio_stop_predicate<possumwood::CGALPolyhedron>(stopCondition), CGAL::parameters::get_cost(SMS::Edge_length_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::LindstromTurk_placement<possumwood::CGALPolyhedron>())); break; case 213: SMS::edge_collapse(*mesh, SMS::Edge_length_stop_predicate<float>(stopCondition), CGAL::parameters::get_cost(SMS::Edge_length_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::LindstromTurk_placement<possumwood::CGALPolyhedron>())); break; case 221: SMS::edge_collapse(*mesh, SMS::Count_stop_predicate<possumwood::CGALPolyhedron>(stopCondition), CGAL::parameters::get_cost(SMS::LindstromTurk_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::LindstromTurk_placement<possumwood::CGALPolyhedron>())); break; case 222: SMS::edge_collapse(*mesh, SMS::Count_ratio_stop_predicate<possumwood::CGALPolyhedron>(stopCondition), CGAL::parameters::get_cost(SMS::LindstromTurk_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::LindstromTurk_placement<possumwood::CGALPolyhedron>())); break; case 223: SMS::edge_collapse(*mesh, SMS::Edge_length_stop_predicate<float>(stopCondition), CGAL::parameters::get_cost(SMS::LindstromTurk_cost<possumwood::CGALPolyhedron>()) .get_placement(SMS::LindstromTurk_placement<possumwood::CGALPolyhedron>())); break; } data.set(a_outMesh, std::shared_ptr<const possumwood::CGALPolyhedron>(mesh.release())); } else data.set(a_outMesh, std::shared_ptr<const possumwood::CGALPolyhedron>()); return dependency_graph::State(); } void init(possumwood::Metadata& meta) { meta.addAttribute(a_inMesh, "input"); meta.addAttribute( a_stopCondition, "stop_condition", possumwood::Enum({std::make_pair("Count_stop_predicate", 1), std::make_pair("Count_ratio_stop_predicate", 2), std::make_pair("Edge_length_stop_predicate", 3)})); meta.addAttribute(a_cost, "cost", possumwood::Enum({std::make_pair("Edge_length_cost", 10), std::make_pair("LindstromTurk_cost", 20)})); meta.addAttribute(a_placement, "placement", possumwood::Enum({std::make_pair("Midpoint_placement", 100), std::make_pair("LindstromTurk_placement", 200)})); meta.addAttribute(a_stopParam, "stop_parameter", 1000.0f); meta.addAttribute(a_outMesh, "output"); meta.addInfluence(a_inMesh, a_outMesh); meta.addInfluence(a_stopCondition, a_outMesh); meta.addInfluence(a_cost, a_outMesh); meta.addInfluence(a_placement, a_outMesh); meta.addInfluence(a_stopParam, a_outMesh); meta.setCompute(compute); } possumwood::NodeImplementation s_impl("cgal/simplification/simplification", init); } <|endoftext|>
<commit_before>/* ******************************************************************************* * * Copyright (C) 1999-2001, International Business Machines * Corporation and others. All Rights Reserved. * ******************************************************************************* * file name: scrptrun.cpp * * created on: 10/17/2001 * created by: Eric R. Mader * * NOTE: This file is copied from ICU. * http://source.icu-project.org/repos/icu/icu/trunk/license.html */ #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <unicode/utypes.h> #include <unicode/uscript.h> #pragma GCC diagnostic pop #include <mapnik/text/scrptrun.hpp> #define ARRAY_SIZE(array) (sizeof array / sizeof array[0]) UChar32 ScriptRun::pairedChars[] = { 0x0028, 0x0029, // ascii paired punctuation 0x003c, 0x003e, 0x005b, 0x005d, 0x007b, 0x007d, 0x00ab, 0x00bb, // guillemets 0x2018, 0x2019, // general punctuation 0x201c, 0x201d, 0x2039, 0x203a, 0x3008, 0x3009, // chinese paired punctuation 0x300a, 0x300b, 0x300c, 0x300d, 0x300e, 0x300f, 0x3010, 0x3011, 0x3014, 0x3015, 0x3016, 0x3017, 0x3018, 0x3019, 0x301a, 0x301b }; const int32_t ScriptRun::pairedCharCount = ARRAY_SIZE(pairedChars); const int32_t ScriptRun::pairedCharPower = 1 << highBit(pairedCharCount); const int32_t ScriptRun::pairedCharExtra = pairedCharCount - pairedCharPower; int8_t ScriptRun::highBit(int32_t value) { if (value <= 0) { return -32; } int8_t bit = 0; if (value >= 1 << 16) { value >>= 16; bit += 16; } if (value >= 1 << 8) { value >>= 8; bit += 8; } if (value >= 1 << 4) { value >>= 4; bit += 4; } if (value >= 1 << 2) { value >>= 2; bit += 2; } if (value >= 1 << 1) { value >>= 1; bit += 1; } return bit; } int32_t ScriptRun::getPairIndex(UChar32 ch) { int32_t probe = pairedCharPower; int32_t index = 0; if (ch >= pairedChars[pairedCharExtra]) { index = pairedCharExtra; } while (probe > (1 << 0)) { probe >>= 1; if (ch >= pairedChars[index + probe]) { index += probe; } } if (pairedChars[index] != ch) { index = -1; } return index; } UBool ScriptRun::sameScript(int32_t scriptOne, int32_t scriptTwo) { return scriptOne <= USCRIPT_INHERITED || scriptTwo <= USCRIPT_INHERITED || scriptOne == scriptTwo; } UBool ScriptRun::next() { int32_t startSP = parenSP; // used to find the first new open character UErrorCode error = U_ZERO_ERROR; // if we've fallen off the end of the text, we're done if (scriptEnd >= charLimit) { return false; } scriptCode = USCRIPT_COMMON; for (scriptStart = scriptEnd; scriptEnd < charLimit; scriptEnd += 1) { UChar high = charArray[scriptEnd]; UChar32 ch = high; // if the character is a high surrogate and it's not the last one // in the text, see if it's followed by a low surrogate if (high >= 0xD800 && high <= 0xDBFF && scriptEnd < charLimit - 1) { UChar low = charArray[scriptEnd + 1]; // if it is followed by a low surrogate, // consume it and form the full character if (low >= 0xDC00 && low <= 0xDFFF) { ch = (high - 0xD800) * 0x0400 + low - 0xDC00 + 0x10000; scriptEnd += 1; } } UScriptCode sc = uscript_getScript(ch, &error); int32_t pairIndex = getPairIndex(ch); // Paired character handling: // // if it's an open character, push it onto the stack. // if it's a close character, find the matching open on the // stack, and use that script code. Any non-matching open // characters above it on the stack will be poped. if (pairIndex >= 0) { if ((pairIndex & 1) == 0) { parenStack[++parenSP].pairIndex = pairIndex; parenStack[parenSP].scriptCode = scriptCode; } else if (parenSP >= 0) { int32_t pi = pairIndex & ~1; while (parenSP >= 0 && parenStack[parenSP].pairIndex != pi) { parenSP -= 1; } if (parenSP < startSP) { startSP = parenSP; } if (parenSP >= 0) { sc = parenStack[parenSP].scriptCode; } } } if (sameScript(scriptCode, sc)) { if (scriptCode <= USCRIPT_INHERITED && sc > USCRIPT_INHERITED) { scriptCode = sc; // now that we have a final script code, fix any open // characters we pushed before we knew the script code. while (startSP < parenSP) { parenStack[++startSP].scriptCode = scriptCode; } } // if this character is a close paired character, // pop it from the stack if (pairIndex >= 0 && (pairIndex & 1) != 0 && parenSP >= 0) { parenSP -= 1; startSP -= 1; } } else { // if the run broke on a surrogate pair, // end it before the high surrogate if (ch >= 0x10000) { scriptEnd -= 1; } break; } } return true; } <commit_msg>Fix buffer overflow<commit_after>/* ******************************************************************************* * * Copyright (C) 1999-2001, International Business Machines * Corporation and others. All Rights Reserved. * ******************************************************************************* * file name: scrptrun.cpp * * created on: 10/17/2001 * created by: Eric R. Mader * * NOTE: This file is copied from ICU. * http://source.icu-project.org/repos/icu/icu/trunk/license.html */ #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <unicode/utypes.h> #include <unicode/uscript.h> #pragma GCC diagnostic pop #include <mapnik/text/scrptrun.hpp> #include <algorithm> #define ARRAY_SIZE(array) (sizeof array / sizeof array[0]) UChar32 ScriptRun::pairedChars[] = { 0x0028, 0x0029, // ascii paired punctuation 0x003c, 0x003e, 0x005b, 0x005d, 0x007b, 0x007d, 0x00ab, 0x00bb, // guillemets 0x2018, 0x2019, // general punctuation 0x201c, 0x201d, 0x2039, 0x203a, 0x3008, 0x3009, // chinese paired punctuation 0x300a, 0x300b, 0x300c, 0x300d, 0x300e, 0x300f, 0x3010, 0x3011, 0x3014, 0x3015, 0x3016, 0x3017, 0x3018, 0x3019, 0x301a, 0x301b }; const int32_t ScriptRun::pairedCharCount = ARRAY_SIZE(pairedChars); const int32_t ScriptRun::pairedCharPower = 1 << highBit(pairedCharCount); const int32_t ScriptRun::pairedCharExtra = pairedCharCount - pairedCharPower; int8_t ScriptRun::highBit(int32_t value) { if (value <= 0) { return -32; } int8_t bit = 0; if (value >= 1 << 16) { value >>= 16; bit += 16; } if (value >= 1 << 8) { value >>= 8; bit += 8; } if (value >= 1 << 4) { value >>= 4; bit += 4; } if (value >= 1 << 2) { value >>= 2; bit += 2; } if (value >= 1 << 1) { value >>= 1; bit += 1; } return bit; } int32_t ScriptRun::getPairIndex(UChar32 ch) { int32_t probe = pairedCharPower; int32_t index = 0; if (ch >= pairedChars[pairedCharExtra]) { index = pairedCharExtra; } while (probe > (1 << 0)) { probe >>= 1; if (ch >= pairedChars[index + probe]) { index += probe; } } if (pairedChars[index] != ch) { index = -1; } return index; } UBool ScriptRun::sameScript(int32_t scriptOne, int32_t scriptTwo) { return scriptOne <= USCRIPT_INHERITED || scriptTwo <= USCRIPT_INHERITED || scriptOne == scriptTwo; } UBool ScriptRun::next() { int32_t startSP = parenSP; // used to find the first new open character UErrorCode error = U_ZERO_ERROR; // if we've fallen off the end of the text, we're done if (scriptEnd >= charLimit) { return false; } scriptCode = USCRIPT_COMMON; for (scriptStart = scriptEnd; scriptEnd < charLimit; scriptEnd += 1) { UChar high = charArray[scriptEnd]; UChar32 ch = high; // if the character is a high surrogate and it's not the last one // in the text, see if it's followed by a low surrogate if (high >= 0xD800 && high <= 0xDBFF && scriptEnd < charLimit - 1) { UChar low = charArray[scriptEnd + 1]; // if it is followed by a low surrogate, // consume it and form the full character if (low >= 0xDC00 && low <= 0xDFFF) { ch = (high - 0xD800) * 0x0400 + low - 0xDC00 + 0x10000; scriptEnd += 1; } } UScriptCode sc = uscript_getScript(ch, &error); int32_t pairIndex = getPairIndex(ch); // Paired character handling: // // if it's an open character, push it onto the stack. // if it's a close character, find the matching open on the // stack, and use that script code. Any non-matching open // characters above it on the stack will be poped. if (pairIndex >= 0) { if ((pairIndex & 1) == 0) { parenStack[++parenSP].pairIndex = pairIndex; parenStack[parenSP].scriptCode = scriptCode; } else if (parenSP >= 0) { int32_t pi = pairIndex & ~1; while (parenSP >= 0 && parenStack[parenSP].pairIndex != pi) { parenSP -= 1; } if (parenSP < startSP) { startSP = parenSP; } if (parenSP >= 0) { sc = parenStack[parenSP].scriptCode; } } } if (sameScript(scriptCode, sc)) { if (scriptCode <= USCRIPT_INHERITED && sc > USCRIPT_INHERITED) { scriptCode = sc; // now that we have a final script code, fix any open // characters we pushed before we knew the script code. while (startSP < parenSP) { parenStack[++startSP].scriptCode = scriptCode; } } // if this character is a close paired character, // pop it from the stack if (pairIndex >= 0 && (pairIndex & 1) != 0 && parenSP >= 0) { parenSP -= 1; startSP = std::max(-1, startSP - 1); } } else { // if the run broke on a surrogate pair, // end it before the high surrogate if (ch >= 0x10000) { scriptEnd -= 1; } break; } } return true; } <|endoftext|>
<commit_before><commit_msg>No need to trim capacity any more; it's allocated to the exact size.<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: editsrc.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: nn $ $Date: 2001-02-15 18:07:09 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop #ifndef _SFXSMPLHINT_HXX //autogen #include <svtools/smplhint.hxx> #endif #include "scitems.hxx" #include <tools/debug.hxx> #include <svx/editeng.hxx> #include <svx/unofored.hxx> #include <svx/editobj.hxx> #include "textuno.hxx" #include "editsrc.hxx" #include "editutil.hxx" #include "docsh.hxx" #include "docfunc.hxx" #include "cell.hxx" #include "hints.hxx" #include "patattr.hxx" #include "scmod.hxx" #include "unoguard.hxx" //------------------------------------------------------------------------ TYPEINIT1( ScHeaderFooterChangedHint, SfxHint ); ScHeaderFooterChangedHint::ScHeaderFooterChangedHint(USHORT nP) : nPart( nP ) { } ScHeaderFooterChangedHint::~ScHeaderFooterChangedHint() { } //------------------------------------------------------------------------ ScHeaderFooterEditSource::ScHeaderFooterEditSource( ScHeaderFooterContentObj* pContent, USHORT nP ) : pContentObj( pContent ), nPart( nP ), pEditEngine( NULL ), pForwarder( NULL ), bDataValid( FALSE ), bInUpdate( FALSE ) { if (pContentObj) // pContentObj can be 0 if constructed via getReflection { pContentObj->acquire(); // must not go away pContentObj->AddListener( *this ); } } ScHeaderFooterEditSource::~ScHeaderFooterEditSource() { ScUnoGuard aGuard; // needed for EditEngine dtor if (pContentObj) pContentObj->RemoveListener( *this ); delete pForwarder; delete pEditEngine; if (pContentObj) pContentObj->release(); } SvxEditSource* ScHeaderFooterEditSource::Clone() const { return new ScHeaderFooterEditSource( pContentObj, nPart ); } SvxTextForwarder* ScHeaderFooterEditSource::GetTextForwarder() { if (!pEditEngine) { ScHeaderEditEngine* pHdrEngine = new ScHeaderEditEngine( EditEngine::CreatePool(), TRUE ); pHdrEngine->EnableUndo( FALSE ); pHdrEngine->SetRefMapMode( MAP_TWIP ); // default font must be set, independently of document // -> use global pool from module SfxItemSet aDefaults( pHdrEngine->GetEmptyItemSet() ); const ScPatternAttr& rPattern = (const ScPatternAttr&)SC_MOD()->GetPool().GetDefaultItem(ATTR_PATTERN); rPattern.FillEditItemSet( &aDefaults ); // FillEditItemSet adjusts font height to 1/100th mm, // but for header/footer twips is needed, as in the PatternAttr: aDefaults.Put( rPattern.GetItem(ATTR_FONT_HEIGHT), EE_CHAR_FONTHEIGHT ); aDefaults.Put( rPattern.GetItem(ATTR_CJK_FONT_HEIGHT), EE_CHAR_FONTHEIGHT_CJK ); aDefaults.Put( rPattern.GetItem(ATTR_CTL_FONT_HEIGHT), EE_CHAR_FONTHEIGHT_CTL ); pHdrEngine->SetDefaults( aDefaults ); ScHeaderFieldData aData; ScHeaderFooterTextObj::FillDummyFieldData( aData ); pHdrEngine->SetData( aData ); pEditEngine = pHdrEngine; pForwarder = new SvxEditEngineForwarder(*pEditEngine); } if (bDataValid) return pForwarder; if (pContentObj) { const EditTextObject* pData; if (nPart == SC_HDFT_LEFT) pData = pContentObj->GetLeftEditObject(); else if (nPart == SC_HDFT_CENTER) pData = pContentObj->GetCenterEditObject(); else pData = pContentObj->GetRightEditObject(); if (pData) pEditEngine->SetText(*pData); } bDataValid = TRUE; return pForwarder; } void ScHeaderFooterEditSource::UpdateData() { if ( pContentObj && pEditEngine ) { bInUpdate = TRUE; // don't reset bDataValid during UpdateText pContentObj->UpdateText( nPart, *pEditEngine ); bInUpdate = FALSE; } } void ScHeaderFooterEditSource::Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) { if ( rHint.ISA( ScHeaderFooterChangedHint ) ) { if ( ((const ScHeaderFooterChangedHint&)rHint).GetPart() == nPart ) { if (!bInUpdate) // not for own updates bDataValid = FALSE; // text has to be fetched again } } } //------------------------------------------------------------------------ ScCellEditSource::ScCellEditSource(ScDocShell* pDocSh, const ScAddress& rP) : pDocShell( pDocSh ), aCellPos( rP ), pEditEngine( NULL ), pForwarder( NULL ), bDataValid( FALSE ), bInUpdate( FALSE ) { if (pDocShell) pDocShell->GetDocument()->AddUnoObject(*this); } ScCellEditSource::~ScCellEditSource() { ScUnoGuard aGuard; // needed for EditEngine dtor if (pDocShell) pDocShell->GetDocument()->RemoveUnoObject(*this); delete pForwarder; delete pEditEngine; } SvxEditSource* ScCellEditSource::Clone() const { return new ScCellEditSource( pDocShell, aCellPos ); } SvxTextForwarder* ScCellEditSource::GetTextForwarder() { if (!pEditEngine) { if ( pDocShell ) { const ScDocument* pDoc = pDocShell->GetDocument(); pEditEngine = new ScFieldEditEngine( pDoc->GetEnginePool(), pDoc->GetEditPool(), FALSE ); } else pEditEngine = new ScFieldEditEngine( EditEngine::CreatePool(), NULL, TRUE ); #if SUPD > 600 // currently, GetPortions doesn't work if UpdateMode is FALSE, // this will be fixed (in EditEngine) by src600 // pEditEngine->SetUpdateMode( FALSE ); #endif pEditEngine->EnableUndo( FALSE ); pEditEngine->SetRefMapMode( MAP_100TH_MM ); pForwarder = new SvxEditEngineForwarder(*pEditEngine); } if (bDataValid) return pForwarder; BOOL bEditCell = FALSE; String aText; if (pDocShell) { ScDocument* pDoc = pDocShell->GetDocument(); const ScBaseCell* pCell = pDoc->GetCell( aCellPos ); if ( pCell && pCell->GetCellType() == CELLTYPE_EDIT ) { pEditEngine->SetText( *((const ScEditCell*)pCell)->GetData() ); bEditCell = TRUE; } else pDoc->GetInputString( aCellPos.Col(), aCellPos.Row(), aCellPos.Tab(), aText ); SfxItemSet aDefaults( pEditEngine->GetEmptyItemSet() ); const ScPatternAttr* pPattern = pDoc->GetPattern( aCellPos.Col(), aCellPos.Row(), aCellPos.Tab() ); pPattern->FillEditItemSet( &aDefaults ); pPattern->FillEditParaItems( &aDefaults ); // auch Ausrichtung etc. auslesbar pEditEngine->SetDefaults( aDefaults ); } if (!bEditCell) pEditEngine->SetText( aText ); bDataValid = TRUE; return pForwarder; } void ScCellEditSource::UpdateData() { if ( pDocShell && pEditEngine ) { // beim eigenen Update darf bDataValid nicht zurueckgesetzt werden, // damit z.B. Attribute hinter dem Text nicht verloren gehen // (werden in die Zelle nicht uebernommen) bInUpdate = TRUE; // damit wird bDataValid nicht zurueckgesetzt ScDocFunc aFunc(*pDocShell); aFunc.PutData( aCellPos, *pEditEngine, FALSE, TRUE ); // immer Text bInUpdate = FALSE; } } void ScCellEditSource::Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) { if ( rHint.ISA( ScUpdateRefHint ) ) { const ScUpdateRefHint& rRef = (const ScUpdateRefHint&)rHint; //! Ref-Update } else if ( rHint.ISA( SfxSimpleHint ) ) { ULONG nId = ((const SfxSimpleHint&)rHint).GetId(); if ( nId == SFX_HINT_DYING ) { pDocShell = NULL; // ungueltig geworden DELETEZ( pForwarder ); DELETEZ( pEditEngine ); // EditEngine uses document's pool } else if ( nId == SFX_HINT_DATACHANGED ) { if (!bInUpdate) // eigene Updates zaehlen nicht bDataValid = FALSE; // Text muss neu geholt werden } } } //------------------------------------------------------------------------ ScAnnotationEditSource::ScAnnotationEditSource(ScDocShell* pDocSh, const ScAddress& rP) : pDocShell( pDocSh ), aCellPos( rP ), pEditEngine( NULL ), pForwarder( NULL ), bDataValid( FALSE ) { if (pDocShell) pDocShell->GetDocument()->AddUnoObject(*this); } ScAnnotationEditSource::~ScAnnotationEditSource() { ScUnoGuard aGuard; // needed for EditEngine dtor if (pDocShell) pDocShell->GetDocument()->RemoveUnoObject(*this); delete pForwarder; delete pEditEngine; } SvxEditSource* ScAnnotationEditSource::Clone() const { return new ScAnnotationEditSource( pDocShell, aCellPos ); } SvxTextForwarder* ScAnnotationEditSource::GetTextForwarder() { if (!pEditEngine) { // Notizen haben keine Felder if ( pDocShell ) pEditEngine = new ScEditEngineDefaulter( pDocShell->GetDocument()->GetEnginePool(), FALSE ); else pEditEngine = new ScEditEngineDefaulter( EditEngine::CreatePool(), TRUE ); pForwarder = new SvxEditEngineForwarder(*pEditEngine); } if (bDataValid) return pForwarder; if ( pDocShell ) { ScPostIt aNote; ScDocument* pDoc = pDocShell->GetDocument(); pDoc->GetNote( aCellPos.Col(), aCellPos.Row(), aCellPos.Tab(), aNote ); pEditEngine->SetText( aNote.GetText() ); // incl. Umbrueche } bDataValid = TRUE; return pForwarder; } void ScAnnotationEditSource::UpdateData() { if ( pDocShell && pEditEngine ) { String aNewText = pEditEngine->GetText( LINEEND_LF ); // im SetNoteText passiert ConvertLineEnd ScDocFunc aFunc(*pDocShell); aFunc.SetNoteText( aCellPos, aNewText, TRUE ); // bDataValid wird bei SetDocumentModified zurueckgesetzt } } void ScAnnotationEditSource::Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) { if ( rHint.ISA( ScUpdateRefHint ) ) { const ScUpdateRefHint& rRef = (const ScUpdateRefHint&)rHint; //! Ref-Update } else if ( rHint.ISA( SfxSimpleHint ) ) { ULONG nId = ((const SfxSimpleHint&)rHint).GetId(); if ( nId == SFX_HINT_DYING ) { pDocShell = NULL; // ungueltig geworden DELETEZ( pForwarder ); DELETEZ( pEditEngine ); // EditEngine uses document's pool } else if ( nId == SFX_HINT_DATACHANGED ) bDataValid = FALSE; // Text muss neu geholt werden } } //------------------------------------------------------------------------ ScSimpleEditSource::ScSimpleEditSource( SvxTextForwarder* pForw ) : pForwarder( pForw ) { // The same forwarder (and EditEngine) is shared by all children of the same Text object. // Text range and cursor keep a reference to their parent text, so the text object is // always alive and the forwarder is valid as long as there are children. } ScSimpleEditSource::~ScSimpleEditSource() { } SvxEditSource* ScSimpleEditSource::Clone() const { return new ScSimpleEditSource( pForwarder ); } SvxTextForwarder* ScSimpleEditSource::GetTextForwarder() { return pForwarder; } void ScSimpleEditSource::UpdateData() { // nothing } <commit_msg>#78966# call FreezeIdRanges for edit engine pool<commit_after>/************************************************************************* * * $RCSfile: editsrc.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: nn $ $Date: 2001-06-01 19:12:54 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop #ifndef _SFXSMPLHINT_HXX //autogen #include <svtools/smplhint.hxx> #endif #include "scitems.hxx" #include <tools/debug.hxx> #include <svx/editeng.hxx> #include <svx/unofored.hxx> #include <svx/editobj.hxx> #include "textuno.hxx" #include "editsrc.hxx" #include "editutil.hxx" #include "docsh.hxx" #include "docfunc.hxx" #include "cell.hxx" #include "hints.hxx" #include "patattr.hxx" #include "scmod.hxx" #include "unoguard.hxx" //------------------------------------------------------------------------ TYPEINIT1( ScHeaderFooterChangedHint, SfxHint ); ScHeaderFooterChangedHint::ScHeaderFooterChangedHint(USHORT nP) : nPart( nP ) { } ScHeaderFooterChangedHint::~ScHeaderFooterChangedHint() { } //------------------------------------------------------------------------ ScHeaderFooterEditSource::ScHeaderFooterEditSource( ScHeaderFooterContentObj* pContent, USHORT nP ) : pContentObj( pContent ), nPart( nP ), pEditEngine( NULL ), pForwarder( NULL ), bDataValid( FALSE ), bInUpdate( FALSE ) { if (pContentObj) // pContentObj can be 0 if constructed via getReflection { pContentObj->acquire(); // must not go away pContentObj->AddListener( *this ); } } ScHeaderFooterEditSource::~ScHeaderFooterEditSource() { ScUnoGuard aGuard; // needed for EditEngine dtor if (pContentObj) pContentObj->RemoveListener( *this ); delete pForwarder; delete pEditEngine; if (pContentObj) pContentObj->release(); } SvxEditSource* ScHeaderFooterEditSource::Clone() const { return new ScHeaderFooterEditSource( pContentObj, nPart ); } SvxTextForwarder* ScHeaderFooterEditSource::GetTextForwarder() { if (!pEditEngine) { SfxItemPool* pEnginePool = EditEngine::CreatePool(); pEnginePool->FreezeIdRanges(); ScHeaderEditEngine* pHdrEngine = new ScHeaderEditEngine( pEnginePool, TRUE ); pHdrEngine->EnableUndo( FALSE ); pHdrEngine->SetRefMapMode( MAP_TWIP ); // default font must be set, independently of document // -> use global pool from module SfxItemSet aDefaults( pHdrEngine->GetEmptyItemSet() ); const ScPatternAttr& rPattern = (const ScPatternAttr&)SC_MOD()->GetPool().GetDefaultItem(ATTR_PATTERN); rPattern.FillEditItemSet( &aDefaults ); // FillEditItemSet adjusts font height to 1/100th mm, // but for header/footer twips is needed, as in the PatternAttr: aDefaults.Put( rPattern.GetItem(ATTR_FONT_HEIGHT), EE_CHAR_FONTHEIGHT ); aDefaults.Put( rPattern.GetItem(ATTR_CJK_FONT_HEIGHT), EE_CHAR_FONTHEIGHT_CJK ); aDefaults.Put( rPattern.GetItem(ATTR_CTL_FONT_HEIGHT), EE_CHAR_FONTHEIGHT_CTL ); pHdrEngine->SetDefaults( aDefaults ); ScHeaderFieldData aData; ScHeaderFooterTextObj::FillDummyFieldData( aData ); pHdrEngine->SetData( aData ); pEditEngine = pHdrEngine; pForwarder = new SvxEditEngineForwarder(*pEditEngine); } if (bDataValid) return pForwarder; if (pContentObj) { const EditTextObject* pData; if (nPart == SC_HDFT_LEFT) pData = pContentObj->GetLeftEditObject(); else if (nPart == SC_HDFT_CENTER) pData = pContentObj->GetCenterEditObject(); else pData = pContentObj->GetRightEditObject(); if (pData) pEditEngine->SetText(*pData); } bDataValid = TRUE; return pForwarder; } void ScHeaderFooterEditSource::UpdateData() { if ( pContentObj && pEditEngine ) { bInUpdate = TRUE; // don't reset bDataValid during UpdateText pContentObj->UpdateText( nPart, *pEditEngine ); bInUpdate = FALSE; } } void ScHeaderFooterEditSource::Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) { if ( rHint.ISA( ScHeaderFooterChangedHint ) ) { if ( ((const ScHeaderFooterChangedHint&)rHint).GetPart() == nPart ) { if (!bInUpdate) // not for own updates bDataValid = FALSE; // text has to be fetched again } } } //------------------------------------------------------------------------ ScCellEditSource::ScCellEditSource(ScDocShell* pDocSh, const ScAddress& rP) : pDocShell( pDocSh ), aCellPos( rP ), pEditEngine( NULL ), pForwarder( NULL ), bDataValid( FALSE ), bInUpdate( FALSE ) { if (pDocShell) pDocShell->GetDocument()->AddUnoObject(*this); } ScCellEditSource::~ScCellEditSource() { ScUnoGuard aGuard; // needed for EditEngine dtor if (pDocShell) pDocShell->GetDocument()->RemoveUnoObject(*this); delete pForwarder; delete pEditEngine; } SvxEditSource* ScCellEditSource::Clone() const { return new ScCellEditSource( pDocShell, aCellPos ); } SvxTextForwarder* ScCellEditSource::GetTextForwarder() { if (!pEditEngine) { if ( pDocShell ) { const ScDocument* pDoc = pDocShell->GetDocument(); pEditEngine = new ScFieldEditEngine( pDoc->GetEnginePool(), pDoc->GetEditPool(), FALSE ); } else { SfxItemPool* pEnginePool = EditEngine::CreatePool(); pEnginePool->FreezeIdRanges(); pEditEngine = new ScFieldEditEngine( pEnginePool, NULL, TRUE ); } #if SUPD > 600 // currently, GetPortions doesn't work if UpdateMode is FALSE, // this will be fixed (in EditEngine) by src600 // pEditEngine->SetUpdateMode( FALSE ); #endif pEditEngine->EnableUndo( FALSE ); pEditEngine->SetRefMapMode( MAP_100TH_MM ); pForwarder = new SvxEditEngineForwarder(*pEditEngine); } if (bDataValid) return pForwarder; BOOL bEditCell = FALSE; String aText; if (pDocShell) { ScDocument* pDoc = pDocShell->GetDocument(); const ScBaseCell* pCell = pDoc->GetCell( aCellPos ); if ( pCell && pCell->GetCellType() == CELLTYPE_EDIT ) { pEditEngine->SetText( *((const ScEditCell*)pCell)->GetData() ); bEditCell = TRUE; } else pDoc->GetInputString( aCellPos.Col(), aCellPos.Row(), aCellPos.Tab(), aText ); SfxItemSet aDefaults( pEditEngine->GetEmptyItemSet() ); const ScPatternAttr* pPattern = pDoc->GetPattern( aCellPos.Col(), aCellPos.Row(), aCellPos.Tab() ); pPattern->FillEditItemSet( &aDefaults ); pPattern->FillEditParaItems( &aDefaults ); // auch Ausrichtung etc. auslesbar pEditEngine->SetDefaults( aDefaults ); } if (!bEditCell) pEditEngine->SetText( aText ); bDataValid = TRUE; return pForwarder; } void ScCellEditSource::UpdateData() { if ( pDocShell && pEditEngine ) { // beim eigenen Update darf bDataValid nicht zurueckgesetzt werden, // damit z.B. Attribute hinter dem Text nicht verloren gehen // (werden in die Zelle nicht uebernommen) bInUpdate = TRUE; // damit wird bDataValid nicht zurueckgesetzt ScDocFunc aFunc(*pDocShell); aFunc.PutData( aCellPos, *pEditEngine, FALSE, TRUE ); // immer Text bInUpdate = FALSE; } } void ScCellEditSource::Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) { if ( rHint.ISA( ScUpdateRefHint ) ) { const ScUpdateRefHint& rRef = (const ScUpdateRefHint&)rHint; //! Ref-Update } else if ( rHint.ISA( SfxSimpleHint ) ) { ULONG nId = ((const SfxSimpleHint&)rHint).GetId(); if ( nId == SFX_HINT_DYING ) { pDocShell = NULL; // ungueltig geworden DELETEZ( pForwarder ); DELETEZ( pEditEngine ); // EditEngine uses document's pool } else if ( nId == SFX_HINT_DATACHANGED ) { if (!bInUpdate) // eigene Updates zaehlen nicht bDataValid = FALSE; // Text muss neu geholt werden } } } //------------------------------------------------------------------------ ScAnnotationEditSource::ScAnnotationEditSource(ScDocShell* pDocSh, const ScAddress& rP) : pDocShell( pDocSh ), aCellPos( rP ), pEditEngine( NULL ), pForwarder( NULL ), bDataValid( FALSE ) { if (pDocShell) pDocShell->GetDocument()->AddUnoObject(*this); } ScAnnotationEditSource::~ScAnnotationEditSource() { ScUnoGuard aGuard; // needed for EditEngine dtor if (pDocShell) pDocShell->GetDocument()->RemoveUnoObject(*this); delete pForwarder; delete pEditEngine; } SvxEditSource* ScAnnotationEditSource::Clone() const { return new ScAnnotationEditSource( pDocShell, aCellPos ); } SvxTextForwarder* ScAnnotationEditSource::GetTextForwarder() { if (!pEditEngine) { // Notizen haben keine Felder if ( pDocShell ) pEditEngine = new ScEditEngineDefaulter( pDocShell->GetDocument()->GetEnginePool(), FALSE ); else { SfxItemPool* pEnginePool = EditEngine::CreatePool(); pEnginePool->FreezeIdRanges(); pEditEngine = new ScEditEngineDefaulter( pEnginePool, TRUE ); } pForwarder = new SvxEditEngineForwarder(*pEditEngine); } if (bDataValid) return pForwarder; if ( pDocShell ) { ScPostIt aNote; ScDocument* pDoc = pDocShell->GetDocument(); pDoc->GetNote( aCellPos.Col(), aCellPos.Row(), aCellPos.Tab(), aNote ); pEditEngine->SetText( aNote.GetText() ); // incl. Umbrueche } bDataValid = TRUE; return pForwarder; } void ScAnnotationEditSource::UpdateData() { if ( pDocShell && pEditEngine ) { String aNewText = pEditEngine->GetText( LINEEND_LF ); // im SetNoteText passiert ConvertLineEnd ScDocFunc aFunc(*pDocShell); aFunc.SetNoteText( aCellPos, aNewText, TRUE ); // bDataValid wird bei SetDocumentModified zurueckgesetzt } } void ScAnnotationEditSource::Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) { if ( rHint.ISA( ScUpdateRefHint ) ) { const ScUpdateRefHint& rRef = (const ScUpdateRefHint&)rHint; //! Ref-Update } else if ( rHint.ISA( SfxSimpleHint ) ) { ULONG nId = ((const SfxSimpleHint&)rHint).GetId(); if ( nId == SFX_HINT_DYING ) { pDocShell = NULL; // ungueltig geworden DELETEZ( pForwarder ); DELETEZ( pEditEngine ); // EditEngine uses document's pool } else if ( nId == SFX_HINT_DATACHANGED ) bDataValid = FALSE; // Text muss neu geholt werden } } //------------------------------------------------------------------------ ScSimpleEditSource::ScSimpleEditSource( SvxTextForwarder* pForw ) : pForwarder( pForw ) { // The same forwarder (and EditEngine) is shared by all children of the same Text object. // Text range and cursor keep a reference to their parent text, so the text object is // always alive and the forwarder is valid as long as there are children. } ScSimpleEditSource::~ScSimpleEditSource() { } SvxEditSource* ScSimpleEditSource::Clone() const { return new ScSimpleEditSource( pForwarder ); } SvxTextForwarder* ScSimpleEditSource::GetTextForwarder() { return pForwarder; } void ScSimpleEditSource::UpdateData() { // nothing } <|endoftext|>
<commit_before>/* * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "mesh_resource_marker.h" #include "marker_selection_handler.h" #include "rviz/default_plugin/marker_display.h" #include "rviz/selection/selection_manager.h" #include "rviz/visualization_manager.h" #include "rviz/mesh_loader.h" #include "marker_display.h" #include <OGRE/OgreSceneNode.h> #include <OGRE/OgreSceneManager.h> #include <OGRE/OgreEntity.h> #include <OGRE/OgreMaterialManager.h> #include <OGRE/OgreTextureManager.h> namespace rviz { MeshResourceMarker::MeshResourceMarker(MarkerDisplay* owner, VisualizationManager* manager, Ogre::SceneNode* parent_node) : MarkerBase(owner, manager, parent_node) , entity_(0) { if (parent_node) { scene_node_ = parent_node->createChildSceneNode(); } else { scene_node_ = vis_manager_->getSceneManager()->getRootSceneNode()->createChildSceneNode(); } } MeshResourceMarker::~MeshResourceMarker() { vis_manager_->getSceneManager()->destroySceneNode(scene_node_->getName()); vis_manager_->getSceneManager()->destroyEntity( entity_ ); for (size_t i = 0; i < material_->getNumTechniques(); ++i) { Ogre::Technique* t = material_->getTechnique(i); // hack hack hack, really need to do a shader-based way of picking, rather than // creating a texture for each object if (t->getSchemeName() == "Pick") { Ogre::TextureManager::getSingleton().remove(t->getPass(0)->getTextureUnitState(0)->getTextureName()); } } material_->unload(); Ogre::MaterialManager::getSingleton().remove(material_->getName()); } void MeshResourceMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message) { ROS_ASSERT(new_message->type == visualization_msgs::Marker::MESH_RESOURCE); scene_node_->setVisible(false); if (!entity_) { if (new_message->mesh_resource.empty()) { return; } if (loadMeshFromResource(new_message->mesh_resource).isNull()) { std::stringstream ss; ss << "Mesh resource marker [" << getStringID() << "] could not load [" << new_message->mesh_resource << "]"; owner_->setMarkerStatus(getID(), status_levels::Error, ss.str()); ROS_DEBUG("%s", ss.str().c_str()); return; } static uint32_t count = 0; std::stringstream ss; ss << "Mesh Resource Marker" << count++; entity_ = vis_manager_->getSceneManager()->createEntity(ss.str(), new_message->mesh_resource); scene_node_->attachObject(entity_); ss << "Material"; material_name_ = ss.str(); material_ = Ogre::MaterialManager::getSingleton().create( material_name_, ROS_PACKAGE_NAME ); material_->setReceiveShadows(false); material_->getTechnique(0)->setLightingEnabled(true); material_->getTechnique(0)->setAmbient( 0.5, 0.5, 0.5 ); entity_->setMaterialName(material_name_); coll_ = vis_manager_->getSelectionManager()->createCollisionForEntity(entity_, SelectionHandlerPtr(new MarkerSelectionHandler(this, MarkerID(new_message->ns, new_message->id))), coll_); } Ogre::Vector3 pos, scale; Ogre::Quaternion orient; transform(new_message, pos, orient, scale, false); scene_node_->setVisible(true); scene_node_->setPosition(pos); scene_node_->setOrientation(orient); scene_node_->setScale(scale); float r = new_message->color.r; float g = new_message->color.g; float b = new_message->color.b; float a = new_message->color.a; material_->getTechnique(0)->setAmbient( r*0.5, g*0.5, b*0.5 ); material_->getTechnique(0)->setDiffuse( r, g, b, a ); if ( a < 0.9998 ) { material_->getTechnique(0)->setSceneBlending( Ogre::SBT_TRANSPARENT_ALPHA ); material_->getTechnique(0)->setDepthWriteEnabled( false ); } else { material_->getTechnique(0)->setSceneBlending( Ogre::SBT_REPLACE ); material_->getTechnique(0)->setDepthWriteEnabled( true ); } } } <commit_msg>fix MESH_RESOURCE marker to not crash on destruction when it had never received a valid resource (#4180)<commit_after>/* * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "mesh_resource_marker.h" #include "marker_selection_handler.h" #include "rviz/default_plugin/marker_display.h" #include "rviz/selection/selection_manager.h" #include "rviz/visualization_manager.h" #include "rviz/mesh_loader.h" #include "marker_display.h" #include <OGRE/OgreSceneNode.h> #include <OGRE/OgreSceneManager.h> #include <OGRE/OgreEntity.h> #include <OGRE/OgreMaterialManager.h> #include <OGRE/OgreTextureManager.h> namespace rviz { MeshResourceMarker::MeshResourceMarker(MarkerDisplay* owner, VisualizationManager* manager, Ogre::SceneNode* parent_node) : MarkerBase(owner, manager, parent_node) , entity_(0) { if (parent_node) { scene_node_ = parent_node->createChildSceneNode(); } else { scene_node_ = vis_manager_->getSceneManager()->getRootSceneNode()->createChildSceneNode(); } } MeshResourceMarker::~MeshResourceMarker() { vis_manager_->getSceneManager()->destroySceneNode(scene_node_->getName()); if (entity_) { vis_manager_->getSceneManager()->destroyEntity( entity_ ); } if (!material_.isNull()) { for (size_t i = 0; i < material_->getNumTechniques(); ++i) { Ogre::Technique* t = material_->getTechnique(i); // hack hack hack, really need to do a shader-based way of picking, rather than // creating a texture for each object if (t->getSchemeName() == "Pick") { Ogre::TextureManager::getSingleton().remove(t->getPass(0)->getTextureUnitState(0)->getTextureName()); } } material_->unload(); Ogre::MaterialManager::getSingleton().remove(material_->getName()); } } void MeshResourceMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message) { ROS_ASSERT(new_message->type == visualization_msgs::Marker::MESH_RESOURCE); scene_node_->setVisible(false); if (!entity_) { if (new_message->mesh_resource.empty()) { return; } if (loadMeshFromResource(new_message->mesh_resource).isNull()) { std::stringstream ss; ss << "Mesh resource marker [" << getStringID() << "] could not load [" << new_message->mesh_resource << "]"; owner_->setMarkerStatus(getID(), status_levels::Error, ss.str()); ROS_DEBUG("%s", ss.str().c_str()); return; } static uint32_t count = 0; std::stringstream ss; ss << "Mesh Resource Marker" << count++; entity_ = vis_manager_->getSceneManager()->createEntity(ss.str(), new_message->mesh_resource); scene_node_->attachObject(entity_); ss << "Material"; material_name_ = ss.str(); material_ = Ogre::MaterialManager::getSingleton().create( material_name_, ROS_PACKAGE_NAME ); material_->setReceiveShadows(false); material_->getTechnique(0)->setLightingEnabled(true); material_->getTechnique(0)->setAmbient( 0.5, 0.5, 0.5 ); entity_->setMaterialName(material_name_); coll_ = vis_manager_->getSelectionManager()->createCollisionForEntity(entity_, SelectionHandlerPtr(new MarkerSelectionHandler(this, MarkerID(new_message->ns, new_message->id))), coll_); } Ogre::Vector3 pos, scale; Ogre::Quaternion orient; transform(new_message, pos, orient, scale, false); scene_node_->setVisible(true); scene_node_->setPosition(pos); scene_node_->setOrientation(orient); scene_node_->setScale(scale); float r = new_message->color.r; float g = new_message->color.g; float b = new_message->color.b; float a = new_message->color.a; material_->getTechnique(0)->setAmbient( r*0.5, g*0.5, b*0.5 ); material_->getTechnique(0)->setDiffuse( r, g, b, a ); if ( a < 0.9998 ) { material_->getTechnique(0)->setSceneBlending( Ogre::SBT_TRANSPARENT_ALPHA ); material_->getTechnique(0)->setDepthWriteEnabled( false ); } else { material_->getTechnique(0)->setSceneBlending( Ogre::SBT_REPLACE ); material_->getTechnique(0)->setDepthWriteEnabled( true ); } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "triangle_list_marker.h" #include "marker_selection_handler.h" #include "rviz/default_plugin/marker_display.h" #include "rviz/selection/selection_manager.h" #include "rviz/uniform_string_stream.h" #include "rviz/display_context.h" #include "rviz/mesh_loader.h" #include "marker_display.h" #include <OGRE/OgreSceneNode.h> #include <OGRE/OgreSceneManager.h> #include <OGRE/OgreManualObject.h> #include <OGRE/OgreMaterialManager.h> #include <OGRE/OgreTextureManager.h> #include <OGRE/OgreTechnique.h> namespace rviz { TriangleListMarker::TriangleListMarker(MarkerDisplay* owner, DisplayContext* context, Ogre::SceneNode* parent_node) : MarkerBase(owner, context, parent_node) , manual_object_(0) { } TriangleListMarker::~TriangleListMarker() { context_->getSceneManager()->destroyManualObject(manual_object_); material_->unload(); Ogre::MaterialManager::getSingleton().remove(material_->getName()); } void TriangleListMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message) { ROS_ASSERT(new_message->type == visualization_msgs::Marker::TRIANGLE_LIST); size_t num_points = new_message->points.size(); if( (num_points % 3) != 0 || num_points == 0 ) { std::stringstream ss; if( num_points == 0 ) { ss << "TriMesh marker [" << getStringID() << "] has no points."; } else { ss << "TriMesh marker [" << getStringID() << "] has a point count which is not divisible by 3 [" << num_points <<"]"; } if ( owner_ ) { owner_->setMarkerStatus(getID(), StatusProperty::Error, ss.str()); } ROS_DEBUG("%s", ss.str().c_str()); scene_node_->setVisible( false ); return; } else { scene_node_->setVisible( true ); } if (!manual_object_) { static uint32_t count = 0; UniformStringStream ss; ss << "Triangle List Marker" << count++; manual_object_ = context_->getSceneManager()->createManualObject(ss.str()); scene_node_->attachObject(manual_object_); ss << "Material"; material_name_ = ss.str(); material_ = Ogre::MaterialManager::getSingleton().create( material_name_, ROS_PACKAGE_NAME ); material_->setReceiveShadows(false); material_->getTechnique(0)->setLightingEnabled(true); material_->setCullingMode(Ogre::CULL_NONE); handler_.reset( new MarkerSelectionHandler( this, MarkerID( new_message->ns, new_message->id ), context_ )); } Ogre::Vector3 pos, scale; Ogre::Quaternion orient; if (!transform(new_message, pos, orient, scale)) { ROS_DEBUG("Unable to transform marker message"); scene_node_->setVisible( false ); return; } if ( owner_ && (new_message->scale.x * new_message->scale.y * new_message->scale.z == 0.0f) ) { owner_->setMarkerStatus(getID(), StatusProperty::Warn, "Scale of 0 in one of x/y/z"); } setPosition(pos); setOrientation(orient); scene_node_->setScale(scale); // If we have the same number of tris as previously, just update the object if (old_message && num_points == old_message->points.size()) { manual_object_->beginUpdate(0); } else // Otherwise clear it and begin anew { manual_object_->clear(); manual_object_->estimateVertexCount(num_points); manual_object_->begin(material_name_, Ogre::RenderOperation::OT_TRIANGLE_LIST); } bool has_vertex_colors = new_message->colors.size() == num_points; bool any_vertex_has_alpha = false; if (has_vertex_colors) { for (size_t i = 0; i < num_points; ++i) { manual_object_->position(new_message->points[i].x, new_message->points[i].y, new_message->points[i].z); any_vertex_has_alpha = any_vertex_has_alpha || (new_message->colors[i].a < 0.9998); manual_object_->colour(new_message->colors[i].r, new_message->colors[i].g, new_message->colors[i].b, new_message->color.a * new_message->colors[i].a); } } else { for (size_t i = 0; i < num_points; ++i) { manual_object_->position(new_message->points[i].x, new_message->points[i].y, new_message->points[i].z); } } manual_object_->end(); if (has_vertex_colors) { material_->getTechnique(0)->setLightingEnabled(false); } else { material_->getTechnique(0)->setLightingEnabled(true); float r,g,b,a; r = new_message->color.r; g = new_message->color.g; b = new_message->color.b; a = new_message->color.a; material_->getTechnique(0)->setAmbient( r,g,b ); material_->getTechnique(0)->setDiffuse( 0,0,0,a ); } if( (!has_vertex_colors && new_message->color.a < 0.9998) || (has_vertex_colors && any_vertex_has_alpha)) { material_->getTechnique(0)->setSceneBlending( Ogre::SBT_TRANSPARENT_ALPHA ); material_->getTechnique(0)->setDepthWriteEnabled( false ); } else { material_->getTechnique(0)->setSceneBlending( Ogre::SBT_REPLACE ); material_->getTechnique(0)->setDepthWriteEnabled( true ); } handler_->addTrackedObject( manual_object_ ); } S_MaterialPtr TriangleListMarker::getMaterials() { S_MaterialPtr materials; materials.insert( material_ ); return materials; } } <commit_msg>trangle list marker: added support for per-face color in addition to per-vertex color<commit_after>/* * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "triangle_list_marker.h" #include "marker_selection_handler.h" #include "rviz/default_plugin/marker_display.h" #include "rviz/selection/selection_manager.h" #include "rviz/uniform_string_stream.h" #include "rviz/display_context.h" #include "rviz/mesh_loader.h" #include "marker_display.h" #include <OGRE/OgreSceneNode.h> #include <OGRE/OgreSceneManager.h> #include <OGRE/OgreManualObject.h> #include <OGRE/OgreMaterialManager.h> #include <OGRE/OgreTextureManager.h> #include <OGRE/OgreTechnique.h> namespace rviz { TriangleListMarker::TriangleListMarker(MarkerDisplay* owner, DisplayContext* context, Ogre::SceneNode* parent_node) : MarkerBase(owner, context, parent_node) , manual_object_(0) { } TriangleListMarker::~TriangleListMarker() { context_->getSceneManager()->destroyManualObject(manual_object_); material_->unload(); Ogre::MaterialManager::getSingleton().remove(material_->getName()); } void TriangleListMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message) { ROS_ASSERT(new_message->type == visualization_msgs::Marker::TRIANGLE_LIST); size_t num_points = new_message->points.size(); if( (num_points % 3) != 0 || num_points == 0 ) { std::stringstream ss; if( num_points == 0 ) { ss << "TriMesh marker [" << getStringID() << "] has no points."; } else { ss << "TriMesh marker [" << getStringID() << "] has a point count which is not divisible by 3 [" << num_points <<"]"; } if ( owner_ ) { owner_->setMarkerStatus(getID(), StatusProperty::Error, ss.str()); } ROS_DEBUG("%s", ss.str().c_str()); scene_node_->setVisible( false ); return; } else { scene_node_->setVisible( true ); } if (!manual_object_) { static uint32_t count = 0; UniformStringStream ss; ss << "Triangle List Marker" << count++; manual_object_ = context_->getSceneManager()->createManualObject(ss.str()); scene_node_->attachObject(manual_object_); ss << "Material"; material_name_ = ss.str(); material_ = Ogre::MaterialManager::getSingleton().create( material_name_, ROS_PACKAGE_NAME ); material_->setReceiveShadows(false); material_->getTechnique(0)->setLightingEnabled(true); material_->setCullingMode(Ogre::CULL_NONE); handler_.reset( new MarkerSelectionHandler( this, MarkerID( new_message->ns, new_message->id ), context_ )); } Ogre::Vector3 pos, scale; Ogre::Quaternion orient; if (!transform(new_message, pos, orient, scale)) { ROS_DEBUG("Unable to transform marker message"); scene_node_->setVisible( false ); return; } if ( owner_ && (new_message->scale.x * new_message->scale.y * new_message->scale.z == 0.0f) ) { owner_->setMarkerStatus(getID(), StatusProperty::Warn, "Scale of 0 in one of x/y/z"); } setPosition(pos); setOrientation(orient); scene_node_->setScale(scale); // If we have the same number of tris as previously, just update the object if (old_message && num_points == old_message->points.size()) { manual_object_->beginUpdate(0); } else // Otherwise clear it and begin anew { manual_object_->clear(); manual_object_->estimateVertexCount(num_points); manual_object_->begin(material_name_, Ogre::RenderOperation::OT_TRIANGLE_LIST); } bool has_vertex_colors = new_message->colors.size() == num_points; bool has_face_colors = new_message->colors.size() == num_points / 3; bool any_vertex_has_alpha = false; if (has_vertex_colors) { for (size_t i = 0; i < num_points; ++i) { manual_object_->position(new_message->points[i].x, new_message->points[i].y, new_message->points[i].z); any_vertex_has_alpha = any_vertex_has_alpha || (new_message->colors[i].a < 0.9998); manual_object_->colour(new_message->colors[i].r, new_message->colors[i].g, new_message->colors[i].b, new_message->color.a * new_message->colors[i].a); } } else if (has_face_colors) { for (size_t i = 0; i < num_points; ++i) { manual_object_->position(new_message->points[i].x, new_message->points[i].y, new_message->points[i].z); any_vertex_has_alpha = any_vertex_has_alpha || (new_message->colors[i].a < 0.9998); manual_object_->colour(new_message->colors[i/3].r, new_message->colors[i/3].g, new_message->colors[i/3].b, new_message->color.a * new_message->colors[i/3].a); } } else { for (size_t i = 0; i < num_points; ++i) { manual_object_->position(new_message->points[i].x, new_message->points[i].y, new_message->points[i].z); } } manual_object_->end(); if (has_vertex_colors || has_face_colors) { material_->getTechnique(0)->setLightingEnabled(false); } else { material_->getTechnique(0)->setLightingEnabled(true); float r,g,b,a; r = new_message->color.r; g = new_message->color.g; b = new_message->color.b; a = new_message->color.a; material_->getTechnique(0)->setAmbient( r,g,b ); material_->getTechnique(0)->setDiffuse( 0,0,0,a ); } if( (!has_vertex_colors && new_message->color.a < 0.9998) || (has_vertex_colors && any_vertex_has_alpha)) { material_->getTechnique(0)->setSceneBlending( Ogre::SBT_TRANSPARENT_ALPHA ); material_->getTechnique(0)->setDepthWriteEnabled( false ); } else { material_->getTechnique(0)->setSceneBlending( Ogre::SBT_REPLACE ); material_->getTechnique(0)->setDepthWriteEnabled( true ); } handler_->addTrackedObject( manual_object_ ); } S_MaterialPtr TriangleListMarker::getMaterials() { S_MaterialPtr materials; materials.insert( material_ ); return materials; } } <|endoftext|>
<commit_before>// $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "boundary_info.h" #include "elem.h" #include "libmesh_logging.h" #include "metis_partitioner.h" #include "serial_mesh.h" namespace libMesh { // ------------------------------------------------------------ // SerialMesh class member functions SerialMesh::SerialMesh (unsigned int d) : UnstructuredMesh (d) { _partitioner = AutoPtr<Partitioner>(new MetisPartitioner()); } SerialMesh::~SerialMesh () { this->clear(); // Free nodes and elements } // This might be specialized later, but right now it's just here to // make sure the compiler doesn't give us a default (non-deep) copy // constructor instead. SerialMesh::SerialMesh (const SerialMesh &other_mesh) : UnstructuredMesh (other_mesh) { this->copy_nodes_and_elements(other_mesh); *this->boundary_info = *other_mesh.boundary_info; } SerialMesh::SerialMesh (const UnstructuredMesh &other_mesh) : UnstructuredMesh (other_mesh) { this->copy_nodes_and_elements(other_mesh); *this->boundary_info = *other_mesh.boundary_info; } const Point& SerialMesh::point (const unsigned int i) const { libmesh_assert (i < this->n_nodes()); libmesh_assert (_nodes[i] != NULL); libmesh_assert (_nodes[i]->id() == i); // This will change soon return (*_nodes[i]); } const Node& SerialMesh::node (const unsigned int i) const { libmesh_assert (i < this->n_nodes()); libmesh_assert (_nodes[i] != NULL); libmesh_assert (_nodes[i]->id() == i); // This will change soon return (*_nodes[i]); } Node& SerialMesh::node (const unsigned int i) { if (i >= this->n_nodes()) { libMesh::out << " i=" << i << ", n_nodes()=" << this->n_nodes() << std::endl; libmesh_error(); } libmesh_assert (i < this->n_nodes()); libmesh_assert (_nodes[i] != NULL); libmesh_assert (_nodes[i]->id() == i); // This will change soon return (*_nodes[i]); } const Node* SerialMesh::node_ptr (const unsigned int i) const { libmesh_assert (i < this->n_nodes()); libmesh_assert (_nodes[i] != NULL); libmesh_assert (_nodes[i]->id() == i); // This will change soon return _nodes[i]; } Node* & SerialMesh::node_ptr (const unsigned int i) { libmesh_assert (i < this->n_nodes()); libmesh_assert (_nodes[i] != NULL); libmesh_assert (_nodes[i]->id() == i); // This will change soon return _nodes[i]; } Elem* SerialMesh::elem (const unsigned int i) const { libmesh_assert (i < this->n_elem()); libmesh_assert (_elements[i] != NULL); libmesh_assert (_elements[i]->id() == i); // This will change soon return _elements[i]; } Elem* SerialMesh::add_elem (Elem* e) { libmesh_assert(e); // We only append elements with SerialMesh libmesh_assert (!e->valid_id() || e->id() == _elements.size()); e->set_id (_elements.size()); _elements.push_back(e); return e; } Elem* SerialMesh::insert_elem (Elem* e) { unsigned int eid = e->id(); libmesh_assert(eid < _elements.size()); Elem *oldelem = _elements[eid]; if (oldelem) { libmesh_assert(oldelem->id() == eid); this->delete_elem(oldelem); } _elements[e->id()] = e; return e; } void SerialMesh::delete_elem(Elem* e) { libmesh_assert (e != NULL); // Initialize an iterator to eventually point to the element we want to delete std::vector<Elem*>::iterator pos = _elements.end(); // In many cases, e->id() gives us a clue as to where e // is located in the _elements vector. Try that first // before trying the O(n_elem) search. libmesh_assert (e->id() < _elements.size()); if (_elements[e->id()] == e) { // We found it! pos = _elements.begin(); std::advance(pos, e->id()); } else { // This search is O(n_elem) pos = std::find (_elements.begin(), _elements.end(), e); } // Huh? Element not in the vector? libmesh_assert (pos != _elements.end()); // Remove the element from the BoundaryInfo object this->boundary_info->remove(e); // delete the element delete e; // explicitly NULL the pointer *pos = NULL; } void SerialMesh::renumber_elem(const unsigned int old_id, const unsigned int new_id) { // This doesn't get used in serial yet Elem *elem = _elements[old_id]; libmesh_assert (elem); elem->set_id(new_id); libmesh_assert (!_elements[new_id]); _elements[new_id] = elem; _elements[old_id] = NULL; } Node* SerialMesh::add_point (const Point& p, const unsigned int id, const unsigned int proc_id) { // // We only append points with SerialMesh // libmesh_assert(id == DofObject::invalid_id || id == _nodes.size()); // Node *n = Node::build(p, _nodes.size()).release(); // n->processor_id() = proc_id; // _nodes.push_back (n); Node *n = NULL; // If the user requests a valid id, either // provide the existing node or resize the container // to fit the new node. if (id != DofObject::invalid_id) if (id < _nodes.size()) n = _nodes[id]; else _nodes.resize(id+1); else _nodes.push_back (static_cast<Node*>(NULL)); // if the node already exists, then assign new (x,y,z) values if (n) *n = p; // otherwise build a new node, put it in the right spot, and return // a valid pointer. else { n = Node::build(p, (id == DofObject::invalid_id) ? _nodes.size()-1 : id).release(); n->processor_id() = proc_id; if (id == DofObject::invalid_id) _nodes.back() = n; else _nodes[id] = n; } // better not pass back a NULL pointer. libmesh_assert (n); return n; } Node* SerialMesh::add_node (Node* n) { libmesh_assert(n); // We only append points with SerialMesh libmesh_assert(!n->valid_id() || n->id() == _nodes.size()); n->set_id (_nodes.size()); _nodes.push_back(n); return n; } void SerialMesh::delete_node(Node* n) { libmesh_assert (n != NULL); libmesh_assert (n->id() < _nodes.size()); // Initialize an iterator to eventually point to the element we want // to delete std::vector<Node*>::iterator pos; // In many cases, e->id() gives us a clue as to where e // is located in the _elements vector. Try that first // before trying the O(n_elem) search. if (_nodes[n->id()] == n) { pos = _nodes.begin(); std::advance(pos, n->id()); } else { pos = std::find (_nodes.begin(), _nodes.end(), n); } // Huh? Node not in the vector? libmesh_assert (pos != _nodes.end()); // Delete the node from the BoundaryInfo object this->boundary_info->remove(n); // delete the node delete n; // explicitly NULL the pointer *pos = NULL; } void SerialMesh::renumber_node(const unsigned int old_id, const unsigned int new_id) { // This doesn't get used in serial yet Node *node = _nodes[old_id]; libmesh_assert (node); node->set_id(new_id); libmesh_assert (!_nodes[new_id]); _nodes[new_id] = node; _nodes[old_id] = NULL; } void SerialMesh::clear () { // Call parent clear function MeshBase::clear(); // Clear our elements and nodes { std::vector<Elem*>::iterator it = _elements.begin(); const std::vector<Elem*>::iterator end = _elements.end(); // There is no need to remove the elements from // the BoundaryInfo data structure since we // already cleared it. for (; it != end; ++it) delete *it; _elements.clear(); } // clear the nodes data structure { std::vector<Node*>::iterator it = _nodes.begin(); const std::vector<Node*>::iterator end = _nodes.end(); // There is no need to remove the nodes from // the BoundaryInfo data structure since we // already cleared it. for (; it != end; ++it) delete *it; _nodes.clear(); } } void SerialMesh::renumber_nodes_and_elements () { START_LOG("renumber_nodes_and_elem()", "Mesh"); // node and element id counters unsigned int next_free_elem = 0; unsigned int next_free_node = 0; // Loop over the elements. Note that there may // be NULLs in the _elements vector from the coarsening // process. Pack the elements in to a contiguous array // and then trim any excess. { std::vector<Elem*>::iterator in = _elements.begin(); std::vector<Elem*>::iterator out = _elements.begin(); const std::vector<Elem*>::iterator end = _elements.end(); for (; in != end; ++in) if (*in != NULL) { Elem* elem = *in; *out = *in; ++out; // Increment the element counter elem->set_id (next_free_elem++); // Loop over this element's nodes. Number them, // if they have not been numbered already. Also, // position them in the _nodes vector so that they // are packed contiguously from the beginning. for (unsigned int n=0; n<elem->n_nodes(); n++) if (elem->node(n) == next_free_node) // don't need to process next_free_node++; // [(src == dst) below] else if (elem->node(n) > next_free_node) // need to process { // The source and destination indices // for this node const unsigned int src_idx = elem->node(n); const unsigned int dst_idx = next_free_node++; // ensure we want to swap valid nodes libmesh_assert (_nodes[src_idx] != NULL); libmesh_assert (_nodes[dst_idx] != NULL); // Swap the source and destination nodes std::swap(_nodes[src_idx], _nodes[dst_idx] ); // Set proper indices _nodes[src_idx]->set_id (src_idx); _nodes[dst_idx]->set_id (dst_idx); } } // Erase any additional storage. These elements have been // copied into NULL voids by the procedure above, and are // thus repeated and unnecessary. _elements.erase (out, end); } // Any nodes in the vector >= _nodes[next_free_node] // are not connected to any elements and may be deleted // if desired. // (This code block will erase the unused nodes) // Now, delete the unused nodes { std::vector<Node*>::iterator nd = _nodes.begin(); const std::vector<Node*>::iterator end = _nodes.end(); std::advance (nd, next_free_node); for (std::vector<Node*>::iterator it=nd; it != end; ++it) { libmesh_assert (*it != NULL); // remove any boundary information associated with // this node this->boundary_info->remove (*it); // delete the node delete *it; *it = NULL; } _nodes.erase (nd, end); } libmesh_assert (next_free_elem == _elements.size()); libmesh_assert (next_free_node == _nodes.size()); STOP_LOG("renumber_nodes_and_elem()", "Mesh"); } void SerialMesh::fix_broken_node_and_element_numbering () { // Nodes first for (unsigned int n=0; n<this->_nodes.size(); n++) if (this->_nodes[n] != NULL) this->_nodes[n]->set_id() = n; // Elements next for (unsigned int e=0; e<this->_elements.size(); e++) if (this->_elements[e] != NULL) this->_elements[e]->set_id() = e; } unsigned int SerialMesh::n_active_elem () const { return static_cast<unsigned int>(std::distance (this->active_elements_begin(), this->active_elements_end())); } } // namespace libMesh <commit_msg>Fix for SerialMesh::delete_node()<commit_after>// $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "boundary_info.h" #include "elem.h" #include "libmesh_logging.h" #include "metis_partitioner.h" #include "serial_mesh.h" namespace libMesh { // ------------------------------------------------------------ // SerialMesh class member functions SerialMesh::SerialMesh (unsigned int d) : UnstructuredMesh (d) { _partitioner = AutoPtr<Partitioner>(new MetisPartitioner()); } SerialMesh::~SerialMesh () { this->clear(); // Free nodes and elements } // This might be specialized later, but right now it's just here to // make sure the compiler doesn't give us a default (non-deep) copy // constructor instead. SerialMesh::SerialMesh (const SerialMesh &other_mesh) : UnstructuredMesh (other_mesh) { this->copy_nodes_and_elements(other_mesh); *this->boundary_info = *other_mesh.boundary_info; } SerialMesh::SerialMesh (const UnstructuredMesh &other_mesh) : UnstructuredMesh (other_mesh) { this->copy_nodes_and_elements(other_mesh); *this->boundary_info = *other_mesh.boundary_info; } const Point& SerialMesh::point (const unsigned int i) const { libmesh_assert (i < this->n_nodes()); libmesh_assert (_nodes[i] != NULL); libmesh_assert (_nodes[i]->id() == i); // This will change soon return (*_nodes[i]); } const Node& SerialMesh::node (const unsigned int i) const { libmesh_assert (i < this->n_nodes()); libmesh_assert (_nodes[i] != NULL); libmesh_assert (_nodes[i]->id() == i); // This will change soon return (*_nodes[i]); } Node& SerialMesh::node (const unsigned int i) { if (i >= this->n_nodes()) { libMesh::out << " i=" << i << ", n_nodes()=" << this->n_nodes() << std::endl; libmesh_error(); } libmesh_assert (i < this->n_nodes()); libmesh_assert (_nodes[i] != NULL); libmesh_assert (_nodes[i]->id() == i); // This will change soon return (*_nodes[i]); } const Node* SerialMesh::node_ptr (const unsigned int i) const { libmesh_assert (i < this->n_nodes()); libmesh_assert (_nodes[i] != NULL); libmesh_assert (_nodes[i]->id() == i); // This will change soon return _nodes[i]; } Node* & SerialMesh::node_ptr (const unsigned int i) { libmesh_assert (i < this->n_nodes()); libmesh_assert (_nodes[i] != NULL); libmesh_assert (_nodes[i]->id() == i); // This will change soon return _nodes[i]; } Elem* SerialMesh::elem (const unsigned int i) const { libmesh_assert (i < this->n_elem()); libmesh_assert (_elements[i] != NULL); libmesh_assert (_elements[i]->id() == i); // This will change soon return _elements[i]; } Elem* SerialMesh::add_elem (Elem* e) { libmesh_assert(e); // We only append elements with SerialMesh libmesh_assert (!e->valid_id() || e->id() == _elements.size()); e->set_id (_elements.size()); _elements.push_back(e); return e; } Elem* SerialMesh::insert_elem (Elem* e) { unsigned int eid = e->id(); libmesh_assert(eid < _elements.size()); Elem *oldelem = _elements[eid]; if (oldelem) { libmesh_assert(oldelem->id() == eid); this->delete_elem(oldelem); } _elements[e->id()] = e; return e; } void SerialMesh::delete_elem(Elem* e) { libmesh_assert (e != NULL); // Initialize an iterator to eventually point to the element we want to delete std::vector<Elem*>::iterator pos = _elements.end(); // In many cases, e->id() gives us a clue as to where e // is located in the _elements vector. Try that first // before trying the O(n_elem) search. libmesh_assert (e->id() < _elements.size()); if (_elements[e->id()] == e) { // We found it! pos = _elements.begin(); std::advance(pos, e->id()); } else { // This search is O(n_elem) pos = std::find (_elements.begin(), _elements.end(), e); } // Huh? Element not in the vector? libmesh_assert (pos != _elements.end()); // Remove the element from the BoundaryInfo object this->boundary_info->remove(e); // delete the element delete e; // explicitly NULL the pointer *pos = NULL; } void SerialMesh::renumber_elem(const unsigned int old_id, const unsigned int new_id) { // This doesn't get used in serial yet Elem *elem = _elements[old_id]; libmesh_assert (elem); elem->set_id(new_id); libmesh_assert (!_elements[new_id]); _elements[new_id] = elem; _elements[old_id] = NULL; } Node* SerialMesh::add_point (const Point& p, const unsigned int id, const unsigned int proc_id) { // // We only append points with SerialMesh // libmesh_assert(id == DofObject::invalid_id || id == _nodes.size()); // Node *n = Node::build(p, _nodes.size()).release(); // n->processor_id() = proc_id; // _nodes.push_back (n); Node *n = NULL; // If the user requests a valid id, either // provide the existing node or resize the container // to fit the new node. if (id != DofObject::invalid_id) if (id < _nodes.size()) n = _nodes[id]; else _nodes.resize(id+1); else _nodes.push_back (static_cast<Node*>(NULL)); // if the node already exists, then assign new (x,y,z) values if (n) *n = p; // otherwise build a new node, put it in the right spot, and return // a valid pointer. else { n = Node::build(p, (id == DofObject::invalid_id) ? _nodes.size()-1 : id).release(); n->processor_id() = proc_id; if (id == DofObject::invalid_id) _nodes.back() = n; else _nodes[id] = n; } // better not pass back a NULL pointer. libmesh_assert (n); return n; } Node* SerialMesh::add_node (Node* n) { libmesh_assert(n); // We only append points with SerialMesh libmesh_assert(!n->valid_id() || n->id() == _nodes.size()); n->set_id (_nodes.size()); _nodes.push_back(n); return n; } void SerialMesh::delete_node(Node* n) { libmesh_assert (n != NULL); libmesh_assert (n->id() < _nodes.size()); // Initialize an iterator to eventually point to the element we want // to delete std::vector<Node*>::iterator pos; // In many cases, e->id() gives us a clue as to where e // is located in the _elements vector. Try that first // before trying the O(n_elem) search. if (_nodes[n->id()] == n) { pos = _nodes.begin(); std::advance(pos, n->id()); } else { pos = std::find (_nodes.begin(), _nodes.end(), n); } // Huh? Node not in the vector? libmesh_assert (pos != _nodes.end()); // Delete the node from the BoundaryInfo object this->boundary_info->remove(n); // delete the node delete n; // explicitly NULL the pointer *pos = NULL; } void SerialMesh::renumber_node(const unsigned int old_id, const unsigned int new_id) { // This doesn't get used in serial yet Node *node = _nodes[old_id]; libmesh_assert (node); node->set_id(new_id); libmesh_assert (!_nodes[new_id]); _nodes[new_id] = node; _nodes[old_id] = NULL; } void SerialMesh::clear () { // Call parent clear function MeshBase::clear(); // Clear our elements and nodes { std::vector<Elem*>::iterator it = _elements.begin(); const std::vector<Elem*>::iterator end = _elements.end(); // There is no need to remove the elements from // the BoundaryInfo data structure since we // already cleared it. for (; it != end; ++it) delete *it; _elements.clear(); } // clear the nodes data structure { std::vector<Node*>::iterator it = _nodes.begin(); const std::vector<Node*>::iterator end = _nodes.end(); // There is no need to remove the nodes from // the BoundaryInfo data structure since we // already cleared it. for (; it != end; ++it) delete *it; _nodes.clear(); } } void SerialMesh::renumber_nodes_and_elements () { START_LOG("renumber_nodes_and_elem()", "Mesh"); // node and element id counters unsigned int next_free_elem = 0; unsigned int next_free_node = 0; // Loop over the elements. Note that there may // be NULLs in the _elements vector from the coarsening // process. Pack the elements in to a contiguous array // and then trim any excess. { std::vector<Elem*>::iterator in = _elements.begin(); std::vector<Elem*>::iterator out = _elements.begin(); const std::vector<Elem*>::iterator end = _elements.end(); for (; in != end; ++in) if (*in != NULL) { Elem* elem = *in; *out = *in; ++out; // Increment the element counter elem->set_id (next_free_elem++); // Loop over this element's nodes. Number them, // if they have not been numbered already. Also, // position them in the _nodes vector so that they // are packed contiguously from the beginning. for (unsigned int n=0; n<elem->n_nodes(); n++) if (elem->node(n) == next_free_node) // don't need to process next_free_node++; // [(src == dst) below] else if (elem->node(n) > next_free_node) // need to process { // The source and destination indices // for this node const unsigned int src_idx = elem->node(n); const unsigned int dst_idx = next_free_node++; // ensure we want to swap a valid nodes libmesh_assert (_nodes[src_idx] != NULL); // Swap the source and destination nodes std::swap(_nodes[src_idx], _nodes[dst_idx] ); // Set proper indices where that makes sense if (_nodes[src_idx] != NULL) _nodes[src_idx]->set_id (src_idx); _nodes[dst_idx]->set_id (dst_idx); } } // Erase any additional storage. These elements have been // copied into NULL voids by the procedure above, and are // thus repeated and unnecessary. _elements.erase (out, end); } // Any nodes in the vector >= _nodes[next_free_node] // are not connected to any elements and may be deleted // if desired. // (This code block will erase the unused nodes) // Now, delete the unused nodes { std::vector<Node*>::iterator nd = _nodes.begin(); const std::vector<Node*>::iterator end = _nodes.end(); std::advance (nd, next_free_node); for (std::vector<Node*>::iterator it=nd; it != end; ++it) { // Mesh modification code might have already deleted some // nodes if (*it == NULL) continue; // remove any boundary information associated with // this node this->boundary_info->remove (*it); // delete the node delete *it; *it = NULL; } _nodes.erase (nd, end); } libmesh_assert (next_free_elem == _elements.size()); libmesh_assert (next_free_node == _nodes.size()); STOP_LOG("renumber_nodes_and_elem()", "Mesh"); } void SerialMesh::fix_broken_node_and_element_numbering () { // Nodes first for (unsigned int n=0; n<this->_nodes.size(); n++) if (this->_nodes[n] != NULL) this->_nodes[n]->set_id() = n; // Elements next for (unsigned int e=0; e<this->_elements.size(); e++) if (this->_elements[e] != NULL) this->_elements[e]->set_id() = e; } unsigned int SerialMesh::n_active_elem () const { return static_cast<unsigned int>(std::distance (this->active_elements_begin(), this->active_elements_end())); } } // namespace libMesh <|endoftext|>
<commit_before>#include "table.h" #include "ui_table.h" table::table(QWidget *parent) : QMainWindow(parent), ui(new Ui::table), m_fileName("") { ui->setupUi(this); ui->tableView->move(0, 0); m_model = new TeamModel(ui->actionSave, this); ui->tableView->setModel(m_model); ui->actionSave->setEnabled(false); ui->tableView->horizontalHeader()->setStretchLastSection(true); } table::~table() { delete ui; if (m_model) { delete m_model; } } void table::resizeEvent(QResizeEvent*) { ui->tableView->resize(size()); ui->tableView->setColumnWidth(0, ui->tableView->width() / 2); } void table::on_actionInsert_row_triggered() { input dlg; dlg.setModal(true); if (dlg.exec() == dlg.Accepted) { m_model->append(dlg.newTeamRow); } } void table::on_actionDelete_row_triggered() { m_model->RemoveLast(); } void table::on_actionOpen_triggered() { Open(); } void table::on_actionSave_triggered() { Save(); } void table::on_actionNew_triggered() { New(); } void table::on_actionSave_as_triggered() { SaveAs(); } void table::on_actionAbout_Application_triggered() { QMessageBox box; box.setWindowTitle("About author"); box.setText("Statistics Editor"); box.setInformativeText("Copyright © 2015 Alitov Vladimir"); box.exec(); } bool table::SaveRequest() { auto confirmDlg = QMessageBox::question(this, tr("Save request"), tr("Do you want to save changes?"), QMessageBox::Yes|QMessageBox::No); return (confirmDlg == QMessageBox::Yes); } void table::Save(QString filePath) { if (m_model->smthChanged || filePath != "") { if (m_fileName == "" && filePath == "") { SaveAs(); return; } if (filePath == "") { filePath = m_fileName; } QFile f(filePath); if(f.open(QIODevice::WriteOnly)) { QVariantMap data; for (int i = 0; i < m_model->rowCount(QModelIndex()); ++i) { data.insert(m_model->data(m_model->index(i, 0), Qt::DisplayRole).toString(), m_model->data(m_model->index(i, 1), Qt::DisplayRole).toInt()); } QJsonDocument doc; f.write(doc.fromVariant(data).toJson()); f.close(); } m_model->smthChanged = false; ui->actionSave->setEnabled(false); } } void table::SaveAs() { QString filePath = QFileDialog::getSaveFileName(this,tr("Open"),QString(),tr("JSON Files (*.json)")); if (filePath != "") { Save(filePath); } } void table::Open() { if (m_model->smthChanged) { if (SaveRequest()) { Save(); } } QString fileName = QFileDialog::getOpenFileName(this,tr("Open"),QString(),tr("JSON Files (*.json)")); if (fileName == "") { return; } QFile f(fileName); QString data = ""; if(f.open(QIODevice::ReadOnly)) { data = f.readAll(); f.close(); } QJsonParseError parseError; QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8(), &parseError); if(parseError.error) { QMessageBox::warning(this, tr("Error"), tr("Parse error")); return; } auto items = doc.object(); m_model->clear(); for (QJsonObject::Iterator iter = items.begin(); iter != items.end(); ++iter) { Team newTeam(iter.key(), iter.value().toInt()); m_model->append(newTeam); } m_fileName = fileName; m_model->smthChanged = false; ui->actionSave->setEnabled(false); } void table::New() { if (m_model->smthChanged) { if (SaveRequest()) { if (m_fileName == "") { SaveAs(); } else { Save(); } } } m_fileName = ""; m_model->clear(); m_model->smthChanged = false; } void table::closeEvent(QCloseEvent*) { if(m_model->smthChanged) { if(SaveRequest()) { Save(); } } } <commit_msg>Одну строчку забыл<commit_after>#include "table.h" #include "ui_table.h" table::table(QWidget *parent) : QMainWindow(parent), ui(new Ui::table), m_fileName("") { ui->setupUi(this); ui->tableView->move(0, 0); m_model = new TeamModel(ui->actionSave, this); ui->tableView->setModel(m_model); ui->actionSave->setEnabled(false); ui->tableView->horizontalHeader()->setStretchLastSection(true); } table::~table() { delete ui; if (m_model) { delete m_model; } } void table::resizeEvent(QResizeEvent*) { ui->tableView->resize(size()); ui->tableView->setColumnWidth(0, ui->tableView->width() / 2); } void table::on_actionInsert_row_triggered() { input dlg; dlg.setModal(true); if (dlg.exec() == dlg.Accepted) { m_model->append(dlg.newTeamRow); } } void table::on_actionDelete_row_triggered() { m_model->RemoveLast(); } void table::on_actionOpen_triggered() { Open(); } void table::on_actionSave_triggered() { Save(); } void table::on_actionNew_triggered() { New(); } void table::on_actionSave_as_triggered() { SaveAs(); } void table::on_actionAbout_Application_triggered() { QMessageBox box; box.setWindowTitle("About author"); box.setText("Statistics Editor"); box.setInformativeText("Copyright © 2015 Alitov Vladimir"); box.exec(); } bool table::SaveRequest() { auto confirmDlg = QMessageBox::question(this, tr("Save request"), tr("Do you want to save changes?"), QMessageBox::Yes|QMessageBox::No); return (confirmDlg == QMessageBox::Yes); } void table::Save(QString filePath) { if (m_model->smthChanged || filePath != "") { if (m_fileName == "" && filePath == "") { SaveAs(); return; } if (filePath == "") { filePath = m_fileName; } QFile f(filePath); if(f.open(QIODevice::WriteOnly)) { QVariantMap data; for (int i = 0; i < m_model->rowCount(QModelIndex()); ++i) { data.insert(m_model->data(m_model->index(i, 0), Qt::DisplayRole).toString(), m_model->data(m_model->index(i, 1), Qt::DisplayRole).toInt()); } QJsonDocument doc; f.write(doc.fromVariant(data).toJson()); f.close(); } m_fileName = filePath; m_model->smthChanged = false; ui->actionSave->setEnabled(false); } } void table::SaveAs() { QString filePath = QFileDialog::getSaveFileName(this,tr("Open"),QString(),tr("JSON Files (*.json)")); if (filePath != "") { Save(filePath); } } void table::Open() { if (m_model->smthChanged) { if (SaveRequest()) { Save(); } } QString fileName = QFileDialog::getOpenFileName(this,tr("Open"),QString(),tr("JSON Files (*.json)")); if (fileName == "") { return; } QFile f(fileName); QString data = ""; if(f.open(QIODevice::ReadOnly)) { data = f.readAll(); f.close(); } QJsonParseError parseError; QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8(), &parseError); if(parseError.error) { QMessageBox::warning(this, tr("Error"), tr("Parse error")); return; } auto items = doc.object(); m_model->clear(); for (QJsonObject::Iterator iter = items.begin(); iter != items.end(); ++iter) { Team newTeam(iter.key(), iter.value().toInt()); m_model->append(newTeam); } m_fileName = fileName; m_model->smthChanged = false; ui->actionSave->setEnabled(false); } void table::New() { if (m_model->smthChanged) { if (SaveRequest()) { if (m_fileName == "") { SaveAs(); } else { Save(); } } } m_fileName = ""; m_model->clear(); m_model->smthChanged = false; } void table::closeEvent(QCloseEvent*) { if(m_model->smthChanged) { if(SaveRequest()) { Save(); } } } <|endoftext|>
<commit_before>// $Id$ // // Copyright (C) 2004-2006 Rational Discovery LLC // // @@ All Rights Reserved @@ // #define NO_IMPORT_ARRAY #include <boost/python.hpp> #include <GraphMol/RDKitBase.h> #include <RDGeneral/types.h> #include <RDBoost/Exceptions.h> #include <GraphMol/MolChemicalFeatures/MolChemicalFeatureFactory.h> #include <GraphMol/MolChemicalFeatures/MolChemicalFeature.h> #include <boost/python/converter/shared_ptr_to_python.hpp> namespace python = boost::python; namespace RDKit { // ---------------------------------------------------------------------------- // NOTE: the reason we don't provide an interface to get all the // features from a molecule at the same time directly from C++ is a // potential problem with the lifetime of molecules and features: // Each Feature carries around a pointer to its owning molecule, // and that pointer must remain valid. So we need to use the BPL's // with_custodian_and_ward() functionality to tie the lifetime // of the molecule to that of the feature. This is not currently // possible in BPL v1.32 if we return a tuple of objects; so if // we return a set of features, there's no way to use // with_custodian_and_ward() to ensure that the molecule doesn't vanish // underneath them. Access to all of a molecule's features is provided // from within python (looping over getMolFeature() and gaining efficiency // by not recomputing after the first call). // ---------------------------------------------------------------------------- int getNumMolFeatures(const MolChemicalFeatureFactory &factory, const ROMol &mol, std::string includeOnly="") { FeatSPtrList feats = factory.getFeaturesForMol(mol,includeOnly.c_str()); return feats.size(); } FeatSPtr getMolFeature(const MolChemicalFeatureFactory &factory, const ROMol &mol, int idx, std::string includeOnly="", bool recompute=true) { static FeatSPtrList feats; if(recompute){ feats = factory.getFeaturesForMol(mol,includeOnly.c_str()); } if(idx<0 || idx>=static_cast<int>(feats.size())){ throw IndexErrorException(idx); } FeatSPtrList_I fi=feats.begin(); for(int i=0;i<idx;++i){ ++fi; } return (*fi); } python::tuple getFeatureFamilies(const MolChemicalFeatureFactory &factory){ python::list res; MolChemicalFeatureDef::CollectionType::const_iterator iter; for(iter=factory.beginFeatureDefs();iter!=factory.endFeatureDefs();++iter){ std::string fam= (*iter)->getFamily(); if(res.count(fam)==0) res.append(fam); } return python::tuple(res); } struct featfactory_wrapper { static void wrap() { std::string factoryClassDoc="Class to featurize a molecule\n"; // no direct constructor - use buildFactory function python::class_<MolChemicalFeatureFactory>("MolChemicalFeatureFactory", factoryClassDoc.c_str(), python::no_init) .def("GetNumFeatureDefs", &MolChemicalFeatureFactory::getNumFeatureDefs, "Get the number of feature definitions") .def("GetFeatureFamilies", getFeatureFamilies, "Get a tuple of feature types") .def("GetNumMolFeatures", getNumMolFeatures, (python::arg("mol"),python::arg("includeOnly")=std::string("")), "Get the number of features the molecule has") .def("GetMolFeature", getMolFeature, (python::arg("mol"),python::arg("idx"), python::arg("includeOnly")=std::string(""), python::arg("recompute")=true), python::with_custodian_and_ward_postcall<0,2>(), "returns a particular feature (by index)") ; }; }; } void wrap_factory() { RDKit::featfactory_wrapper::wrap(); } <commit_msg>add GetFeatureDefs() method<commit_after>// $Id$ // // Copyright (C) 2004-2006 Rational Discovery LLC // // @@ All Rights Reserved @@ // #define NO_IMPORT_ARRAY #include <boost/python.hpp> #include <GraphMol/RDKitBase.h> #include <RDGeneral/types.h> #include <RDBoost/Exceptions.h> #include <GraphMol/MolChemicalFeatures/MolChemicalFeatureFactory.h> #include <GraphMol/MolChemicalFeatures/MolChemicalFeature.h> #include <boost/python/converter/shared_ptr_to_python.hpp> namespace python = boost::python; namespace RDKit { // ---------------------------------------------------------------------------- // NOTE: the reason we don't provide an interface to get all the // features from a molecule at the same time directly from C++ is a // potential problem with the lifetime of molecules and features: // Each Feature carries around a pointer to its owning molecule, // and that pointer must remain valid. So we need to use the BPL's // with_custodian_and_ward() functionality to tie the lifetime // of the molecule to that of the feature. This is not currently // possible in BPL v1.32 if we return a tuple of objects; so if // we return a set of features, there's no way to use // with_custodian_and_ward() to ensure that the molecule doesn't vanish // underneath them. Access to all of a molecule's features is provided // from within python (looping over getMolFeature() and gaining efficiency // by not recomputing after the first call). // ---------------------------------------------------------------------------- int getNumMolFeatures(const MolChemicalFeatureFactory &factory, const ROMol &mol, std::string includeOnly="") { FeatSPtrList feats = factory.getFeaturesForMol(mol,includeOnly.c_str()); return feats.size(); } FeatSPtr getMolFeature(const MolChemicalFeatureFactory &factory, const ROMol &mol, int idx, std::string includeOnly="", bool recompute=true) { static FeatSPtrList feats; if(recompute){ feats = factory.getFeaturesForMol(mol,includeOnly.c_str()); } if(idx<0 || idx>=static_cast<int>(feats.size())){ throw IndexErrorException(idx); } FeatSPtrList_I fi=feats.begin(); for(int i=0;i<idx;++i){ ++fi; } return (*fi); } python::tuple getFeatureFamilies(const MolChemicalFeatureFactory &factory){ python::list res; MolChemicalFeatureDef::CollectionType::const_iterator iter; for(iter=factory.beginFeatureDefs();iter!=factory.endFeatureDefs();++iter){ std::string fam= (*iter)->getFamily(); if(res.count(fam)==0) res.append(fam); } return python::tuple(res); } python::dict getFeatureDefs(const MolChemicalFeatureFactory &factory){ python::dict res; MolChemicalFeatureDef::CollectionType::const_iterator iter; for(iter=factory.beginFeatureDefs();iter!=factory.endFeatureDefs();++iter){ std::string key= (*iter)->getFamily()+"."+(*iter)->getType(); res[key]=(*iter)->getSmarts(); } return res; } struct featfactory_wrapper { static void wrap() { std::string factoryClassDoc="Class to featurize a molecule\n"; // no direct constructor - use buildFactory function python::class_<MolChemicalFeatureFactory>("MolChemicalFeatureFactory", factoryClassDoc.c_str(), python::no_init) .def("GetNumFeatureDefs", &MolChemicalFeatureFactory::getNumFeatureDefs, "Get the number of feature definitions") .def("GetFeatureFamilies", getFeatureFamilies, "Get a tuple of feature types") .def("GetFeatureDefs", getFeatureDefs, "Get a dictionary with SMARTS definitions for each feature type") .def("GetNumMolFeatures", getNumMolFeatures, (python::arg("mol"),python::arg("includeOnly")=std::string("")), "Get the number of features the molecule has") .def("GetMolFeature", getMolFeature, (python::arg("mol"),python::arg("idx"), python::arg("includeOnly")=std::string(""), python::arg("recompute")=true), python::with_custodian_and_ward_postcall<0,2>(), "returns a particular feature (by index)") ; }; }; } void wrap_factory() { RDKit::featfactory_wrapper::wrap(); } <|endoftext|>
<commit_before>/* Copyright (c) 2010-2013, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include <QString> #include <QByteArray> #include <QDateTime> #include <QFile> #include <QDir> #include <QFileInfo> #include <QSqlError> #include <TWebApplication> #include <TLogger> #include <TLog> #include <TAccessLog> #include "tsystemglobal.h" #include "taccesslogstream.h" #include "tfileaiowriter.h" static TAccessLogStream *accesslogstrm = 0; static TAccessLogStream *sqllogstrm = 0; static TFileAioWriter systemLog; static QByteArray syslogLayout; static QByteArray syslogDateTimeFormat; static QByteArray accessLogLayout; static QByteArray accessLogDateTimeFormat; void writeAccessLog(const TAccessLog &log) { if (accesslogstrm) { accesslogstrm->writeLog(log.toByteArray(accessLogLayout, accessLogDateTimeFormat)); } } void tSetupSystemLogger() { // Log directory QDir logdir(Tf::app()->logPath()); if (!logdir.exists()) { logdir.mkpath("."); } // system log systemLog.setFileName(Tf::app()->systemLogFilePath()); systemLog.open(); syslogLayout = Tf::app()->appSettings().value("SystemLog.Layout", "%d %5P %m%n").toByteArray(); syslogDateTimeFormat = Tf::app()->appSettings().value("SystemLog.DateTimeFormat", "yyyy-MM-ddThh:mm:ss").toByteArray(); } void tSetupAccessLogger() { // access log QString accesslogpath = Tf::app()->accessLogFilePath(); if (!accesslogstrm && !accesslogpath.isEmpty()) { accesslogstrm = new TAccessLogStream(accesslogpath); } accessLogLayout = Tf::app()->appSettings().value("AccessLog.Layout", "%h %d \"%r\" %s %O%n").toByteArray(); accessLogDateTimeFormat = Tf::app()->appSettings().value("AccessLog.DateTimeFormat", "yyyy-MM-ddThh:mm:ss").toByteArray(); } void tSetupQueryLogger() { // sql query log QString querylogpath = Tf::app()->sqlQueryLogFilePath(); if (!sqllogstrm && !querylogpath.isEmpty()) { sqllogstrm = new TAccessLogStream(querylogpath); } } static void tSystemMessage(int priority, const char *msg, va_list ap) { TLog log(priority, QString().vsprintf(msg, ap).toLocal8Bit()); QByteArray buf = TLogger::logToByteArray(log, syslogLayout, syslogDateTimeFormat); systemLog.write(buf.data(), buf.length()); } void tSystemError(const char *msg, ...) { va_list ap; va_start(ap, msg); tSystemMessage(TLogger::Error, msg, ap); va_end(ap); } void tSystemWarn(const char *msg, ...) { va_list ap; va_start(ap, msg); tSystemMessage(TLogger::Warn, msg, ap); va_end(ap); } void tSystemInfo(const char *msg, ...) { va_list ap; va_start(ap, msg); tSystemMessage(TLogger::Info, msg, ap); va_end(ap); } #ifndef TF_NO_DEBUG void tSystemDebug(const char *msg, ...) { va_list ap; va_start(ap, msg); tSystemMessage(TLogger::Debug, msg, ap); va_end(ap); } void tSystemTrace(const char *msg, ...) { va_list ap; va_start(ap, msg); tSystemMessage(TLogger::Trace, msg, ap); va_end(ap); } #else void tSystemDebug(const char *, ...) { } void tSystemTrace(const char *, ...) { } #endif void tQueryLog(const char *msg, ...) { if (sqllogstrm) { va_list ap; va_start(ap, msg); TLog log(-1, QString().vsprintf(msg, ap).toLocal8Bit()); QByteArray buf = TLogger::logToByteArray(log, syslogLayout, syslogDateTimeFormat); sqllogstrm->writeLog(buf); va_end(ap); } } void tWriteQueryLog(const QString &query, bool success, const QSqlError &error) { QString q = query; if (!success) { QString err = (!error.databaseText().isEmpty()) ? error.databaseText() : error.text().trimmed(); if (!err.isEmpty()) { err = QLatin1Char('[') + err + QLatin1String("] "); } q = QLatin1String("(Query failed) ") + err + query; } tQueryLog("%s", qPrintable(q)); } <commit_msg>add flushing to access logging.<commit_after>/* Copyright (c) 2010-2013, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include <QString> #include <QByteArray> #include <QDateTime> #include <QFile> #include <QDir> #include <QFileInfo> #include <QSqlError> #include <TWebApplication> #include <TLogger> #include <TLog> #include <TAccessLog> #include "tsystemglobal.h" #include "taccesslogstream.h" #include "tfileaiowriter.h" static TAccessLogStream *accesslogstrm = 0; static TAccessLogStream *sqllogstrm = 0; static TFileAioWriter systemLog; static QByteArray syslogLayout; static QByteArray syslogDateTimeFormat; static QByteArray accessLogLayout; static QByteArray accessLogDateTimeFormat; void writeAccessLog(const TAccessLog &log) { if (accesslogstrm) { accesslogstrm->writeLog(log.toByteArray(accessLogLayout, accessLogDateTimeFormat)); if (Tf::app()->multiProcessingModule() == TWebApplication::Prefork) { accesslogstrm->flush(); } } } void tSetupSystemLogger() { // Log directory QDir logdir(Tf::app()->logPath()); if (!logdir.exists()) { logdir.mkpath("."); } // system log systemLog.setFileName(Tf::app()->systemLogFilePath()); systemLog.open(); syslogLayout = Tf::app()->appSettings().value("SystemLog.Layout", "%d %5P %m%n").toByteArray(); syslogDateTimeFormat = Tf::app()->appSettings().value("SystemLog.DateTimeFormat", "yyyy-MM-ddThh:mm:ss").toByteArray(); } void tSetupAccessLogger() { // access log QString accesslogpath = Tf::app()->accessLogFilePath(); if (!accesslogstrm && !accesslogpath.isEmpty()) { accesslogstrm = new TAccessLogStream(accesslogpath); } accessLogLayout = Tf::app()->appSettings().value("AccessLog.Layout", "%h %d \"%r\" %s %O%n").toByteArray(); accessLogDateTimeFormat = Tf::app()->appSettings().value("AccessLog.DateTimeFormat", "yyyy-MM-ddThh:mm:ss").toByteArray(); } void tSetupQueryLogger() { // sql query log QString querylogpath = Tf::app()->sqlQueryLogFilePath(); if (!sqllogstrm && !querylogpath.isEmpty()) { sqllogstrm = new TAccessLogStream(querylogpath); } } static void tSystemMessage(int priority, const char *msg, va_list ap) { TLog log(priority, QString().vsprintf(msg, ap).toLocal8Bit()); QByteArray buf = TLogger::logToByteArray(log, syslogLayout, syslogDateTimeFormat); systemLog.write(buf.data(), buf.length()); if (Tf::app()->multiProcessingModule() == TWebApplication::Prefork) { systemLog.flush(); } } void tSystemError(const char *msg, ...) { va_list ap; va_start(ap, msg); tSystemMessage(TLogger::Error, msg, ap); va_end(ap); } void tSystemWarn(const char *msg, ...) { va_list ap; va_start(ap, msg); tSystemMessage(TLogger::Warn, msg, ap); va_end(ap); } void tSystemInfo(const char *msg, ...) { va_list ap; va_start(ap, msg); tSystemMessage(TLogger::Info, msg, ap); va_end(ap); } #ifndef TF_NO_DEBUG void tSystemDebug(const char *msg, ...) { va_list ap; va_start(ap, msg); tSystemMessage(TLogger::Debug, msg, ap); va_end(ap); } void tSystemTrace(const char *msg, ...) { va_list ap; va_start(ap, msg); tSystemMessage(TLogger::Trace, msg, ap); va_end(ap); } #else void tSystemDebug(const char *, ...) { } void tSystemTrace(const char *, ...) { } #endif void tQueryLog(const char *msg, ...) { if (sqllogstrm) { va_list ap; va_start(ap, msg); TLog log(-1, QString().vsprintf(msg, ap).toLocal8Bit()); QByteArray buf = TLogger::logToByteArray(log, syslogLayout, syslogDateTimeFormat); sqllogstrm->writeLog(buf); va_end(ap); if (Tf::app()->multiProcessingModule() == TWebApplication::Prefork) { sqllogstrm->flush(); } } } void tWriteQueryLog(const QString &query, bool success, const QSqlError &error) { QString q = query; if (!success) { QString err = (!error.databaseText().isEmpty()) ? error.databaseText() : error.text().trimmed(); if (!err.isEmpty()) { err = QLatin1Char('[') + err + QLatin1String("] "); } q = QLatin1String("(Query failed) ") + err + query; } tQueryLog("%s", qPrintable(q)); } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <graphene/protocol/operations.hpp> namespace graphene { namespace protocol { struct predicate_result; using rejected_predicate = static_variant<predicate_result, fc::exception>; using rejected_predicate_map = map<custom_authority_id_type, rejected_predicate>; using custom_authority_lookup = std::function<vector<authority>(account_id_type, const operation&, rejected_predicate_map*)>; /** * @defgroup transactions Transactions * * All transactions are sets of operations that must be applied atomically. Transactions must refer to a recent * block that defines the context of the operation so that they assert a known binding to the object id's referenced * in the transaction. * * Rather than specify a full block number, we only specify the lower 16 bits of the block number which means you * can reference any block within the last 65,536 blocks which is 3.5 days with a 5 second block interval or 18 * hours with a 1 second interval. * * All transactions must expire so that the network does not have to maintain a permanent record of all transactions * ever published. A transaction may not have an expiration date too far in the future because this would require * keeping too much transaction history in memory. * * The block prefix is the first 4 bytes of the block hash of the reference block number, which is the second 4 * bytes of the @ref block_id_type (the first 4 bytes of the block ID are the block number) * * Note: A transaction which selects a reference block cannot be migrated between forks outside the period of * ref_block_num.time to (ref_block_num.time + rel_exp * interval). This fact can be used to protect market orders * which should specify a relatively short re-org window of perhaps less than 1 minute. Normal payments should * probably have a longer re-org window to ensure their transaction can still go through in the event of a momentary * disruption in service. * * @note It is not recommended to set the @ref ref_block_num, @ref ref_block_prefix, and @ref expiration * fields manually. Call the appropriate overload of @ref set_expiration instead. * * @{ */ /** * @brief groups operations that should be applied atomically */ class transaction { public: virtual ~transaction() = default; /** * Least significant 16 bits from the reference block number. If @ref relative_expiration is zero, this field * must be zero as well. */ uint16_t ref_block_num = 0; /** * The first non-block-number 32-bits of the reference block ID. Recall that block IDs have 32 bits of block * number followed by the actual block hash, so this field should be set using the second 32 bits in the * @ref block_id_type */ uint32_t ref_block_prefix = 0; /** * This field specifies the absolute expiration for this transaction. */ fc::time_point_sec expiration; vector<operation> operations; extensions_type extensions; /// Calculate the digest for a transaction digest_type digest()const; virtual const transaction_id_type& id()const; virtual void validate() const; void set_expiration( fc::time_point_sec expiration_time ); void set_reference_block( const block_id_type& reference_block ); /// visit all operations template<typename Visitor> vector<typename Visitor::result_type> visit( Visitor&& visitor ) { vector<typename Visitor::result_type> results; for( auto& op : operations ) results.push_back(op.visit( std::forward<Visitor>( visitor ) )); return results; } template<typename Visitor> vector<typename Visitor::result_type> visit( Visitor&& visitor )const { vector<typename Visitor::result_type> results; for( auto& op : operations ) results.push_back(op.visit( std::forward<Visitor>( visitor ) )); return results; } void get_required_authorities( flat_set<account_id_type>& active, flat_set<account_id_type>& owner, vector<authority>& other, bool ignore_custom_operation_required_auths )const; virtual uint64_t get_packed_size()const; protected: // Calculate the digest used for signature validation digest_type sig_digest( const chain_id_type& chain_id )const; mutable transaction_id_type _tx_id_buffer; }; /** * @brief adds a signature to a transaction */ class signed_transaction : public transaction { public: signed_transaction( const transaction& trx = transaction() ) : transaction(trx){} virtual ~signed_transaction() = default; /** signs and appends to signatures */ const signature_type& sign( const private_key_type& key, const chain_id_type& chain_id ); /** returns signature but does not append */ signature_type sign( const private_key_type& key, const chain_id_type& chain_id )const; /** * The purpose of this method is to identify some subset of * @ref available_keys that will produce sufficient signatures * for a transaction. The result is not always a minimal set of * signatures, but any non-minimal result will still pass * validation. */ set<public_key_type> get_required_signatures( const chain_id_type& chain_id, const flat_set<public_key_type>& available_keys, const std::function<const authority*(account_id_type)>& get_active, const std::function<const authority*(account_id_type)>& get_owner, bool allow_non_immediate_owner, bool ignore_custom_operation_required_authorities, uint32_t max_recursion = GRAPHENE_MAX_SIG_CHECK_DEPTH )const; /** * Checks whether signatures in this signed transaction are sufficient to authorize the transaction. * Throws an exception when failed. * * @param chain_id the ID of a block chain * @param get_active callback function to retrieve active authorities of a given account * @param get_owner callback function to retrieve owner authorities of a given account * @param get_custom callback function to retrieve viable custom authorities for a given account and operation * @param allow_non_immediate_owner whether to allow owner authority of non-immediately * required accounts to authorize operations in the transaction * @param ignore_custom_operation_required_auths See issue #210; whether to ignore the * required_auths field of custom_operation or not * @param max_recursion maximum level of recursion when verifying, since an account * can have another account in active authorities and/or owner authorities */ void verify_authority( const chain_id_type& chain_id, const std::function<const authority*(account_id_type)>& get_active, const std::function<const authority*(account_id_type)>& get_owner, const custom_authority_lookup& get_custom, bool allow_non_immediate_owner, bool ignore_custom_operation_required_auths, uint32_t max_recursion = GRAPHENE_MAX_SIG_CHECK_DEPTH )const; /** * This is a slower replacement for get_required_signatures() * which returns a minimal set in all cases, including * some cases where get_required_signatures() returns a * non-minimal set. */ set<public_key_type> minimize_required_signatures( const chain_id_type& chain_id, const flat_set<public_key_type>& available_keys, const std::function<const authority*(account_id_type)>& get_active, const std::function<const authority*(account_id_type)>& get_owner, const custom_authority_lookup& get_custom, bool allow_non_immediate_owner, bool ignore_custom_operation_required_auths, uint32_t max_recursion = GRAPHENE_MAX_SIG_CHECK_DEPTH) const; /** * @brief Extract public keys from signatures with given chain ID. * @param chain_id A chain ID * @return Public keys * @note If @ref signees is empty, E.G. when it's the first time calling * this function for the signed transaction, public keys will be * extracted with given chain ID, and be stored into the mutable * @ref signees field, then @ref signees will be returned; * otherwise, the @ref chain_id parameter will be ignored, and * @ref signees will be returned directly. */ virtual const flat_set<public_key_type>& get_signature_keys( const chain_id_type& chain_id )const; /** Signatures */ vector<signature_type> signatures; /** Removes all operations and signatures */ void clear() { operations.clear(); signatures.clear(); } /** Removes all signatures */ void clear_signatures() { signatures.clear(); } protected: /** Public keys extracted from signatures */ mutable flat_set<public_key_type> _signees; }; /** This represents a signed transaction that will never have its operations, * signatures etc. modified again, after initial creation. It is therefore * safe to cache results from various calls. */ class precomputable_transaction : public signed_transaction { public: precomputable_transaction() {} precomputable_transaction( const signed_transaction& tx ) : signed_transaction(tx) {}; precomputable_transaction( signed_transaction&& tx ) : signed_transaction( std::move(tx) ) {}; virtual ~precomputable_transaction() = default; virtual const transaction_id_type& id()const override; virtual void validate()const override; virtual const flat_set<public_key_type>& get_signature_keys( const chain_id_type& chain_id )const override; virtual uint64_t get_packed_size()const override; protected: mutable bool _validated = false; mutable uint64_t _packed_size = 0; }; /** * Checks whether given public keys and approvals are sufficient to authorize given operations. * Throws an exception when failed. * * @param ops a vector of operations * @param sigs a set of public keys * @param get_active callback function to retrieve active authorities of a given account * @param get_owner callback function to retrieve owner authorities of a given account * @param allow_non_immediate_owner whether to allow owner authority of non-immediately * required accounts to authorize operations * @param ignore_custom_operation_required_auths See issue #210; whether to ignore the * required_auths field of custom_operation or not * @param max_recursion maximum level of recursion when verifying, since an account * can have another account in active authorities and/or owner authorities * @param allow_committee whether to allow the special "committee account" to authorize the operations * @param active_approvals accounts that approved the operations with their active authories * @param owner_approvals accounts that approved the operations with their owner authories */ void verify_authority( const vector<operation>& ops, const flat_set<public_key_type>& sigs, const std::function<const authority*(account_id_type)>& get_active, const std::function<const authority*(account_id_type)>& get_owner, const custom_authority_lookup& get_custom, bool allow_non_immediate_owner, bool ignore_custom_operation_required_auths, uint32_t max_recursion = GRAPHENE_MAX_SIG_CHECK_DEPTH, bool allow_committee = false, const flat_set<account_id_type>& active_aprovals = flat_set<account_id_type>(), const flat_set<account_id_type>& owner_approvals = flat_set<account_id_type>() ); /** * @brief captures the result of evaluating the operations contained in the transaction * * When processing a transaction some operations generate * new object IDs and these IDs cannot be known until the * transaction is actually included into a block. When a * block is produced these new ids are captured and included * with every transaction. The index in operation_results should * correspond to the same index in operations. * * If an operation did not create any new object IDs then 0 * should be returned. */ struct processed_transaction : public precomputable_transaction { processed_transaction( const signed_transaction& trx = signed_transaction() ) : precomputable_transaction(trx){} virtual ~processed_transaction() = default; vector<operation_result> operation_results; digest_type merkle_digest()const; }; /// @} transactions group } } // graphene::protocol FC_REFLECT( graphene::protocol::transaction, (ref_block_num)(ref_block_prefix)(expiration)(operations)(extensions) ) // Note: not reflecting signees field for backward compatibility; in addition, it should not be in p2p messages FC_REFLECT_DERIVED( graphene::protocol::signed_transaction, (graphene::protocol::transaction), (signatures) ) FC_REFLECT_DERIVED( graphene::protocol::precomputable_transaction, (graphene::protocol::signed_transaction), ) FC_REFLECT_DERIVED( graphene::protocol::processed_transaction, (graphene::protocol::precomputable_transaction), (operation_results) ) GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::transaction) GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::signed_transaction) GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::precomputable_transaction) GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::processed_transaction) <commit_msg>Add docs for get_custom arg in verify_authority()<commit_after>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <graphene/protocol/operations.hpp> namespace graphene { namespace protocol { struct predicate_result; using rejected_predicate = static_variant<predicate_result, fc::exception>; using rejected_predicate_map = map<custom_authority_id_type, rejected_predicate>; using custom_authority_lookup = std::function<vector<authority>(account_id_type, const operation&, rejected_predicate_map*)>; /** * @defgroup transactions Transactions * * All transactions are sets of operations that must be applied atomically. Transactions must refer to a recent * block that defines the context of the operation so that they assert a known binding to the object id's referenced * in the transaction. * * Rather than specify a full block number, we only specify the lower 16 bits of the block number which means you * can reference any block within the last 65,536 blocks which is 3.5 days with a 5 second block interval or 18 * hours with a 1 second interval. * * All transactions must expire so that the network does not have to maintain a permanent record of all transactions * ever published. A transaction may not have an expiration date too far in the future because this would require * keeping too much transaction history in memory. * * The block prefix is the first 4 bytes of the block hash of the reference block number, which is the second 4 * bytes of the @ref block_id_type (the first 4 bytes of the block ID are the block number) * * Note: A transaction which selects a reference block cannot be migrated between forks outside the period of * ref_block_num.time to (ref_block_num.time + rel_exp * interval). This fact can be used to protect market orders * which should specify a relatively short re-org window of perhaps less than 1 minute. Normal payments should * probably have a longer re-org window to ensure their transaction can still go through in the event of a momentary * disruption in service. * * @note It is not recommended to set the @ref ref_block_num, @ref ref_block_prefix, and @ref expiration * fields manually. Call the appropriate overload of @ref set_expiration instead. * * @{ */ /** * @brief groups operations that should be applied atomically */ class transaction { public: virtual ~transaction() = default; /** * Least significant 16 bits from the reference block number. If @ref relative_expiration is zero, this field * must be zero as well. */ uint16_t ref_block_num = 0; /** * The first non-block-number 32-bits of the reference block ID. Recall that block IDs have 32 bits of block * number followed by the actual block hash, so this field should be set using the second 32 bits in the * @ref block_id_type */ uint32_t ref_block_prefix = 0; /** * This field specifies the absolute expiration for this transaction. */ fc::time_point_sec expiration; vector<operation> operations; extensions_type extensions; /// Calculate the digest for a transaction digest_type digest()const; virtual const transaction_id_type& id()const; virtual void validate() const; void set_expiration( fc::time_point_sec expiration_time ); void set_reference_block( const block_id_type& reference_block ); /// visit all operations template<typename Visitor> vector<typename Visitor::result_type> visit( Visitor&& visitor ) { vector<typename Visitor::result_type> results; for( auto& op : operations ) results.push_back(op.visit( std::forward<Visitor>( visitor ) )); return results; } template<typename Visitor> vector<typename Visitor::result_type> visit( Visitor&& visitor )const { vector<typename Visitor::result_type> results; for( auto& op : operations ) results.push_back(op.visit( std::forward<Visitor>( visitor ) )); return results; } void get_required_authorities( flat_set<account_id_type>& active, flat_set<account_id_type>& owner, vector<authority>& other, bool ignore_custom_operation_required_auths )const; virtual uint64_t get_packed_size()const; protected: // Calculate the digest used for signature validation digest_type sig_digest( const chain_id_type& chain_id )const; mutable transaction_id_type _tx_id_buffer; }; /** * @brief adds a signature to a transaction */ class signed_transaction : public transaction { public: signed_transaction( const transaction& trx = transaction() ) : transaction(trx){} virtual ~signed_transaction() = default; /** signs and appends to signatures */ const signature_type& sign( const private_key_type& key, const chain_id_type& chain_id ); /** returns signature but does not append */ signature_type sign( const private_key_type& key, const chain_id_type& chain_id )const; /** * The purpose of this method is to identify some subset of * @ref available_keys that will produce sufficient signatures * for a transaction. The result is not always a minimal set of * signatures, but any non-minimal result will still pass * validation. */ set<public_key_type> get_required_signatures( const chain_id_type& chain_id, const flat_set<public_key_type>& available_keys, const std::function<const authority*(account_id_type)>& get_active, const std::function<const authority*(account_id_type)>& get_owner, bool allow_non_immediate_owner, bool ignore_custom_operation_required_authorities, uint32_t max_recursion = GRAPHENE_MAX_SIG_CHECK_DEPTH )const; /** * Checks whether signatures in this signed transaction are sufficient to authorize the transaction. * Throws an exception when failed. * * @param chain_id the ID of a block chain * @param get_active callback function to retrieve active authorities of a given account * @param get_owner callback function to retrieve owner authorities of a given account * @param get_custom callback function to retrieve viable custom authorities for a given account and operation * @param allow_non_immediate_owner whether to allow owner authority of non-immediately * required accounts to authorize operations in the transaction * @param ignore_custom_operation_required_auths See issue #210; whether to ignore the * required_auths field of custom_operation or not * @param max_recursion maximum level of recursion when verifying, since an account * can have another account in active authorities and/or owner authorities */ void verify_authority( const chain_id_type& chain_id, const std::function<const authority*(account_id_type)>& get_active, const std::function<const authority*(account_id_type)>& get_owner, const custom_authority_lookup& get_custom, bool allow_non_immediate_owner, bool ignore_custom_operation_required_auths, uint32_t max_recursion = GRAPHENE_MAX_SIG_CHECK_DEPTH )const; /** * This is a slower replacement for get_required_signatures() * which returns a minimal set in all cases, including * some cases where get_required_signatures() returns a * non-minimal set. */ set<public_key_type> minimize_required_signatures( const chain_id_type& chain_id, const flat_set<public_key_type>& available_keys, const std::function<const authority*(account_id_type)>& get_active, const std::function<const authority*(account_id_type)>& get_owner, const custom_authority_lookup& get_custom, bool allow_non_immediate_owner, bool ignore_custom_operation_required_auths, uint32_t max_recursion = GRAPHENE_MAX_SIG_CHECK_DEPTH) const; /** * @brief Extract public keys from signatures with given chain ID. * @param chain_id A chain ID * @return Public keys * @note If @ref signees is empty, E.G. when it's the first time calling * this function for the signed transaction, public keys will be * extracted with given chain ID, and be stored into the mutable * @ref signees field, then @ref signees will be returned; * otherwise, the @ref chain_id parameter will be ignored, and * @ref signees will be returned directly. */ virtual const flat_set<public_key_type>& get_signature_keys( const chain_id_type& chain_id )const; /** Signatures */ vector<signature_type> signatures; /** Removes all operations and signatures */ void clear() { operations.clear(); signatures.clear(); } /** Removes all signatures */ void clear_signatures() { signatures.clear(); } protected: /** Public keys extracted from signatures */ mutable flat_set<public_key_type> _signees; }; /** This represents a signed transaction that will never have its operations, * signatures etc. modified again, after initial creation. It is therefore * safe to cache results from various calls. */ class precomputable_transaction : public signed_transaction { public: precomputable_transaction() {} precomputable_transaction( const signed_transaction& tx ) : signed_transaction(tx) {}; precomputable_transaction( signed_transaction&& tx ) : signed_transaction( std::move(tx) ) {}; virtual ~precomputable_transaction() = default; virtual const transaction_id_type& id()const override; virtual void validate()const override; virtual const flat_set<public_key_type>& get_signature_keys( const chain_id_type& chain_id )const override; virtual uint64_t get_packed_size()const override; protected: mutable bool _validated = false; mutable uint64_t _packed_size = 0; }; /** * Checks whether given public keys and approvals are sufficient to authorize given operations. * Throws an exception when failed. * * @param ops a vector of operations * @param sigs a set of public keys * @param get_active callback function to retrieve active authorities of a given account * @param get_owner callback function to retrieve owner authorities of a given account * @param get_custom callback function to retrieve viable custom authorities for a given account and operation * @param allow_non_immediate_owner whether to allow owner authority of non-immediately * required accounts to authorize operations * @param ignore_custom_operation_required_auths See issue #210; whether to ignore the * required_auths field of custom_operation or not * @param max_recursion maximum level of recursion when verifying, since an account * can have another account in active authorities and/or owner authorities * @param allow_committee whether to allow the special "committee account" to authorize the operations * @param active_approvals accounts that approved the operations with their active authories * @param owner_approvals accounts that approved the operations with their owner authories */ void verify_authority( const vector<operation>& ops, const flat_set<public_key_type>& sigs, const std::function<const authority*(account_id_type)>& get_active, const std::function<const authority*(account_id_type)>& get_owner, const custom_authority_lookup& get_custom, bool allow_non_immediate_owner, bool ignore_custom_operation_required_auths, uint32_t max_recursion = GRAPHENE_MAX_SIG_CHECK_DEPTH, bool allow_committee = false, const flat_set<account_id_type>& active_aprovals = flat_set<account_id_type>(), const flat_set<account_id_type>& owner_approvals = flat_set<account_id_type>() ); /** * @brief captures the result of evaluating the operations contained in the transaction * * When processing a transaction some operations generate * new object IDs and these IDs cannot be known until the * transaction is actually included into a block. When a * block is produced these new ids are captured and included * with every transaction. The index in operation_results should * correspond to the same index in operations. * * If an operation did not create any new object IDs then 0 * should be returned. */ struct processed_transaction : public precomputable_transaction { processed_transaction( const signed_transaction& trx = signed_transaction() ) : precomputable_transaction(trx){} virtual ~processed_transaction() = default; vector<operation_result> operation_results; digest_type merkle_digest()const; }; /// @} transactions group } } // graphene::protocol FC_REFLECT( graphene::protocol::transaction, (ref_block_num)(ref_block_prefix)(expiration)(operations)(extensions) ) // Note: not reflecting signees field for backward compatibility; in addition, it should not be in p2p messages FC_REFLECT_DERIVED( graphene::protocol::signed_transaction, (graphene::protocol::transaction), (signatures) ) FC_REFLECT_DERIVED( graphene::protocol::precomputable_transaction, (graphene::protocol::signed_transaction), ) FC_REFLECT_DERIVED( graphene::protocol::processed_transaction, (graphene::protocol::precomputable_transaction), (operation_results) ) GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::transaction) GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::signed_transaction) GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::precomputable_transaction) GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::processed_transaction) <|endoftext|>
<commit_before>#include "lemonbuddy.hpp" #include "bar.hpp" #include "utils/math.hpp" #include "utils/macros.hpp" #include "modules/volume.hpp" using namespace modules; VolumeModule::VolumeModule(std::string name_) : EventModule(name_) { // Load configuration values {{{ auto master_mixer = config::get<std::string>(name(), "master_mixer", "Master"); auto speaker_mixer = config::get<std::string>(name(), "speaker_mixer", ""); auto headphone_mixer = config::get<std::string>(name(), "headphone_mixer", ""); this->headphone_ctrl_numid = config::get<int>(name(), "headphone_control_numid", -1); if (!headphone_mixer.empty() && this->headphone_ctrl_numid == -1) throw ModuleError("[VolumeModule] Missing required property value for \"headphone_control_numid\"..."); else if (headphone_mixer.empty() && this->headphone_ctrl_numid != -1) throw ModuleError("[VolumeModule] Missing required property value for \"headphone_mixer\"..."); if (string::lower(speaker_mixer) == "master") throw ModuleError("[VolumeModule] The \"Master\" mixer is already processed internally. Specify another mixer or comment out the \"speaker_mixer\" parameter..."); if (string::lower(headphone_mixer) == "master") throw ModuleError("[VolumeModule] The \"Master\" mixer is already processed internally. Specify another mixer or comment out the \"headphone_mixer\" parameter..."); // }}} // Setup mixers {{{ auto create_mixer = [](std::string mixer_name) { std::unique_ptr<alsa::Mixer> mixer; try { mixer = std::make_unique<alsa::Mixer>(mixer_name); } catch (alsa::MixerError &e) { log_error("Failed to open \""+ mixer_name +"\" mixer => "+ ToStr(e.what())); mixer.reset(); } return mixer; }; this->master_mixer = create_mixer(master_mixer); if (!speaker_mixer.empty()) this->speaker_mixer = create_mixer(speaker_mixer); if (!headphone_mixer.empty()) this->headphone_mixer = create_mixer(headphone_mixer); if (!this->master_mixer && !this->speaker_mixer && !this->headphone_mixer) { this->stop(); return; } if (this->headphone_mixer && this->headphone_ctrl_numid > -1) { try { this->headphone_ctrl = std::make_unique<alsa::ControlInterface>(this->headphone_ctrl_numid); } catch (alsa::ControlInterfaceError &e) { log_error("Failed to open headphone control interface => "+ ToStr(e.what())); this->headphone_ctrl.reset(); } } // }}} // Add formats and elements {{{ this->formatter->add(FORMAT_VOLUME, TAG_LABEL_VOLUME, { TAG_RAMP_VOLUME, TAG_LABEL_VOLUME, TAG_BAR_VOLUME }); this->formatter->add(FORMAT_MUTED, TAG_LABEL_MUTED, { TAG_RAMP_VOLUME, TAG_LABEL_MUTED, TAG_BAR_VOLUME }); if (this->formatter->has(TAG_BAR_VOLUME)) this->bar_volume = drawtypes::get_config_bar(name(), get_tag_name(TAG_BAR_VOLUME)); if (this->formatter->has(TAG_RAMP_VOLUME)) this->ramp_volume = drawtypes::get_config_ramp(name(), get_tag_name(TAG_RAMP_VOLUME)); if (this->formatter->has(TAG_LABEL_VOLUME, FORMAT_VOLUME)) { this->label_volume = drawtypes::get_optional_config_label(name(), get_tag_name(TAG_LABEL_VOLUME), "%percentage%"); this->label_volume_tokenized = this->label_volume->clone(); } if (this->formatter->has(TAG_LABEL_MUTED, FORMAT_MUTED)) { this->label_muted = drawtypes::get_optional_config_label(name(), get_tag_name(TAG_LABEL_MUTED), "%percentage%"); this->label_muted_tokenized = this->label_muted->clone(); } // }}} } VolumeModule::~VolumeModule() { std::lock_guard<concurrency::SpinLock> lck(this->update_lock); this->master_mixer.reset(); this->speaker_mixer.reset(); this->headphone_mixer.reset(); this->headphone_ctrl.reset(); } bool VolumeModule::has_event() { bool has_event = false; if (this->has_changed()) has_event = true; try { if (!has_event && this->master_mixer) has_event |= this->master_mixer->wait(25); if (!has_event && this->speaker_mixer) has_event |= this->speaker_mixer->wait(25); if (!has_event && this->headphone_mixer) has_event |= this->headphone_mixer->wait(25); if (!has_event && this->headphone_ctrl) has_event |= this->headphone_ctrl->wait(25); } catch (alsa::Exception &e) { log_error(e.what()); } return has_event; } bool VolumeModule::update() { // Consume any other pending events this->has_changed = false; if (this->master_mixer) this->master_mixer->process_events(); if (this->speaker_mixer) this->speaker_mixer->process_events(); if (this->headphone_mixer) this->headphone_mixer->process_events(); if (this->headphone_ctrl) this->headphone_ctrl->wait(0); int volume = 100; bool muted = false; if (this->master_mixer) { volume *= this->master_mixer->get_volume() / 100.0f; muted |= this->master_mixer->is_muted(); } if (this->headphone_mixer && this->headphone_ctrl && this->headphone_ctrl->test_device_plugged()) { volume *= this->headphone_mixer->get_volume() / 100.0f; muted |= this->headphone_mixer->is_muted(); } else if (this->speaker_mixer) { volume *= this->speaker_mixer->get_volume() / 100.0f; muted |= this->speaker_mixer->is_muted(); } this->volume = volume; this->muted = muted; this->label_volume_tokenized->text = this->label_volume->text; this->label_volume_tokenized->replace_token("%percentage%", std::to_string(this->volume()) +"%"); this->label_muted_tokenized->text = this->label_muted->text; this->label_muted_tokenized->replace_token("%percentage%", std::to_string(this->volume()) +"%"); return true; } std::string VolumeModule::get_format() { return this->muted() == true ? FORMAT_MUTED : FORMAT_VOLUME; } std::string VolumeModule::get_output() { this->builder->cmd(Cmd::LEFT_CLICK, EVENT_TOGGLE_MUTE); if (!this->muted()) { if (this->volume() < 100) this->builder->cmd(Cmd::SCROLL_UP, EVENT_VOLUME_UP); if (this->volume() > 0) this->builder->cmd(Cmd::SCROLL_DOWN, EVENT_VOLUME_DOWN); } this->builder->node(this->Module::get_output()); return this->builder->flush(); } bool VolumeModule::build(Builder *builder, std::string tag) { if (tag == TAG_BAR_VOLUME) builder->node(this->bar_volume, volume); else if (tag == TAG_RAMP_VOLUME) builder->node(this->ramp_volume, volume); else if (tag == TAG_LABEL_VOLUME) builder->node(this->label_volume_tokenized); else if (tag == TAG_LABEL_MUTED) builder->node(this->label_muted_tokenized); else return false; return true; } bool VolumeModule::handle_command(std::string cmd) { if (cmd.length() < std::strlen(EVENT_PREFIX)) return false; if (std::strncmp(cmd.c_str(), EVENT_PREFIX, 3) != 0) return false; std::lock_guard<concurrency::SpinLock> lck(this->update_lock); alsa::Mixer *master_mixer = nullptr; alsa::Mixer *other_mixer = nullptr; if (this->master_mixer) master_mixer = this->master_mixer.get(); if (master_mixer == nullptr) return false; if (this->headphone_mixer && this->headphone_ctrl && this->headphone_ctrl->test_device_plugged()) other_mixer = this->headphone_mixer.get(); else if (this->speaker_mixer) other_mixer = this->speaker_mixer.get(); // Toggle mute state if (std::strncmp(cmd.c_str(), EVENT_TOGGLE_MUTE, std::strlen(EVENT_TOGGLE_MUTE)) == 0) { master_mixer->set_mute(this->muted()); if (other_mixer != nullptr) other_mixer->set_mute(this->muted()); // Increase volume } else if (std::strncmp(cmd.c_str(), EVENT_VOLUME_UP, std::strlen(EVENT_VOLUME_UP)) == 0) { master_mixer->set_volume(math::cap<float>(master_mixer->get_volume() + 5, 0, 100)); if (other_mixer != nullptr) other_mixer->set_volume(math::cap<float>(other_mixer->get_volume() + 5, 0, 100)); // Decrease volume } else if (std::strncmp(cmd.c_str(), EVENT_VOLUME_DOWN, std::strlen(EVENT_VOLUME_DOWN)) == 0) { master_mixer->set_volume(math::cap<float>(master_mixer->get_volume() - 5, 0, 100)); if (other_mixer != nullptr) other_mixer->set_volume(math::cap<float>(other_mixer->get_volume() - 5, 0, 100)); } else { return false; } this->has_changed = true; return true; } <commit_msg>Fix volume ramp not working<commit_after>#include <iostream> #include "lemonbuddy.hpp" #include "bar.hpp" #include "utils/math.hpp" #include "utils/macros.hpp" #include "modules/volume.hpp" using namespace modules; using namespace std; VolumeModule::VolumeModule(std::string name_) : EventModule(name_) { // Load configuration values {{{ auto master_mixer = config::get<std::string>(name(), "master_mixer", "Master"); auto speaker_mixer = config::get<std::string>(name(), "speaker_mixer", ""); auto headphone_mixer = config::get<std::string>(name(), "headphone_mixer", ""); this->headphone_ctrl_numid = config::get<int>(name(), "headphone_control_numid", -1); if (!headphone_mixer.empty() && this->headphone_ctrl_numid == -1) throw ModuleError("[VolumeModule] Missing required property value for \"headphone_control_numid\"..."); else if (headphone_mixer.empty() && this->headphone_ctrl_numid != -1) throw ModuleError("[VolumeModule] Missing required property value for \"headphone_mixer\"..."); if (string::lower(speaker_mixer) == "master") throw ModuleError("[VolumeModule] The \"Master\" mixer is already processed internally. Specify another mixer or comment out the \"speaker_mixer\" parameter..."); if (string::lower(headphone_mixer) == "master") throw ModuleError("[VolumeModule] The \"Master\" mixer is already processed internally. Specify another mixer or comment out the \"headphone_mixer\" parameter..."); // }}} // Setup mixers {{{ auto create_mixer = [](std::string mixer_name) { std::unique_ptr<alsa::Mixer> mixer; try { mixer = std::make_unique<alsa::Mixer>(mixer_name); } catch (alsa::MixerError &e) { log_error("Failed to open \""+ mixer_name +"\" mixer => "+ ToStr(e.what())); mixer.reset(); } return mixer; }; this->master_mixer = create_mixer(master_mixer); if (!speaker_mixer.empty()) this->speaker_mixer = create_mixer(speaker_mixer); if (!headphone_mixer.empty()) this->headphone_mixer = create_mixer(headphone_mixer); if (!this->master_mixer && !this->speaker_mixer && !this->headphone_mixer) { this->stop(); return; } if (this->headphone_mixer && this->headphone_ctrl_numid > -1) { try { this->headphone_ctrl = std::make_unique<alsa::ControlInterface>(this->headphone_ctrl_numid); } catch (alsa::ControlInterfaceError &e) { log_error("Failed to open headphone control interface => "+ ToStr(e.what())); this->headphone_ctrl.reset(); } } // }}} // Add formats and elements {{{ this->formatter->add(FORMAT_VOLUME, TAG_LABEL_VOLUME, { TAG_RAMP_VOLUME, TAG_LABEL_VOLUME, TAG_BAR_VOLUME }); this->formatter->add(FORMAT_MUTED, TAG_LABEL_MUTED, { TAG_RAMP_VOLUME, TAG_LABEL_MUTED, TAG_BAR_VOLUME }); if (this->formatter->has(TAG_BAR_VOLUME)) this->bar_volume = drawtypes::get_config_bar(name(), get_tag_name(TAG_BAR_VOLUME)); if (this->formatter->has(TAG_RAMP_VOLUME)) this->ramp_volume = drawtypes::get_config_ramp(name(), get_tag_name(TAG_RAMP_VOLUME)); if (this->formatter->has(TAG_LABEL_VOLUME, FORMAT_VOLUME)) { this->label_volume = drawtypes::get_optional_config_label(name(), get_tag_name(TAG_LABEL_VOLUME), "%percentage%"); this->label_volume_tokenized = this->label_volume->clone(); } if (this->formatter->has(TAG_LABEL_MUTED, FORMAT_MUTED)) { this->label_muted = drawtypes::get_optional_config_label(name(), get_tag_name(TAG_LABEL_MUTED), "%percentage%"); this->label_muted_tokenized = this->label_muted->clone(); } // }}} } VolumeModule::~VolumeModule() { std::lock_guard<concurrency::SpinLock> lck(this->update_lock); this->master_mixer.reset(); this->speaker_mixer.reset(); this->headphone_mixer.reset(); this->headphone_ctrl.reset(); } bool VolumeModule::has_event() { bool has_event = false; if (this->has_changed()) has_event = true; try { if (!has_event && this->master_mixer) has_event |= this->master_mixer->wait(25); if (!has_event && this->speaker_mixer) has_event |= this->speaker_mixer->wait(25); if (!has_event && this->headphone_mixer) has_event |= this->headphone_mixer->wait(25); if (!has_event && this->headphone_ctrl) has_event |= this->headphone_ctrl->wait(25); } catch (alsa::Exception &e) { log_error(e.what()); } return has_event; } bool VolumeModule::update() { // Consume any other pending events this->has_changed = false; if (this->master_mixer) this->master_mixer->process_events(); if (this->speaker_mixer) this->speaker_mixer->process_events(); if (this->headphone_mixer) this->headphone_mixer->process_events(); if (this->headphone_ctrl) this->headphone_ctrl->wait(0); int volume = 100; bool muted = false; if (this->master_mixer) { volume *= this->master_mixer->get_volume() / 100.0f; muted |= this->master_mixer->is_muted(); } if (this->headphone_mixer && this->headphone_ctrl && this->headphone_ctrl->test_device_plugged()) { volume *= this->headphone_mixer->get_volume() / 100.0f; muted |= this->headphone_mixer->is_muted(); } else if (this->speaker_mixer) { volume *= this->speaker_mixer->get_volume() / 100.0f; muted |= this->speaker_mixer->is_muted(); } this->volume = volume; this->muted = muted; this->label_volume_tokenized->text = this->label_volume->text; this->label_volume_tokenized->replace_token("%percentage%", std::to_string(this->volume()) +"%"); this->label_muted_tokenized->text = this->label_muted->text; this->label_muted_tokenized->replace_token("%percentage%", std::to_string(this->volume()) +"%"); return true; } std::string VolumeModule::get_format() { return this->muted() == true ? FORMAT_MUTED : FORMAT_VOLUME; } std::string VolumeModule::get_output() { this->builder->cmd(Cmd::LEFT_CLICK, EVENT_TOGGLE_MUTE); if (!this->muted()) { if (this->volume() < 100) this->builder->cmd(Cmd::SCROLL_UP, EVENT_VOLUME_UP); if (this->volume() > 0) this->builder->cmd(Cmd::SCROLL_DOWN, EVENT_VOLUME_DOWN); } this->builder->node(this->Module::get_output()); return this->builder->flush(); } bool VolumeModule::build(Builder *builder, std::string tag) { if (tag == TAG_BAR_VOLUME) builder->node(this->bar_volume, volume()); else if (tag == TAG_RAMP_VOLUME) builder->node(this->ramp_volume, volume()); else if (tag == TAG_LABEL_VOLUME) builder->node(this->label_volume_tokenized); else if (tag == TAG_LABEL_MUTED) builder->node(this->label_muted_tokenized); else return false; return true; } bool VolumeModule::handle_command(std::string cmd) { if (cmd.length() < std::strlen(EVENT_PREFIX)) return false; if (std::strncmp(cmd.c_str(), EVENT_PREFIX, 3) != 0) return false; std::lock_guard<concurrency::SpinLock> lck(this->update_lock); alsa::Mixer *master_mixer = nullptr; alsa::Mixer *other_mixer = nullptr; if (this->master_mixer) master_mixer = this->master_mixer.get(); if (master_mixer == nullptr) return false; if (this->headphone_mixer && this->headphone_ctrl && this->headphone_ctrl->test_device_plugged()) other_mixer = this->headphone_mixer.get(); else if (this->speaker_mixer) other_mixer = this->speaker_mixer.get(); // Toggle mute state if (std::strncmp(cmd.c_str(), EVENT_TOGGLE_MUTE, std::strlen(EVENT_TOGGLE_MUTE)) == 0) { master_mixer->set_mute(this->muted()); if (other_mixer != nullptr) other_mixer->set_mute(this->muted()); // Increase volume } else if (std::strncmp(cmd.c_str(), EVENT_VOLUME_UP, std::strlen(EVENT_VOLUME_UP)) == 0) { master_mixer->set_volume(math::cap<float>(master_mixer->get_volume() + 5, 0, 100)); if (other_mixer != nullptr) other_mixer->set_volume(math::cap<float>(other_mixer->get_volume() + 5, 0, 100)); // Decrease volume } else if (std::strncmp(cmd.c_str(), EVENT_VOLUME_DOWN, std::strlen(EVENT_VOLUME_DOWN)) == 0) { master_mixer->set_volume(math::cap<float>(master_mixer->get_volume() - 5, 0, 100)); if (other_mixer != nullptr) other_mixer->set_volume(math::cap<float>(other_mixer->get_volume() - 5, 0, 100)); } else { return false; } this->has_changed = true; return true; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <vector> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/foreach.hpp> #include <boost/preprocessor/stringize.hpp> #include <boost/test/unit_test.hpp> #include "json/json_spirit_reader_template.h" #include "json/json_spirit_writer_template.h" #include "json/json_spirit_utils.h" #include "main.h" #include "wallet.h" using namespace std; using namespace json_spirit; using namespace boost::algorithm; extern uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType); extern bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, int nHashType); CScript ParseScript(string s) { CScript result; static map<string, opcodetype> mapOpNames; if (mapOpNames.size() == 0) { for (int op = OP_NOP; op <= OP_NOP10; op++) { const char* name = GetOpName((opcodetype)op); if (strcmp(name, "OP_UNKNOWN") == 0) continue; string strName(name); mapOpNames[strName] = (opcodetype)op; // Convenience: OP_ADD and just ADD are both recognized: replace_first(strName, "OP_", ""); mapOpNames[strName] = (opcodetype)op; } } vector<string> words; split(words, s, is_any_of(" \t\n"), token_compress_on); BOOST_FOREACH(string w, words) { if (all(w, is_digit()) || (starts_with(w, "-") && all(string(w.begin()+1, w.end()), is_digit()))) { // Number int64 n = atoi64(w); result << n; } else if (starts_with(w, "0x") && IsHex(string(w.begin()+2, w.end()))) { // Raw hex data, inserted NOT pushed onto stack: std::vector<unsigned char> raw = ParseHex(string(w.begin()+2, w.end())); result.insert(result.end(), raw.begin(), raw.end()); } else if (w.size() >= 2 && starts_with(w, "'") && ends_with(w, "'")) { // Single-quoted string, pushed as data. NOTE: this is poor-man's // parsing, spaces/tabs/newlines in single-quoted strings won't work. std::vector<unsigned char> value(w.begin()+1, w.end()-1); result << value; } else if (mapOpNames.count(w)) { // opcode, e.g. OP_ADD or OP_1: result << mapOpNames[w]; } else { BOOST_ERROR("Parse error: " << s); return CScript(); } } return result; } Array read_json(const std::string& filename) { namespace fs = boost::filesystem; fs::path testFile = fs::current_path() / "test" / "data" / filename; #ifdef TEST_DATA_DIR if (!fs::exists(testFile)) { testFile = fs::path(BOOST_PP_STRINGIZE(TEST_DATA_DIR)) / filename; } #endif ifstream ifs(testFile.string().c_str(), ifstream::in); Value v; if (!read_stream(ifs, v)) { if (ifs.fail()) BOOST_ERROR("Cound not find/open " << filename); else BOOST_ERROR("JSON syntax error in " << filename); return Array(); } if (v.type() != array_type) { BOOST_ERROR(filename << " does not contain a json array"); return Array(); } return v.get_array(); } BOOST_AUTO_TEST_SUITE(script_tests) BOOST_AUTO_TEST_CASE(script_valid) { // Read tests from test/data/script_valid.json // Format is an array of arrays // Inner arrays are [ "scriptSig", "scriptPubKey" ] // ... where scriptSig and scriptPubKey are stringified // scripts. Array tests = read_json("script_valid.json"); BOOST_FOREACH(Value& tv, tests) { Array test = tv.get_array(); string strTest = write_string(tv, false); if (test.size() < 2) // Allow size > 2; extra stuff ignored (useful for comments) { BOOST_ERROR("Bad test: " << strTest); continue; } string scriptSigString = test[0].get_str(); CScript scriptSig = ParseScript(scriptSigString); string scriptPubKeyString = test[1].get_str(); CScript scriptPubKey = ParseScript(scriptPubKeyString); CTransaction tx; BOOST_CHECK_MESSAGE(VerifyScript(scriptSig, scriptPubKey, tx, 0, true, SIGHASH_NONE), strTest); } } BOOST_AUTO_TEST_CASE(script_invalid) { // Scripts that should evaluate as invalid Array tests = read_json("script_invalid.json"); BOOST_FOREACH(Value& tv, tests) { Array test = tv.get_array(); string strTest = write_string(tv, false); if (test.size() < 2) // Allow size > 2; extra stuff ignored (useful for comments) { BOOST_ERROR("Bad test: " << strTest); continue; } string scriptSigString = test[0].get_str(); CScript scriptSig = ParseScript(scriptSigString); string scriptPubKeyString = test[1].get_str(); CScript scriptPubKey = ParseScript(scriptPubKeyString); CTransaction tx; BOOST_CHECK_MESSAGE(!VerifyScript(scriptSig, scriptPubKey, tx, 0, true, SIGHASH_NONE), strTest); } } BOOST_AUTO_TEST_CASE(script_PushData) { // Check that PUSHDATA1, PUSHDATA2, and PUSHDATA4 create the same value on // the stack as the 1-75 opcodes do. static const unsigned char direct[] = { 1, 0x5a }; static const unsigned char pushdata1[] = { OP_PUSHDATA1, 1, 0x5a }; static const unsigned char pushdata2[] = { OP_PUSHDATA2, 1, 0, 0x5a }; static const unsigned char pushdata4[] = { OP_PUSHDATA4, 1, 0, 0, 0, 0x5a }; vector<vector<unsigned char> > directStack; BOOST_CHECK(EvalScript(directStack, CScript(&direct[0], &direct[sizeof(direct)]), CTransaction(), 0, 0)); vector<vector<unsigned char> > pushdata1Stack; BOOST_CHECK(EvalScript(pushdata1Stack, CScript(&pushdata1[0], &pushdata1[sizeof(pushdata1)]), CTransaction(), 0, 0)); BOOST_CHECK(pushdata1Stack == directStack); vector<vector<unsigned char> > pushdata2Stack; BOOST_CHECK(EvalScript(pushdata2Stack, CScript(&pushdata2[0], &pushdata2[sizeof(pushdata2)]), CTransaction(), 0, 0)); BOOST_CHECK(pushdata2Stack == directStack); vector<vector<unsigned char> > pushdata4Stack; BOOST_CHECK(EvalScript(pushdata4Stack, CScript(&pushdata4[0], &pushdata4[sizeof(pushdata4)]), CTransaction(), 0, 0)); BOOST_CHECK(pushdata4Stack == directStack); } CScript sign_multisig(CScript scriptPubKey, std::vector<CKey> keys, CTransaction transaction) { uint256 hash = SignatureHash(scriptPubKey, transaction, 0, SIGHASH_ALL); CScript result; // // NOTE: CHECKMULTISIG has an unfortunate bug; it requires // one extra item on the stack, before the signatures. // Putting OP_0 on the stack is the workaround; // fixing the bug would mean splitting the blockchain (old // clients would not accept new CHECKMULTISIG transactions, // and vice-versa) // result << OP_0; BOOST_FOREACH(CKey key, keys) { vector<unsigned char> vchSig; BOOST_CHECK(key.Sign(hash, vchSig)); vchSig.push_back((unsigned char)SIGHASH_ALL); result << vchSig; } return result; } CScript sign_multisig(CScript scriptPubKey, CKey key, CTransaction transaction) { std::vector<CKey> keys; keys.push_back(key); return sign_multisig(scriptPubKey, keys, transaction); } BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12) { CKey key1, key2, key3; key1.MakeNewKey(true); key2.MakeNewKey(false); key3.MakeNewKey(true); CScript scriptPubKey12; scriptPubKey12 << OP_1 << key1.GetPubKey() << key2.GetPubKey() << OP_2 << OP_CHECKMULTISIG; CTransaction txFrom12; txFrom12.vout.resize(1); txFrom12.vout[0].scriptPubKey = scriptPubKey12; CTransaction txTo12; txTo12.vin.resize(1); txTo12.vout.resize(1); txTo12.vin[0].prevout.n = 0; txTo12.vin[0].prevout.hash = txFrom12.GetHash(); txTo12.vout[0].nValue = 1; CScript goodsig1 = sign_multisig(scriptPubKey12, key1, txTo12); BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey12, txTo12, 0, true, 0)); txTo12.vout[0].nValue = 2; BOOST_CHECK(!VerifyScript(goodsig1, scriptPubKey12, txTo12, 0, true, 0)); CScript goodsig2 = sign_multisig(scriptPubKey12, key2, txTo12); BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey12, txTo12, 0, true, 0)); CScript badsig1 = sign_multisig(scriptPubKey12, key3, txTo12); BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, txTo12, 0, true, 0)); } BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23) { CKey key1, key2, key3, key4; key1.MakeNewKey(true); key2.MakeNewKey(false); key3.MakeNewKey(true); key4.MakeNewKey(false); CScript scriptPubKey23; scriptPubKey23 << OP_2 << key1.GetPubKey() << key2.GetPubKey() << key3.GetPubKey() << OP_3 << OP_CHECKMULTISIG; CTransaction txFrom23; txFrom23.vout.resize(1); txFrom23.vout[0].scriptPubKey = scriptPubKey23; CTransaction txTo23; txTo23.vin.resize(1); txTo23.vout.resize(1); txTo23.vin[0].prevout.n = 0; txTo23.vin[0].prevout.hash = txFrom23.GetHash(); txTo23.vout[0].nValue = 1; std::vector<CKey> keys; keys.push_back(key1); keys.push_back(key2); CScript goodsig1 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey23, txTo23, 0, true, 0)); keys.clear(); keys.push_back(key1); keys.push_back(key3); CScript goodsig2 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey23, txTo23, 0, true, 0)); keys.clear(); keys.push_back(key2); keys.push_back(key3); CScript goodsig3 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(VerifyScript(goodsig3, scriptPubKey23, txTo23, 0, true, 0)); keys.clear(); keys.push_back(key2); keys.push_back(key2); // Can't re-use sig CScript badsig1 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey23, txTo23, 0, true, 0)); keys.clear(); keys.push_back(key2); keys.push_back(key1); // sigs must be in correct order CScript badsig2 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig2, scriptPubKey23, txTo23, 0, true, 0)); keys.clear(); keys.push_back(key3); keys.push_back(key2); // sigs must be in correct order CScript badsig3 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig3, scriptPubKey23, txTo23, 0, true, 0)); keys.clear(); keys.push_back(key4); keys.push_back(key2); // sigs must match pubkeys CScript badsig4 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig4, scriptPubKey23, txTo23, 0, true, 0)); keys.clear(); keys.push_back(key1); keys.push_back(key4); // sigs must match pubkeys CScript badsig5 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig5, scriptPubKey23, txTo23, 0, true, 0)); keys.clear(); // Must have signatures CScript badsig6 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, txTo23, 0, true, 0)); } BOOST_AUTO_TEST_CASE(script_combineSigs) { // Test the CombineSignatures function CBasicKeyStore keystore; vector<CKey> keys; for (int i = 0; i < 3; i++) { CKey key; key.MakeNewKey(i%2 == 1); keys.push_back(key); keystore.AddKey(key); } CTransaction txFrom; txFrom.vout.resize(1); txFrom.vout[0].scriptPubKey.SetDestination(keys[0].GetPubKey().GetID()); CScript& scriptPubKey = txFrom.vout[0].scriptPubKey; CTransaction txTo; txTo.vin.resize(1); txTo.vout.resize(1); txTo.vin[0].prevout.n = 0; txTo.vin[0].prevout.hash = txFrom.GetHash(); CScript& scriptSig = txTo.vin[0].scriptSig; txTo.vout[0].nValue = 1; CScript empty; CScript combined = CombineSignatures(scriptPubKey, txTo, 0, empty, empty); BOOST_CHECK(combined.empty()); // Single signature case: SignSignature(keystore, txFrom, txTo, 0); // changes scriptSig combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty); BOOST_CHECK(combined == scriptSig); combined = CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig); BOOST_CHECK(combined == scriptSig); CScript scriptSigCopy = scriptSig; // Signing again will give a different, valid signature: SignSignature(keystore, txFrom, txTo, 0); combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig); BOOST_CHECK(combined == scriptSigCopy || combined == scriptSig); // P2SH, single-signature case: CScript pkSingle; pkSingle << keys[0].GetPubKey() << OP_CHECKSIG; keystore.AddCScript(pkSingle); scriptPubKey.SetDestination(pkSingle.GetID()); SignSignature(keystore, txFrom, txTo, 0); combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty); BOOST_CHECK(combined == scriptSig); combined = CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig); BOOST_CHECK(combined == scriptSig); scriptSigCopy = scriptSig; SignSignature(keystore, txFrom, txTo, 0); combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig); BOOST_CHECK(combined == scriptSigCopy || combined == scriptSig); // dummy scriptSigCopy with placeholder, should always choose non-placeholder: scriptSigCopy = CScript() << OP_0 << static_cast<vector<unsigned char> >(pkSingle); combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig); BOOST_CHECK(combined == scriptSig); combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, scriptSigCopy); BOOST_CHECK(combined == scriptSig); // Hardest case: Multisig 2-of-3 scriptPubKey.SetMultisig(2, keys); keystore.AddCScript(scriptPubKey); SignSignature(keystore, txFrom, txTo, 0); combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty); BOOST_CHECK(combined == scriptSig); combined = CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig); BOOST_CHECK(combined == scriptSig); // A couple of partially-signed versions: vector<unsigned char> sig1; uint256 hash1 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_ALL); BOOST_CHECK(keys[0].Sign(hash1, sig1)); sig1.push_back(SIGHASH_ALL); vector<unsigned char> sig2; uint256 hash2 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_NONE); BOOST_CHECK(keys[1].Sign(hash2, sig2)); sig2.push_back(SIGHASH_NONE); vector<unsigned char> sig3; uint256 hash3 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_SINGLE); BOOST_CHECK(keys[2].Sign(hash3, sig3)); sig3.push_back(SIGHASH_SINGLE); // Not fussy about order (or even existence) of placeholders or signatures: CScript partial1a = CScript() << OP_0 << sig1 << OP_0; CScript partial1b = CScript() << OP_0 << OP_0 << sig1; CScript partial2a = CScript() << OP_0 << sig2; CScript partial2b = CScript() << sig2 << OP_0; CScript partial3a = CScript() << sig3; CScript partial3b = CScript() << OP_0 << OP_0 << sig3; CScript partial3c = CScript() << OP_0 << sig3 << OP_0; CScript complete12 = CScript() << OP_0 << sig1 << sig2; CScript complete13 = CScript() << OP_0 << sig1 << sig3; CScript complete23 = CScript() << OP_0 << sig2 << sig3; combined = CombineSignatures(scriptPubKey, txTo, 0, partial1a, partial1b); BOOST_CHECK(combined == partial1a); combined = CombineSignatures(scriptPubKey, txTo, 0, partial1a, partial2a); BOOST_CHECK(combined == complete12); combined = CombineSignatures(scriptPubKey, txTo, 0, partial2a, partial1a); BOOST_CHECK(combined == complete12); combined = CombineSignatures(scriptPubKey, txTo, 0, partial1b, partial2b); BOOST_CHECK(combined == complete12); combined = CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial1b); BOOST_CHECK(combined == complete13); combined = CombineSignatures(scriptPubKey, txTo, 0, partial2a, partial3a); BOOST_CHECK(combined == complete23); combined = CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial2b); BOOST_CHECK(combined == complete23); combined = CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial3a); BOOST_CHECK(combined == partial3c); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Delete script_tests.cpp<commit_after><|endoftext|>
<commit_before>// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #include "src/version.h" // These macros define the version number for the current version. // NOTE these macros are used by some of the tool scripts and the build // system so their names cannot be changed without changing the scripts. #define MAJOR_VERSION 3 #define MINOR_VERSION 28 #define BUILD_NUMBER 39 #define PATCH_LEVEL 0 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) #define IS_CANDIDATE_VERSION 1 // Define SONAME to have the build system put a specific SONAME into the // shared library instead the generic SONAME generated from the V8 version // number. This define is mainly used by the build system script. #define SONAME "" #if IS_CANDIDATE_VERSION #define CANDIDATE_STRING " (candidate)" #else #define CANDIDATE_STRING "" #endif #define SX(x) #x #define S(x) SX(x) #if PATCH_LEVEL > 0 #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \ S(PATCH_LEVEL) CANDIDATE_STRING #else #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \ CANDIDATE_STRING #endif namespace v8 { namespace internal { int Version::major_ = MAJOR_VERSION; int Version::minor_ = MINOR_VERSION; int Version::build_ = BUILD_NUMBER; int Version::patch_ = PATCH_LEVEL; bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0); const char* Version::soname_ = SONAME; const char* Version::version_string_ = VERSION_STRING; // Calculate the V8 version string. void Version::GetString(Vector<char> str) { const char* candidate = IsCandidate() ? " (candidate)" : ""; #ifdef USE_SIMULATOR const char* is_simulator = " SIMULATOR"; #else const char* is_simulator = ""; #endif // USE_SIMULATOR if (GetPatch() > 0) { SNPrintF(str, "%d.%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate, is_simulator); } else { SNPrintF(str, "%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), candidate, is_simulator); } } // Calculate the SONAME for the V8 shared library. void Version::GetSONAME(Vector<char> str) { if (soname_ == NULL || *soname_ == '\0') { // Generate generic SONAME if no specific SONAME is defined. const char* candidate = IsCandidate() ? "-candidate" : ""; if (GetPatch() > 0) { SNPrintF(str, "libv8-%d.%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate); } else { SNPrintF(str, "libv8-%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), candidate); } } else { // Use specific SONAME. SNPrintF(str, "%s", soname_); } } } } // namespace v8::internal <commit_msg>[Auto-roll] Bump up version to 3.28.40.0<commit_after>// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #include "src/version.h" // These macros define the version number for the current version. // NOTE these macros are used by some of the tool scripts and the build // system so their names cannot be changed without changing the scripts. #define MAJOR_VERSION 3 #define MINOR_VERSION 28 #define BUILD_NUMBER 40 #define PATCH_LEVEL 0 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) #define IS_CANDIDATE_VERSION 1 // Define SONAME to have the build system put a specific SONAME into the // shared library instead the generic SONAME generated from the V8 version // number. This define is mainly used by the build system script. #define SONAME "" #if IS_CANDIDATE_VERSION #define CANDIDATE_STRING " (candidate)" #else #define CANDIDATE_STRING "" #endif #define SX(x) #x #define S(x) SX(x) #if PATCH_LEVEL > 0 #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \ S(PATCH_LEVEL) CANDIDATE_STRING #else #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \ CANDIDATE_STRING #endif namespace v8 { namespace internal { int Version::major_ = MAJOR_VERSION; int Version::minor_ = MINOR_VERSION; int Version::build_ = BUILD_NUMBER; int Version::patch_ = PATCH_LEVEL; bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0); const char* Version::soname_ = SONAME; const char* Version::version_string_ = VERSION_STRING; // Calculate the V8 version string. void Version::GetString(Vector<char> str) { const char* candidate = IsCandidate() ? " (candidate)" : ""; #ifdef USE_SIMULATOR const char* is_simulator = " SIMULATOR"; #else const char* is_simulator = ""; #endif // USE_SIMULATOR if (GetPatch() > 0) { SNPrintF(str, "%d.%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate, is_simulator); } else { SNPrintF(str, "%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), candidate, is_simulator); } } // Calculate the SONAME for the V8 shared library. void Version::GetSONAME(Vector<char> str) { if (soname_ == NULL || *soname_ == '\0') { // Generate generic SONAME if no specific SONAME is defined. const char* candidate = IsCandidate() ? "-candidate" : ""; if (GetPatch() > 0) { SNPrintF(str, "libv8-%d.%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate); } else { SNPrintF(str, "libv8-%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), candidate); } } else { // Use specific SONAME. SNPrintF(str, "%s", soname_); } } } } // namespace v8::internal <|endoftext|>
<commit_before>#include "internal.hpp" #include "macros.hpp" #include "message.hpp" namespace CaDiCaL { // Vivification is a special case of asymmetric tautology elimination. It // strengthens and removes irredundant clauses proven redundant through unit // propagation. The original algorithm is due to a paper by Piette, Hamadi // published at ECAI'08. We have an inprocessing version, e.g., it does not // necessarily run-to-completion. It does no conflict analysis and uses a // new heuristic for selecting clauses to vivify. /*------------------------------------------------------------------------*/ struct ClauseScore { Clause * clause; long score; ClauseScore (Clause * c) : clause (c), score (0) { } }; struct less_clause_score { bool operator () (const ClauseScore & a, const ClauseScore & b) const { return a.score < b.score; } }; struct less_negated_noccs2 { Internal * internal; less_negated_noccs2 (Internal * i) : internal (i) { } bool operator () (int a, int b) { long u = internal->noccs2 (-a), v = internal->noccs2 (-b); if (u < v) return true; if (u > v) return false; int i = abs (a), j = abs (b); if (i < j) return true; if (i > j) return false; return a < b; } }; /*------------------------------------------------------------------------*/ void Internal::vivify () { assert (opts.vivify); SWITCH_AND_START (search, simplify, vivify); assert (!vivifying); vivifying = true; stats.vivifications++; if (level) backtrack (); vector<ClauseScore> schedule; const const_clause_iterator end = clauses.end (); const_clause_iterator i; // After an arithmetic increasing number of calls to 'vivify' we // reschedule all clauses, instead of only those not tried before. Then // this limit is increased by one. The argument is that we should focus on // clauses with many occurrences of their negated literals (also long // clauses), but in the limit eventually still should vivify all clauses. // bool reschedule_all = !lim.vivifywaitreset; if (reschedule_all) lim.vivifywaitreset = ++inc.vivifywaitreset; else lim.vivifywaitreset--; // In the first round check whether there are still clauses left, which // are scheduled to but have not been vivified yet. In the second round // if no such clauses are found in the first round. This is also // performed if rescheduling is forced because 'reschedule_all' is true. // for (int round = 0; schedule.empty () && round <= 1; round++) { for (i = clauses.begin (); i != end; i++) { Clause * c = *i; if (c->garbage) continue; if (c->redundant) continue; if (c->size == 2) continue; // see also (NO-BINARY) below if (!reschedule_all && !round && !c->vivify) continue; schedule.push_back (c); c->vivify = true; } } shrink_vector (schedule); // Count the number of occurrences of literals in all irredundant clauses, // particularly the irredundant binary clauses, responsible for most of // the propagation usually. // init_noccs2 (); for (i = clauses.begin (); i != end; i++) { Clause * c = *i; if (c->garbage) continue; if (c->redundant) continue; const const_literal_iterator eoc = c->end (); const_literal_iterator j; for (j = c->begin (); j != eoc; j++) noccs2 (*j)++; } // Then update the score of the candidate clauses by adding up the number // of occurrences of the negation of its literals. // const vector<ClauseScore>::const_iterator eos = schedule.end (); vector<ClauseScore>::iterator k; for (k = schedule.begin (); k != eos; k++) { ClauseScore & cs = *k; const const_literal_iterator eoc = cs.clause->end (); const_literal_iterator j; long score = 0; for (j = cs.clause->begin (); j != eoc; j++) score += noccs2 (-*j); cs.score = score; } // Then sort candidates, with best clause (many negative occurrences) last. // stable_sort (schedule.begin (), schedule.end (), less_clause_score ()); long scheduled = schedule.size (); VRB ("vivification", stats.vivifications, "scheduled irredundant %ld clauses to be vivified %.0f%%", scheduled, percent (scheduled, stats.irredundant)); // We need to make sure to propagate only over irredundant clauses. // flush_redundant_watches (); size_t old_propagated = propagated; long checked = 0, subsumed = 0, strengthened = 0, units = 0; vector<int> sorted; // Limit the number of propagations during vivification as in 'probe'. // long delta = opts.vivifyreleff * stats.propagations.search; if (delta < opts.vivifymineff) delta = opts.vivifymineff; if (delta > opts.vivifymaxeff) delta = opts.vivifymaxeff; long limit = stats.propagations.vivify + delta; while (!unsat && !schedule.empty () && stats.propagations.vivify < limit) { // Next candidate clause to vivify. // Clause * c = schedule.back ().clause; schedule.pop_back (); assert (c->vivify); c->vivify = false; assert (!c->garbage); assert (!c->redundant); assert (c->size > 2); assert (!level); // First check whether it is already satisfied. // const const_literal_iterator eoc = c->end (); const_literal_iterator j; bool satisfied = false; sorted.clear (); for (j = c->begin (); !satisfied && j != eoc; j++) { const int lit = *j, tmp = val (lit); if (tmp > 0) satisfied = true; else if (!tmp) sorted.push_back (lit); } if (satisfied) { mark_garbage (c); continue; } // The actual vivification checking is performed here, by assuming the // negation of each of the remaining literals of the clause in turn and // propagating it. If a conflict occurs or another literal in the // clause becomes assigned during propagation, we can stop. // LOG (c, "vivification checking"); checked++; // Sort the literals of the candidate with respect to the largest number // of negative occurrences. The idea is that more negative occurrences // lead to more propagations and thus potentially higher earlier effect. // sort (sorted.begin (), sorted.end (), less_negated_noccs2 (this)); // Make sure to ignore this clause during propagation. This is not that // easy for binary clauses, e.g., ignoring binary clauses, without // changing 'propagate' and actually we also do not want to remove // binary clauses which are subsumed. Those are hyper binary // resolvents and should be kept as learned clauses instead (TODO). // c->ignore = true; // see also (NO-BINARY) above bool redundant = false; // determined to be redundant / subsumed int remove = 0; // at least literal 'remove' can be removed while (!redundant && !remove && !sorted.empty ()) { const int lit = sorted.back (), tmp = val (lit); sorted.pop_back (); if (tmp > 0) { LOG ("redundant since literal %d already true", lit); redundant = true; } else if (tmp < 0) { LOG ("removing at least literal %d which is already false", lit); remove = lit; } else { assume_decision (-lit); if (propagate ()) continue; LOG ("redundant since propagation produced conflict"); redundant = true; conflict = 0; } } if (redundant) { REDUNDANT: subsumed++; LOG (c, "redundant asymmetric tautology"); mark_garbage (c); } else if (remove) { strengthened++; assert (level); assert (clause.empty ()); #ifndef NDEBUG bool found = false; #endif // There might be other literals implied to false (or even root level // falsified). Those should be removed in addition to 'remove'. // for (j = c->begin (); j != eoc; j++) { const int other = *j, tmp = val (other); Var & v = var (other); if (tmp > 0) { LOG ("redundant since literal %d already true", other); clause.clear (); goto REDUNDANT; } if (tmp < 0 && !v.level) continue; if (tmp < 0 && v.level && v.reason) { assert (v.level); assert (v.reason); LOG ("flushing literal %d", other); mark_removed (other); #ifndef NDEBUG if (other == remove) found = true; #endif } else clause.push_back (other); } assert (found); assert (!clause.empty ()); backtrack (); if (clause.size () == 1) { const int unit = clause[0]; LOG (c, "vivification shrunken to unit %d", unit); assert (!val (unit)); assign_unit (unit); units++; bool ok = propagate (); if (!ok) learn_empty_clause (); } else { #ifdef LOGGING Clause * d = #endif new_clause_as (c); LOG (c, "before vivification"); LOG (d, "after vivification"); } clause.clear (); mark_garbage (c); } if (level) backtrack (); c->ignore = false; } if (!unsat) { erase_vector (sorted); reset_noccs2 (); erase_vector (schedule); disconnect_watches (); connect_watches (); if (old_propagated < propagated) { propagated = old_propagated; if (!propagate ()) { LOG ("propagating vivified units leads to conflict"); learn_empty_clause (); } } } VRB ("vivification", stats.vivifications, "checked %ld clauses %.02f%% out of scheduled", checked, percent (checked, scheduled)); VRB ("vivification", stats.vivifications, "found %ld units %.02f%% out of checked", units, percent (units, checked)); VRB ("vivification", stats.vivifications, "subsumed %ld clauses %.02f%% out of checked", subsumed, percent (subsumed, checked)); VRB ("vivification", stats.vivifications, "strengthened %ld clauses %.02f%% out of checked", strengthened, percent (strengthened, checked)); stats.vivifychecks += checked; stats.vivifysubs += subsumed; stats.vivifystrs += strengthened; stats.vivifyunits += units; stats.subsumed += subsumed; stats.strengthened += strengthened; assert (vivifying); vivifying = false; report ('v'); STOP_AND_SWITCH (vivify, simplify, search); } }; <commit_msg>commented on issue<commit_after>#include "internal.hpp" #include "macros.hpp" #include "message.hpp" namespace CaDiCaL { // Vivification is a special case of asymmetric tautology elimination. It // strengthens and removes irredundant clauses proven redundant through unit // propagation. The original algorithm is due to a paper by Piette, Hamadi // published at ECAI'08. We have an inprocessing version, e.g., it does not // necessarily run-to-completion. It does no conflict analysis and uses a // new heuristic for selecting clauses to vivify. /*------------------------------------------------------------------------*/ struct ClauseScore { Clause * clause; long score; ClauseScore (Clause * c) : clause (c), score (0) { } }; struct less_clause_score { bool operator () (const ClauseScore & a, const ClauseScore & b) const { return a.score < b.score; } }; struct less_negated_noccs2 { Internal * internal; less_negated_noccs2 (Internal * i) : internal (i) { } bool operator () (int a, int b) { long u = internal->noccs2 (-a), v = internal->noccs2 (-b); if (u < v) return true; if (u > v) return false; int i = abs (a), j = abs (b); if (i < j) return true; if (i > j) return false; return a < b; } }; /*------------------------------------------------------------------------*/ void Internal::vivify () { assert (opts.vivify); SWITCH_AND_START (search, simplify, vivify); assert (!vivifying); vivifying = true; stats.vivifications++; if (level) backtrack (); vector<ClauseScore> schedule; const const_clause_iterator end = clauses.end (); const_clause_iterator i; // After an arithmetic increasing number of calls to 'vivify' we // reschedule all clauses, instead of only those not tried before. Then // this limit is increased by one. The argument is that we should focus on // clauses with many occurrences of their negated literals (also long // clauses), but in the limit eventually still should vivify all clauses. // bool reschedule_all = !lim.vivifywaitreset; if (reschedule_all) lim.vivifywaitreset = ++inc.vivifywaitreset; else lim.vivifywaitreset--; // In the first round check whether there are still clauses left, which // are scheduled to but have not been vivified yet. In the second round // if no such clauses are found in the first round. This is also // performed if rescheduling is forced because 'reschedule_all' is true. // for (int round = 0; schedule.empty () && round <= 1; round++) { for (i = clauses.begin (); i != end; i++) { Clause * c = *i; if (c->garbage) continue; if (c->redundant) continue; if (c->size == 2) continue; // see also (NO-BINARY) below if (!reschedule_all && !round && !c->vivify) continue; schedule.push_back (c); c->vivify = true; } } shrink_vector (schedule); // Count the number of occurrences of literals in all irredundant clauses, // particularly the irredundant binary clauses, responsible for most of // the propagation usually. // init_noccs2 (); for (i = clauses.begin (); i != end; i++) { Clause * c = *i; if (c->garbage) continue; if (c->redundant) continue; const const_literal_iterator eoc = c->end (); const_literal_iterator j; for (j = c->begin (); j != eoc; j++) noccs2 (*j)++; } // Then update the score of the candidate clauses by adding up the number // of occurrences of the negation of its literals. // const vector<ClauseScore>::const_iterator eos = schedule.end (); vector<ClauseScore>::iterator k; for (k = schedule.begin (); k != eos; k++) { ClauseScore & cs = *k; const const_literal_iterator eoc = cs.clause->end (); const_literal_iterator j; long score = 0; for (j = cs.clause->begin (); j != eoc; j++) score += noccs2 (-*j); cs.score = score; } // Then sort candidates, with best clause (many negative occurrences) last. // stable_sort (schedule.begin (), schedule.end (), less_clause_score ()); long scheduled = schedule.size (); VRB ("vivification", stats.vivifications, "scheduled irredundant %ld clauses to be vivified %.0f%%", scheduled, percent (scheduled, stats.irredundant)); // We need to make sure to propagate only over irredundant clauses. // flush_redundant_watches (); size_t old_propagated = propagated; // see [RE-PROPAGATE] below. long checked = 0, subsumed = 0, strengthened = 0, units = 0; vector<int> sorted; // Limit the number of propagations during vivification as in 'probe'. // long delta = opts.vivifyreleff * stats.propagations.search; if (delta < opts.vivifymineff) delta = opts.vivifymineff; if (delta > opts.vivifymaxeff) delta = opts.vivifymaxeff; long limit = stats.propagations.vivify + delta; while (!unsat && !schedule.empty () && stats.propagations.vivify < limit) { // Next candidate clause to vivify. // Clause * c = schedule.back ().clause; schedule.pop_back (); assert (c->vivify); c->vivify = false; assert (!c->garbage); assert (!c->redundant); assert (c->size > 2); assert (!level); // First check whether it is already satisfied. // const const_literal_iterator eoc = c->end (); const_literal_iterator j; bool satisfied = false; sorted.clear (); for (j = c->begin (); !satisfied && j != eoc; j++) { const int lit = *j, tmp = val (lit); if (tmp > 0) satisfied = true; else if (!tmp) sorted.push_back (lit); } if (satisfied) { mark_garbage (c); continue; } // The actual vivification checking is performed here, by assuming the // negation of each of the remaining literals of the clause in turn and // propagating it. If a conflict occurs or another literal in the // clause becomes assigned during propagation, we can stop. // LOG (c, "vivification checking"); checked++; // Sort the literals of the candidate with respect to the largest number // of negative occurrences. The idea is that more negative occurrences // lead to more propagations and thus potentially higher earlier effect. // sort (sorted.begin (), sorted.end (), less_negated_noccs2 (this)); // Make sure to ignore this clause during propagation. This is not that // easy for binary clauses, e.g., ignoring binary clauses, without // changing 'propagate' and actually we also do not want to remove // binary clauses which are subsumed. Those are hyper binary // resolvents and should be kept as learned clauses instead (TODO). // c->ignore = true; // see also (NO-BINARY) above bool redundant = false; // determined to be redundant / subsumed int remove = 0; // at least literal 'remove' can be removed while (!redundant && !remove && !sorted.empty ()) { const int lit = sorted.back (), tmp = val (lit); sorted.pop_back (); if (tmp > 0) { LOG ("redundant since literal %d already true", lit); redundant = true; } else if (tmp < 0) { LOG ("removing at least literal %d which is already false", lit); remove = lit; } else { assume_decision (-lit); if (propagate ()) continue; LOG ("redundant since propagation produced conflict"); redundant = true; conflict = 0; } } if (redundant) { REDUNDANT: subsumed++; LOG (c, "redundant asymmetric tautology"); mark_garbage (c); } else if (remove) { strengthened++; assert (level); assert (clause.empty ()); #ifndef NDEBUG bool found = false; #endif // There might be other literals implied to false (or even root level // falsified). Those should be removed in addition to 'remove'. // for (j = c->begin (); j != eoc; j++) { const int other = *j, tmp = val (other); Var & v = var (other); if (tmp > 0) { LOG ("redundant since literal %d already true", other); clause.clear (); goto REDUNDANT; } if (tmp < 0 && !v.level) continue; if (tmp < 0 && v.level && v.reason) { assert (v.level); assert (v.reason); LOG ("flushing literal %d", other); mark_removed (other); #ifndef NDEBUG if (other == remove) found = true; #endif } else clause.push_back (other); } assert (found); assert (!clause.empty ()); backtrack (); if (clause.size () == 1) { const int unit = clause[0]; LOG (c, "vivification shrunken to unit %d", unit); assert (!val (unit)); assign_unit (unit); units++; bool ok = propagate (); if (!ok) learn_empty_clause (); } else { #ifdef LOGGING Clause * d = #endif new_clause_as (c); LOG (c, "before vivification"); LOG (d, "after vivification"); } clause.clear (); mark_garbage (c); } if (level) backtrack (); c->ignore = false; } if (!unsat) { erase_vector (sorted); reset_noccs2 (); erase_vector (schedule); disconnect_watches (); connect_watches (); // [RE-PROPAGATE] Since redundant clause were disconnected during // propagating vivified units above, we have propagate all those fixed // literals again after connecting the redundant clauses back. // Otherwise, the invariants for watching and blocking literals break. // if (old_propagated < propagated) { propagated = old_propagated; if (!propagate ()) { LOG ("propagating vivified units leads to conflict"); learn_empty_clause (); } } } VRB ("vivification", stats.vivifications, "checked %ld clauses %.02f%% out of scheduled", checked, percent (checked, scheduled)); VRB ("vivification", stats.vivifications, "found %ld units %.02f%% out of checked", units, percent (units, checked)); VRB ("vivification", stats.vivifications, "subsumed %ld clauses %.02f%% out of checked", subsumed, percent (subsumed, checked)); VRB ("vivification", stats.vivifications, "strengthened %ld clauses %.02f%% out of checked", strengthened, percent (strengthened, checked)); stats.vivifychecks += checked; stats.vivifysubs += subsumed; stats.vivifystrs += strengthened; stats.vivifyunits += units; stats.subsumed += subsumed; stats.strengthened += strengthened; assert (vivifying); vivifying = false; report ('v'); STOP_AND_SWITCH (vivify, simplify, search); } }; <|endoftext|>
<commit_before>#include "internal.hpp" #include "macros.hpp" #include "message.hpp" namespace CaDiCaL { // Vivification is a special case of asymmetric tautology elimination. It // strengthens and removes irredundant clauses proven redundant through unit // propagation. The original algorithm is due to a paper by Piette, Hamadi // published at ECAI'08. We have an inprocessing version, e.g., it does not // necessarily run-to-completion. It does no conflict analysis and uses a // new heuristic for selecting clauses to vivify. /*------------------------------------------------------------------------*/ struct ClauseScore { Clause * clause; long score; ClauseScore (Clause * c) : clause (c), score (0) { } }; struct less_clause_score { bool operator () (const ClauseScore & a, const ClauseScore & b) const { return a.score < b.score; } }; // Check whether negated literal occurs less often. // struct less_negated_noccs2 { Internal * internal; less_negated_noccs2 (Internal * i) : internal (i) { } bool operator () (int a, int b) { long u = internal->noccs2 (-a), v = internal->noccs2 (-b); if (u < v) return true; if (u > v) return false; int i = abs (a), j = abs (b); if (i < j) return true; if (i > j) return false; return a < b; } }; /*------------------------------------------------------------------------*/ void Internal::vivify () { assert (opts.vivify); SWITCH_AND_START (search, simplify, vivify); assert (!vivifying); vivifying = true; stats.vivifications++; if (level) backtrack (); // Refill the schedule every time. Unchecked clauses are 'saved' by // setting their 'vivify' bit, such that they can be tried next time. // vector<ClauseScore> schedule; const const_clause_iterator end = clauses.end (); const_clause_iterator i; // After an arithmetic increasing number of calls to 'vivify' we // reschedule all clauses, instead of only those not tried before. Then // this limit is increased by one. The argument is that we should focus on // clauses with many occurrences of their negated literals (also long // clauses), but in the limit eventually still should vivify all clauses. // bool reschedule_all = !lim.vivifywaitreset; if (reschedule_all) lim.vivifywaitreset = ++inc.vivifywaitreset; else lim.vivifywaitreset--; // In the first round check whether there are still clauses left, which // are scheduled to but have not been vivified yet. In the second round // if no such clauses are found in the first round. This is also // performed if rescheduling is forced because 'reschedule_all' is true. // for (int round = 0; schedule.empty () && round <= 1; round++) { for (i = clauses.begin (); i != end; i++) { Clause * c = *i; if (c->garbage) continue; if (c->redundant) continue; if (c->size == 2) continue; // see also (NO-BINARY) below if (!reschedule_all && !round && !c->vivify) continue; schedule.push_back (c); c->vivify = true; } } shrink_vector (schedule); // Count the number of occurrences of literals in all irredundant clauses, // particularly the irredundant binary clauses, responsible for most of // the propagation usually. // init_noccs2 (); for (i = clauses.begin (); i != end; i++) { Clause * c = *i; if (c->garbage) continue; if (c->redundant) continue; const const_literal_iterator eoc = c->end (); const_literal_iterator j; for (j = c->begin (); j != eoc; j++) noccs2 (*j)++; } // Then update the score of the candidate clauses by adding up the number // of occurrences of the negation of its literals. // const vector<ClauseScore>::const_iterator eos = schedule.end (); vector<ClauseScore>::iterator k; for (k = schedule.begin (); k != eos; k++) { ClauseScore & cs = *k; const const_literal_iterator eoc = cs.clause->end (); const_literal_iterator j; long score = 0; for (j = cs.clause->begin (); j != eoc; j++) score += noccs2 (-*j); cs.score = score; } // Now sort candidates, with best clause (many negative occurrences) last. // stable_sort (schedule.begin (), schedule.end (), less_clause_score ()); long scheduled = schedule.size (); VRB ("vivification", stats.vivifications, "scheduled %ld clauses to be vivified %.0f%%", scheduled, percent (scheduled, stats.irredundant)); // We need to make sure to propagate only over irredundant clauses. // flush_redundant_watches (); size_t old_propagated = propagated; // see [RE-PROPAGATE] below. // Counters, for what happened. // long checked = 0, subsumed = 0, strengthened = 0, units = 0; // Temporarily save and sort the candidate clause literals here. // vector<int> sorted; // Limit the number of propagations during vivification as in 'probe'. // long delta = opts.vivifyreleff * stats.propagations.search; if (delta < opts.vivifymineff) delta = opts.vivifymineff; if (delta > opts.vivifymaxeff) delta = opts.vivifymaxeff; long limit = stats.propagations.vivify + delta; while (!unsat && !schedule.empty () && stats.propagations.vivify < limit) { // Next candidate clause to vivify. // Clause * c = schedule.back ().clause; schedule.pop_back (); assert (c->vivify); c->vivify = false; assert (!c->garbage); assert (!c->redundant); assert (c->size > 2); // see assert (!level); // First check whether it is already satisfied. // const const_literal_iterator eoc = c->end (); const_literal_iterator j; bool satisfied = false; sorted.clear (); for (j = c->begin (); !satisfied && j != eoc; j++) { const int lit = *j, tmp = val (lit); if (tmp > 0) satisfied = true; else if (!tmp) sorted.push_back (lit); } if (satisfied) { mark_garbage (c); continue; } // The actual vivification checking is performed here, by assuming the // negation of each of the remaining literals of the clause in turn and // propagating it. If a conflict occurs or another literal in the // clause becomes assigned during propagation, we can stop. // LOG (c, "vivification checking"); checked++; // Sort the literals of the candidate with respect to the largest number // of negative occurrences. The idea is that more negative occurrences // lead to more propagations and thus potentially higher earlier effect. // sort (sorted.begin (), sorted.end (), less_negated_noccs2 (this)); // Make sure to ignore this clause during propagation. This is not that // easy for binary clauses (NO-BINARY), e.g., ignoring binary clauses, // without changing 'propagate' and actually we also do not want to // remove binary clauses which are subsumed. Those are hyper binary // resolvents and should be kept as learned clauses instead unless they // are transitive in the binary implication graph (TODO). // c->ignore = true; // see also (NO-BINARY) above bool redundant = false; // determined to be redundant / subsumed int remove = 0; // at least literal 'remove' can be removed while (!redundant && !remove && !sorted.empty ()) { const int lit = sorted.back (), tmp = val (lit); sorted.pop_back (); if (tmp > 0) { LOG ("redundant since literal %d already true", lit); redundant = true; } else if (tmp < 0) { LOG ("removing at least literal %d which is already false", lit); remove = lit; } else { assume_decision (-lit); if (propagate ()) continue; LOG ("redundant since propagation produced conflict"); redundant = true; conflict = 0; } } if (redundant) { REDUNDANT: subsumed++; LOG (c, "redundant asymmetric tautology"); mark_garbage (c); } else if (remove) { strengthened++; assert (level); assert (clause.empty ()); #ifndef NDEBUG bool found = false; #endif // There might be other literals implied to false (or even root level // falsified). Those should be removed in addition to 'remove'. // for (j = c->begin (); j != eoc; j++) { const int other = *j, tmp = val (other); Var & v = var (other); if (tmp > 0) { LOG ("redundant since literal %d already true", other); clause.clear (); goto REDUNDANT; } if (tmp < 0 && !v.level) continue; if (tmp < 0 && v.level && v.reason) { assert (v.level); assert (v.reason); LOG ("flushing literal %d", other); mark_removed (other); #ifndef NDEBUG if (other == remove) found = true; #endif } else clause.push_back (other); } assert (found); assert (!clause.empty ()); backtrack (); if (clause.size () == 1) { const int unit = clause[0]; LOG (c, "vivification shrunken to unit %d", unit); assert (!val (unit)); assign_unit (unit); units++; bool ok = propagate (); if (!ok) learn_empty_clause (); } else { #ifdef LOGGING Clause * d = #endif new_clause_as (c); LOG (c, "before vivification"); LOG (d, "after vivification"); } clause.clear (); mark_garbage (c); } if (level) backtrack (); c->ignore = false; } if (!unsat) { erase_vector (sorted); reset_noccs2 (); erase_vector (schedule); disconnect_watches (); connect_watches (); // [RE-PROPAGATE] Since redundant clause were disconnected during // propagating vivified units above, we have propagate all those fixed // literals again after connecting the redundant clauses back. // Otherwise, the invariants for watching and blocking literals break. // if (old_propagated < propagated) { propagated = old_propagated; if (!propagate ()) { LOG ("propagating vivified units leads to conflict"); learn_empty_clause (); } } } VRB ("vivification", stats.vivifications, "checked %ld clauses %.02f%% out of scheduled", checked, percent (checked, scheduled)); if (units) VRB ("vivification", stats.vivifications, "found %ld units %.02f%% out of checked", units, percent (units, checked)); VRB ("vivification", stats.vivifications, "subsumed %ld clauses %.02f%% out of checked", subsumed, percent (subsumed, checked)); VRB ("vivification", stats.vivifications, "strengthened %ld clauses %.02f%% out of checked", strengthened, percent (strengthened, checked)); stats.vivifychecks += checked; stats.vivifysubs += subsumed; stats.vivifystrs += strengthened; stats.vivifyunits += units; stats.subsumed += subsumed; stats.strengthened += strengthened; assert (vivifying); vivifying = false; report ('v'); STOP_AND_SWITCH (vivify, simplify, search); } }; <commit_msg>fixed score<commit_after>#include "internal.hpp" #include "macros.hpp" #include "message.hpp" namespace CaDiCaL { // Vivification is a special case of asymmetric tautology elimination. It // strengthens and removes irredundant clauses proven redundant through unit // propagation. The original algorithm is due to a paper by Piette, Hamadi // published at ECAI'08. We have an inprocessing version, e.g., it does not // necessarily run-to-completion. It does no conflict analysis and uses a // new heuristic for selecting clauses to vivify. /*------------------------------------------------------------------------*/ struct ClauseScore { Clause * clause; double score; ClauseScore (Clause * c) : clause (c), score (0) { } }; struct less_clause_score { bool operator () (const ClauseScore & a, const ClauseScore & b) const { return a.score < b.score; } }; // Check whether negated literal occurs less often. // struct less_negated_noccs2 { Internal * internal; less_negated_noccs2 (Internal * i) : internal (i) { } bool operator () (int a, int b) { long u = internal->noccs2 (-a), v = internal->noccs2 (-b); if (u < v) return true; if (u > v) return false; int i = abs (a), j = abs (b); if (i < j) return true; if (i > j) return false; return a < b; } }; /*------------------------------------------------------------------------*/ void Internal::vivify () { assert (opts.vivify); SWITCH_AND_START (search, simplify, vivify); assert (!vivifying); vivifying = true; stats.vivifications++; if (level) backtrack (); // Refill the schedule every time. Unchecked clauses are 'saved' by // setting their 'vivify' bit, such that they can be tried next time. // vector<ClauseScore> schedule; const const_clause_iterator end = clauses.end (); const_clause_iterator i; // After an arithmetic increasing number of calls to 'vivify' we // reschedule all clauses, instead of only those not tried before. Then // this limit is increased by one. The argument is that we should focus on // clauses with many occurrences of their negated literals (also long // clauses), but in the limit eventually still should vivify all clauses. // bool reschedule_all = !lim.vivifywaitreset; if (reschedule_all) lim.vivifywaitreset = ++inc.vivifywaitreset; else lim.vivifywaitreset--; // In the first round check whether there are still clauses left, which // are scheduled to but have not been vivified yet. In the second round // if no such clauses are found in the first round. This is also // performed if rescheduling is forced because 'reschedule_all' is true. // for (int round = 0; schedule.empty () && round <= 1; round++) { for (i = clauses.begin (); i != end; i++) { Clause * c = *i; if (c->garbage) continue; if (c->redundant) continue; if (c->size == 2) continue; // see also (NO-BINARY) below if (!reschedule_all && !round && !c->vivify) continue; schedule.push_back (c); c->vivify = true; } } shrink_vector (schedule); // Count the number of occurrences of literals in all irredundant clauses, // particularly the irredundant binary clauses, responsible for most of // the propagation usually. // init_noccs2 (); for (i = clauses.begin (); i != end; i++) { Clause * c = *i; if (c->garbage) continue; if (c->redundant) continue; // Compute score as 'pow (2, -c->size)' without 'math.h' (it actually // could be faster even, since second argument is always an integer). // This is the same score the Jeroslow-Wang heuristic would give. // double base = 0.5, score = 0.25; for (int n = c->size - 2; n; n >>= 1) { if (n & 1) score *= base; base *= base; } const const_literal_iterator eoc = c->end (); const_literal_iterator j; for (j = c->begin (); j != eoc; j++) noccs2 (*j) += score; } // Then update the score of the candidate clauses by adding up the number // of occurrences of the negation of its literals. // const vector<ClauseScore>::const_iterator eos = schedule.end (); vector<ClauseScore>::iterator k; for (k = schedule.begin (); k != eos; k++) { ClauseScore & cs = *k; const const_literal_iterator eoc = cs.clause->end (); const_literal_iterator j; long score = 0; for (j = cs.clause->begin (); j != eoc; j++) score += noccs2 (-*j); cs.score = score; } // Now sort candidates, with best clause (many negative occurrences) last. // stable_sort (schedule.begin (), schedule.end (), less_clause_score ()); long scheduled = schedule.size (); VRB ("vivification", stats.vivifications, "scheduled %ld clauses to be vivified %.0f%%", scheduled, percent (scheduled, stats.irredundant)); // We need to make sure to propagate only over irredundant clauses. // flush_redundant_watches (); size_t old_propagated = propagated; // see [RE-PROPAGATE] below. // Counters, for what happened. // long checked = 0, subsumed = 0, strengthened = 0, units = 0; // Temporarily save and sort the candidate clause literals here. // vector<int> sorted; // Limit the number of propagations during vivification as in 'probe'. // long delta = opts.vivifyreleff * stats.propagations.search; if (delta < opts.vivifymineff) delta = opts.vivifymineff; if (delta > opts.vivifymaxeff) delta = opts.vivifymaxeff; long limit = stats.propagations.vivify + delta; while (!unsat && !schedule.empty () && stats.propagations.vivify < limit) { // Next candidate clause to vivify. // Clause * c = schedule.back ().clause; schedule.pop_back (); assert (c->vivify); c->vivify = false; assert (!c->garbage); assert (!c->redundant); assert (c->size > 2); // see assert (!level); // First check whether it is already satisfied. // const const_literal_iterator eoc = c->end (); const_literal_iterator j; bool satisfied = false; sorted.clear (); for (j = c->begin (); !satisfied && j != eoc; j++) { const int lit = *j, tmp = val (lit); if (tmp > 0) satisfied = true; else if (!tmp) sorted.push_back (lit); } if (satisfied) { mark_garbage (c); continue; } // The actual vivification checking is performed here, by assuming the // negation of each of the remaining literals of the clause in turn and // propagating it. If a conflict occurs or another literal in the // clause becomes assigned during propagation, we can stop. // LOG (c, "vivification checking"); checked++; // Sort the literals of the candidate with respect to the largest number // of negative occurrences. The idea is that more negative occurrences // lead to more propagations and thus potentially higher earlier effect. // sort (sorted.begin (), sorted.end (), less_negated_noccs2 (this)); // Make sure to ignore this clause during propagation. This is not that // easy for binary clauses (NO-BINARY), e.g., ignoring binary clauses, // without changing 'propagate' and actually we also do not want to // remove binary clauses which are subsumed. Those are hyper binary // resolvents and should be kept as learned clauses instead unless they // are transitive in the binary implication graph (TODO). // c->ignore = true; // see also (NO-BINARY) above bool redundant = false; // determined to be redundant / subsumed int remove = 0; // at least literal 'remove' can be removed while (!redundant && !remove && !sorted.empty ()) { const int lit = sorted.back (), tmp = val (lit); sorted.pop_back (); if (tmp > 0) { LOG ("redundant since literal %d already true", lit); redundant = true; } else if (tmp < 0) { LOG ("removing at least literal %d which is already false", lit); remove = lit; } else { assume_decision (-lit); if (propagate ()) continue; LOG ("redundant since propagation produced conflict"); redundant = true; conflict = 0; } } if (redundant) { REDUNDANT: subsumed++; LOG (c, "redundant asymmetric tautology"); mark_garbage (c); } else if (remove) { strengthened++; assert (level); assert (clause.empty ()); #ifndef NDEBUG bool found = false; #endif // There might be other literals implied to false (or even root level // falsified). Those should be removed in addition to 'remove'. // for (j = c->begin (); j != eoc; j++) { const int other = *j, tmp = val (other); Var & v = var (other); if (tmp > 0) { LOG ("redundant since literal %d already true", other); clause.clear (); goto REDUNDANT; } if (tmp < 0 && !v.level) continue; if (tmp < 0 && v.level && v.reason) { assert (v.level); assert (v.reason); LOG ("flushing literal %d", other); mark_removed (other); #ifndef NDEBUG if (other == remove) found = true; #endif } else clause.push_back (other); } assert (found); assert (!clause.empty ()); backtrack (); if (clause.size () == 1) { const int unit = clause[0]; LOG (c, "vivification shrunken to unit %d", unit); assert (!val (unit)); assign_unit (unit); units++; bool ok = propagate (); if (!ok) learn_empty_clause (); } else { #ifdef LOGGING Clause * d = #endif new_clause_as (c); LOG (c, "before vivification"); LOG (d, "after vivification"); } clause.clear (); mark_garbage (c); } if (level) backtrack (); c->ignore = false; } if (!unsat) { erase_vector (sorted); reset_noccs2 (); erase_vector (schedule); disconnect_watches (); connect_watches (); // [RE-PROPAGATE] Since redundant clause were disconnected during // propagating vivified units above, we have propagate all those fixed // literals again after connecting the redundant clauses back. // Otherwise, the invariants for watching and blocking literals break. // if (old_propagated < propagated) { propagated = old_propagated; if (!propagate ()) { LOG ("propagating vivified units leads to conflict"); learn_empty_clause (); } } } VRB ("vivification", stats.vivifications, "checked %ld clauses %.02f%% out of scheduled", checked, percent (checked, scheduled)); if (units) VRB ("vivification", stats.vivifications, "found %ld units %.02f%% out of checked", units, percent (units, checked)); VRB ("vivification", stats.vivifications, "subsumed %ld clauses %.02f%% out of checked", subsumed, percent (subsumed, checked)); VRB ("vivification", stats.vivifications, "strengthened %ld clauses %.02f%% out of checked", strengthened, percent (strengthened, checked)); stats.vivifychecks += checked; stats.vivifysubs += subsumed; stats.vivifystrs += strengthened; stats.vivifyunits += units; stats.subsumed += subsumed; stats.strengthened += strengthened; assert (vivifying); vivifying = false; report ('v'); STOP_AND_SWITCH (vivify, simplify, search); } }; <|endoftext|>
<commit_before>#include "internal.hpp" #include "macros.hpp" #include "message.hpp" namespace CaDiCaL { // Vivification is a special case of asymmetric tautology elimination. It // strengthens and removes irredundant clauses proven redundant through unit // propagation. The original algorithm is due to a paper by Piette, Hamadi // published at ECAI'08. We have an inprocessing version, e.g., it does not // necessarily run-to-completion. It does no conflict analysis and uses a // new heuristic for selecting clauses to vivify. /*------------------------------------------------------------------------*/ struct ClauseScore { Clause * clause; double score; ClauseScore (Clause * c) : clause (c), score (0) { } }; struct less_clause_score { bool operator () (const ClauseScore & a, const ClauseScore & b) const { return a.score < b.score; } }; // Check whether negated literal occurs less often. // struct less_negated_noccs2 { Internal * internal; less_negated_noccs2 (Internal * i) : internal (i) { } bool operator () (int a, int b) { long u = internal->noccs2 (-a), v = internal->noccs2 (-b); if (u < v) return true; if (u > v) return false; int i = abs (a), j = abs (b); if (i < j) return true; if (i > j) return false; return a < b; } }; /*------------------------------------------------------------------------*/ void Internal::vivify () { assert (opts.vivify); SWITCH_AND_START (search, simplify, vivify); assert (!vivifying); vivifying = true; stats.vivifications++; if (level) backtrack (); // Refill the schedule every time. Unchecked clauses are 'saved' by // setting their 'vivify' bit, such that they can be tried next time. // vector<ClauseScore> schedule; const const_clause_iterator end = clauses.end (); const_clause_iterator i; // After an arithmetic increasing number of calls to 'vivify' we // reschedule all clauses, instead of only those not tried before. Then // this limit is increased by one. The argument is that we should focus on // clauses with many occurrences of their negated literals (also long // clauses), but in the limit eventually still should vivify all clauses. // bool reschedule_all = !lim.vivify_wait_reschedule; if (reschedule_all) { VRB ("vivify", stats.vivifications, "forced to reschedule all clauses"); lim.vivify_wait_reschedule = ++inc.vivify_wait_reschedule; } else lim.vivify_wait_reschedule--; // In the first round check whether there are still clauses left, which // are scheduled to but have not been vivified yet. In the second round // if no such clauses are found in the first round. This is also // performed if rescheduling is forced because 'reschedule_all' is true. // for (int round = 0; schedule.empty () && round <= 1; round++) { for (i = clauses.begin (); i != end; i++) { Clause * c = *i; if (c->garbage) continue; if (c->redundant) continue; if (c->size == 2) continue; // see also [NO-BINARY] below if (!reschedule_all && !round && !c->vivify) continue; schedule.push_back (c); c->vivify = true; } } shrink_vector (schedule); // Count the number of occurrences of literals in all irredundant clauses, // particularly the irredundant binary clauses, responsible for most of // the propagation usually. // init_noccs2 (); for (i = clauses.begin (); i != end; i++) { Clause * c = *i; if (c->garbage) continue; if (c->redundant) continue; // Compute score as 'pow (2, -c->size)' without 'math.h' (it actually // could be faster even, since second argument is always an integer). // This is the same score the Jeroslow-Wang heuristic would give. // double base = 0.5, score = 0.25; for (int n = c->size - 2; n; n >>= 1) { if (n & 1) score *= base; base *= base; } const const_literal_iterator eoc = c->end (); const_literal_iterator j; for (j = c->begin (); j != eoc; j++) noccs2 (*j) += score; } // Then update the score of the candidate clauses by adding up the number // of occurrences of the negation of its literals. // const vector<ClauseScore>::const_iterator eos = schedule.end (); vector<ClauseScore>::iterator k; for (k = schedule.begin (); k != eos; k++) { ClauseScore & cs = *k; const const_literal_iterator eoc = cs.clause->end (); const_literal_iterator j; long score = 0; for (j = cs.clause->begin (); j != eoc; j++) score += noccs2 (-*j); cs.score = score; } // Now sort candidates, with best clause (many negative occurrences) last. // stable_sort (schedule.begin (), schedule.end (), less_clause_score ()); long scheduled = schedule.size (); VRB ("vivify", stats.vivifications, "scheduled %ld clauses to be vivified %.0f%%", scheduled, percent (scheduled, stats.irredundant)); // We need to make sure to propagate only over irredundant clauses. // flush_redundant_watches (); size_t old_propagated = propagated; // see [RE-PROPAGATE] below. // Counters, for what happened. // long checked = 0, subsumed = 0, strengthened = 0, units = 0; // Temporarily save and sort the candidate clause literals here. // vector<int> sorted; // Limit the number of propagations during vivification as in 'probe'. // long delta = opts.vivifyreleff * stats.propagations.search; if (delta < opts.vivifymineff) delta = opts.vivifymineff; if (delta > opts.vivifymaxeff) delta = opts.vivifymaxeff; long limit = stats.propagations.vivify + delta; while (!unsat && !schedule.empty () && stats.propagations.vivify < limit) { // Next candidate clause to vivify. // Clause * c = schedule.back ().clause; schedule.pop_back (); assert (c->vivify); c->vivify = false; assert (!c->garbage); assert (!c->redundant); assert (c->size > 2); // see [NO-BINARY] above assert (!level); // First check whether it is already satisfied. // const const_literal_iterator eoc = c->end (); const_literal_iterator j; bool satisfied = false; sorted.clear (); for (j = c->begin (); !satisfied && j != eoc; j++) { const int lit = *j, tmp = val (lit); if (tmp > 0) satisfied = true; else if (!tmp) sorted.push_back (lit); } if (satisfied) { mark_garbage (c); continue; } // The actual vivification checking is performed here, by assuming the // negation of each of the remaining literals of the clause in turn and // propagating it. If a conflict occurs or another literal in the // clause becomes assigned during propagation, we can stop. // LOG (c, "vivification checking"); checked++; // Sort the literals of the candidate with respect to the largest number // of negative occurrences. The idea is that more negative occurrences // lead to more propagations and thus potentially higher earlier effect. // sort (sorted.begin (), sorted.end (), less_negated_noccs2 (this)); // Make sure to ignore this clause during propagation. This is not that // easy for binary clauses [NO-BINARY], e.g., ignoring binary clauses, // without changing 'propagate' and actually we also do not want to // remove binary clauses which are subsumed. Those are hyper binary // resolvents and should be kept as learned clauses instead unless they // are transitive in the binary implication graph (TODO). // c->ignore = true; // see also [NO-BINARY] above bool redundant = false; // determined to be redundant / subsumed int remove = 0; // at least literal 'remove' can be removed while (!redundant && !remove && !sorted.empty ()) { const int lit = sorted.back (), tmp = val (lit); sorted.pop_back (); if (tmp > 0) { LOG ("redundant since literal %d already true", lit); redundant = true; } else if (tmp < 0) { LOG ("removing at least literal %d which is already false", lit); remove = lit; } else { assume_decision (-lit); if (propagate ()) continue; LOG ("redundant since propagation produced conflict"); redundant = true; conflict = 0; } } if (redundant) { REDUNDANT: subsumed++; LOG (c, "redundant asymmetric tautology"); mark_garbage (c); } else if (remove) { assert (level); assert (clause.empty ()); #ifndef NDEBUG bool found = false; #endif // There might be other literals implied to false (or even root level // falsified). Those should be removed in addition to 'remove'. It // might further be possible that a latter to be assumed literal is // already forced to true in which case the clause is actually // redundant (we solved this by bad style 'goto' programming). // for (j = c->begin (); j != eoc; j++) { const int other = *j, tmp = val (other); Var & v = var (other); if (tmp > 0) { LOG ("redundant since literal %d already true", other); clause.clear (); goto REDUNDANT; } if (tmp < 0 && !v.level) continue; if (tmp < 0 && v.level && v.reason) { assert (v.level); assert (v.reason); LOG ("flushing literal %d", other); mark_removed (other); #ifndef NDEBUG if (other == remove) found = true; #endif } else clause.push_back (other); } // Assume remaining literals and propagate them to see whether this // clause is actually redundant and does not have to be strengthened. if (!sorted.empty ()) { do { const int lit = sorted.back (), tmp = val (lit); sorted.pop_back (); if (tmp < 0) continue; assert (!tmp); assume_decision (-lit); } while (!sorted.empty ()); if (!propagate ()) { LOG ("redundant since propagating rest produces conflict"); clause.clear (); conflict = 0; goto REDUNDANT; } LOG ("propagating remaining negated literals without conflict"); } strengthened++; // only now because of 'goto REDUNDANT' above assert (found); assert (!clause.empty ()); backtrack (); if (clause.size () == 1) { const int unit = clause[0]; LOG (c, "vivification shrunken to unit %d", unit); assert (!val (unit)); assign_unit (unit); units++; bool ok = propagate (); if (!ok) learn_empty_clause (); } else { #ifdef LOGGING Clause * d = #endif new_clause_as (c); LOG (c, "before vivification"); LOG (d, "after vivification"); } clause.clear (); mark_garbage (c); } if (level) backtrack (); c->ignore = false; } if (!unsat) { erase_vector (sorted); reset_noccs2 (); erase_vector (schedule); disconnect_watches (); connect_watches (); // [RE-PROPAGATE] Since redundant clause were disconnected during // propagating vivified units above, we have propagate all those fixed // literals again after connecting the redundant clauses back. // Otherwise, the invariants for watching and blocking literals break. // if (old_propagated < propagated) { propagated = old_propagated; if (!propagate ()) { LOG ("propagating vivified units leads to conflict"); learn_empty_clause (); } } } VRB ("vivify", stats.vivifications, "checked %ld clauses %.02f%% out of scheduled", checked, percent (checked, scheduled)); if (units) VRB ("vivify", stats.vivifications, "found %ld units %.02f%% out of checked", units, percent (units, checked)); VRB ("vivify", stats.vivifications, "subsumed %ld clauses %.02f%% out of checked", subsumed, percent (subsumed, checked)); VRB ("vivify", stats.vivifications, "strengthened %ld clauses %.02f%% out of checked", strengthened, percent (strengthened, checked)); stats.vivifychecks += checked; stats.vivifysubs += subsumed; stats.vivifystrs += strengthened; stats.vivifyunits += units; stats.subsumed += subsumed; stats.strengthened += strengthened; assert (vivifying); vivifying = false; report ('v'); STOP_AND_SWITCH (vivify, simplify, search); } }; <commit_msg>try redundant again<commit_after>#include "internal.hpp" #include "macros.hpp" #include "message.hpp" namespace CaDiCaL { // Vivification is a special case of asymmetric tautology elimination. It // strengthens and removes irredundant clauses proven redundant through unit // propagation. The original algorithm is due to a paper by Piette, Hamadi // published at ECAI'08. We have an inprocessing version, e.g., it does not // necessarily run-to-completion. It does no conflict analysis and uses a // new heuristic for selecting clauses to vivify. /*------------------------------------------------------------------------*/ struct ClauseScore { Clause * clause; double score; ClauseScore (Clause * c) : clause (c), score (0) { } }; struct less_clause_score { bool operator () (const ClauseScore & a, const ClauseScore & b) const { return a.score < b.score; } }; // Check whether negated literal occurs less often. // struct less_negated_noccs2 { Internal * internal; less_negated_noccs2 (Internal * i) : internal (i) { } bool operator () (int a, int b) { long u = internal->noccs2 (-a), v = internal->noccs2 (-b); if (u < v) return true; if (u > v) return false; int i = abs (a), j = abs (b); if (i < j) return true; if (i > j) return false; return a < b; } }; /*------------------------------------------------------------------------*/ void Internal::vivify () { assert (opts.vivify); SWITCH_AND_START (search, simplify, vivify); assert (!vivifying); vivifying = true; stats.vivifications++; if (level) backtrack (); // Refill the schedule every time. Unchecked clauses are 'saved' by // setting their 'vivify' bit, such that they can be tried next time. // vector<ClauseScore> schedule; const const_clause_iterator end = clauses.end (); const_clause_iterator i; // After an arithmetic increasing number of calls to 'vivify' we // reschedule all clauses, instead of only those not tried before. Then // this limit is increased by one. The argument is that we should focus on // clauses with many occurrences of their negated literals (also long // clauses), but in the limit eventually still should vivify all clauses. // bool reschedule_all = !lim.vivify_wait_reschedule; if (reschedule_all) { VRB ("vivify", stats.vivifications, "forced to reschedule all clauses"); lim.vivify_wait_reschedule = ++inc.vivify_wait_reschedule; } else lim.vivify_wait_reschedule--; // In the first round check whether there are still clauses left, which // are scheduled to but have not been vivified yet. In the second round // if no such clauses are found in the first round. This is also // performed if rescheduling is forced because 'reschedule_all' is true. // for (int round = 0; schedule.empty () && round <= 1; round++) { for (i = clauses.begin (); i != end; i++) { Clause * c = *i; if (c->garbage) continue; if (c->redundant) continue; if (c->size == 2) continue; // see also [NO-BINARY] below if (!reschedule_all && !round && !c->vivify) continue; schedule.push_back (c); c->vivify = true; } } shrink_vector (schedule); // Count the number of occurrences of literals in all irredundant clauses, // particularly the irredundant binary clauses, responsible for most of // the propagation usually. // init_noccs2 (); for (i = clauses.begin (); i != end; i++) { Clause * c = *i; if (c->garbage) continue; if (c->redundant) continue; // Compute score as 'pow (2, -c->size)' without 'math.h' (it actually // could be faster even, since second argument is always an integer). // This is the same score the Jeroslow-Wang heuristic would give. // double base = 0.5, score = 0.25; for (int n = c->size - 2; n; n >>= 1) { if (n & 1) score *= base; base *= base; } const const_literal_iterator eoc = c->end (); const_literal_iterator j; for (j = c->begin (); j != eoc; j++) noccs2 (*j) += score; } // Then update the score of the candidate clauses by adding up the number // of occurrences of the negation of its literals. // const vector<ClauseScore>::const_iterator eos = schedule.end (); vector<ClauseScore>::iterator k; for (k = schedule.begin (); k != eos; k++) { ClauseScore & cs = *k; const const_literal_iterator eoc = cs.clause->end (); const_literal_iterator j; long score = 0; for (j = cs.clause->begin (); j != eoc; j++) score += noccs2 (-*j); cs.score = score; } // Now sort candidates, with best clause (many negative occurrences) last. // stable_sort (schedule.begin (), schedule.end (), less_clause_score ()); long scheduled = schedule.size (); VRB ("vivify", stats.vivifications, "scheduled %ld clauses to be vivified %.0f%%", scheduled, percent (scheduled, stats.irredundant)); // We need to make sure to propagate only over irredundant clauses. // flush_redundant_watches (); size_t old_propagated = propagated; // see [RE-PROPAGATE] below. // Counters, for what happened. // long checked = 0, subsumed = 0, strengthened = 0, units = 0; // Temporarily save and sort the candidate clause literals here. // vector<int> sorted; // Limit the number of propagations during vivification as in 'probe'. // long delta = opts.vivifyreleff * stats.propagations.search; if (delta < opts.vivifymineff) delta = opts.vivifymineff; if (delta > opts.vivifymaxeff) delta = opts.vivifymaxeff; long limit = stats.propagations.vivify + delta; while (!unsat && !schedule.empty () && stats.propagations.vivify < limit) { // Next candidate clause to vivify. // Clause * c = schedule.back ().clause; schedule.pop_back (); assert (c->vivify); c->vivify = false; assert (!c->garbage); assert (!c->redundant); assert (c->size > 2); // see [NO-BINARY] above assert (!level); // First check whether it is already satisfied. // const const_literal_iterator eoc = c->end (); const_literal_iterator j; bool satisfied = false; sorted.clear (); for (j = c->begin (); !satisfied && j != eoc; j++) { const int lit = *j, tmp = val (lit); if (tmp > 0) satisfied = true; else if (!tmp) sorted.push_back (lit); } if (satisfied) { mark_garbage (c); continue; } // The actual vivification checking is performed here, by assuming the // negation of each of the remaining literals of the clause in turn and // propagating it. If a conflict occurs or another literal in the // clause becomes assigned during propagation, we can stop. // LOG (c, "vivification checking"); checked++; // Sort the literals of the candidate with respect to the largest number // of negative occurrences. The idea is that more negative occurrences // lead to more propagations and thus potentially higher earlier effect. // sort (sorted.begin (), sorted.end (), less_negated_noccs2 (this)); // Make sure to ignore this clause during propagation. This is not that // easy for binary clauses [NO-BINARY], e.g., ignoring binary clauses, // without changing 'propagate' and actually we also do not want to // remove binary clauses which are subsumed. Those are hyper binary // resolvents and should be kept as learned clauses instead unless they // are transitive in the binary implication graph (TODO). // c->ignore = true; // see also [NO-BINARY] above bool redundant = false; // determined to be redundant / subsumed int remove = 0; // at least literal 'remove' can be removed while (!redundant && !remove && !sorted.empty ()) { const int lit = sorted.back (), tmp = val (lit); sorted.pop_back (); if (tmp > 0) { LOG ("redundant since literal %d already true", lit); redundant = true; } else if (tmp < 0) { LOG ("removing at least literal %d which is already false", lit); remove = lit; } else { assume_decision (-lit); if (propagate ()) continue; LOG ("redundant since propagation produced conflict"); redundant = true; conflict = 0; } } if (redundant) { REDUNDANT: subsumed++; LOG (c, "redundant asymmetric tautology"); mark_garbage (c); } else if (remove) { assert (level); assert (clause.empty ()); #ifndef NDEBUG bool found = false; #endif // There might be other literals implied to false (or even root level // falsified). Those should be removed in addition to 'remove'. It // might further be possible that a latter to be assumed literal is // already forced to true in which case the clause is actually // redundant (we solved this by bad style 'goto' programming). // for (j = c->begin (); j != eoc; j++) { const int other = *j, tmp = val (other); Var & v = var (other); if (tmp > 0) { LOG ("redundant since literal %d already true", other); clause.clear (); goto REDUNDANT; } if (tmp < 0 && !v.level) continue; if (tmp < 0 && v.level && v.reason) { assert (v.level); assert (v.reason); LOG ("flushing literal %d", other); mark_removed (other); #ifndef NDEBUG if (other == remove) found = true; #endif } else clause.push_back (other); } assert (found); // Assume remaining literals and propagate them to see whether this // clause is actually redundant and does not have to be strengthened. if (!sorted.empty ()) { do { const int lit = sorted.back (), tmp = val (lit); sorted.pop_back (); if (tmp < 0) continue; if (tmp > 0) { LOG ("redundant since literal %d already true", lit); redundant = true; } else { assume_decision (-lit); redundant = !propagate (); } } while (!redundant && !sorted.empty ()); if (redundant) { if (conflict) conflict = 0; LOG ("redundant since propagating rest produces conflict"); clause.clear (); goto REDUNDANT; } LOG ("propagating remaining negated literals without conflict"); } strengthened++; // only now because of 'goto REDUNDANT' above (twice) assert (!clause.empty ()); backtrack (); if (clause.size () == 1) { const int unit = clause[0]; LOG (c, "vivification shrunken to unit %d", unit); assert (!val (unit)); assign_unit (unit); units++; bool ok = propagate (); if (!ok) learn_empty_clause (); } else { #ifdef LOGGING Clause * d = #endif new_clause_as (c); LOG (c, "before vivification"); LOG (d, "after vivification"); } clause.clear (); mark_garbage (c); } if (level) backtrack (); c->ignore = false; } if (!unsat) { erase_vector (sorted); reset_noccs2 (); erase_vector (schedule); disconnect_watches (); connect_watches (); // [RE-PROPAGATE] Since redundant clause were disconnected during // propagating vivified units above, we have propagate all those fixed // literals again after connecting the redundant clauses back. // Otherwise, the invariants for watching and blocking literals break. // if (old_propagated < propagated) { propagated = old_propagated; if (!propagate ()) { LOG ("propagating vivified units leads to conflict"); learn_empty_clause (); } } } VRB ("vivify", stats.vivifications, "checked %ld clauses %.02f%% out of scheduled", checked, percent (checked, scheduled)); if (units) VRB ("vivify", stats.vivifications, "found %ld units %.02f%% out of checked", units, percent (units, checked)); VRB ("vivify", stats.vivifications, "subsumed %ld clauses %.02f%% out of checked", subsumed, percent (subsumed, checked)); VRB ("vivify", stats.vivifications, "strengthened %ld clauses %.02f%% out of checked", strengthened, percent (strengthened, checked)); stats.vivifychecks += checked; stats.vivifysubs += subsumed; stats.vivifystrs += strengthened; stats.vivifyunits += units; stats.subsumed += subsumed; stats.strengthened += strengthened; assert (vivifying); vivifying = false; report ('v'); STOP_AND_SWITCH (vivify, simplify, search); } }; <|endoftext|>
<commit_before>#ifndef SOFA_COMPONENTS_LagrangianMultiplierContactConstraint_INL #define SOFA_COMPONENTS_LagrangianMultiplierContactConstraint_INL #include "LagrangianMultiplierContactConstraint.h" #include "Sofa/Core/Constraint.inl" #include "Sofa/Core/MechanicalObject.inl" #include "Common/config.h" #include <assert.h> #include <GL/gl.h> #include "GL/template.h" namespace Sofa { namespace Components { template<class DataTypes> void LagrangianMultiplierContactConstraint<DataTypes>::addContact(int m1, int m2, const Deriv& norm, Real dist, Real ks, Real mu_s, Real mu_v) { int i = contacts.size(); contacts.resize(i+1); lambda->resize(i+1); (*lambda->getX())[i] = 0; Contact& c = contacts[i]; c.m1 = m1; c.m2 = m2; c.norm = norm; c.dist = dist; c.ks = ks; c.mu_s = mu_s; c.mu_v = mu_v; c.pen = 0; } template<class DataTypes> void LagrangianMultiplierContactConstraint<DataTypes>::addForce() { assert(this->object1); assert(this->object2); VecDeriv& f1 = *this->object1->getF(); VecCoord& p1 = *this->object1->getX(); VecDeriv& v1 = *this->object1->getV(); VecDeriv& f2 = *this->object2->getF(); VecCoord& p2 = *this->object2->getX(); VecDeriv& v2 = *this->object2->getV(); f1.resize(p1.size()); f2.resize(p2.size()); LMVecCoord& lambda = *this->lambda->getX(); LMVecDeriv& flambda = *this->lambda->getF(); flambda.resize(lambda.size()); // Create list of active contact for (unsigned int i=0; i<contacts.size(); i++) { Contact& c = contacts[i]; c.pen0 = (p2[c.m2]-p1[c.m1])*c.norm - c.dist;//c.dist - (p1[c.m1]-p2[c.m2])*c.norm; } // flamdba += C X for (unsigned int i=0; i<contacts.size(); i++) { Contact& c = contacts[i]; if (c.pen0 > 0) continue; flambda[i] += p2[c.m2]*c.norm - p1[c.m1]*c.norm - c.dist; } // f += Ct lambda for (unsigned int i=0; i<contacts.size(); i++) { Contact& c = contacts[i]; if (c.pen0 > 0) continue; Real v = lambda[i]; f1[c.m1] += c.norm * v; f2[c.m2] -= c.norm * v; } } template<class DataTypes> void LagrangianMultiplierContactConstraint<DataTypes>::addDForce() { VecDeriv& f1 = *this->object1->getF(); VecCoord& p1 = *this->object1->getX(); VecDeriv& dx1 = *this->object1->getDx(); VecDeriv& f2 = *this->object2->getF(); VecCoord& p2 = *this->object2->getX(); VecDeriv& dx2 = *this->object2->getDx(); f1.resize(dx1.size()); f2.resize(dx2.size()); LMVecCoord& lambda = *this->lambda->getX(); LMVecCoord& dlambda = *this->lambda->getDx(); LMVecDeriv& flambda = *this->lambda->getF(); flambda.resize(dlambda.size()); // dflamdba += C dX // Create list of active contact for (unsigned int i=0; i<contacts.size(); i++) { Contact& c = contacts[i]; c.pen = c.pen0; // + dx2[c.m2]*c.norm - dx1[c.m1]*c.norm; } for (unsigned int i=0; i<contacts.size(); i++) { Contact& c = contacts[i]; if (c.pen > 0) continue; flambda[i] += dx2[c.m2]*c.norm - dx1[c.m1]*c.norm; } // df += Ct dlambda for (unsigned int i=0; i<contacts.size(); i++) { Contact& c = contacts[i]; if (c.pen > 0) continue; Real v = dlambda[i]; f1[c.m1] += c.norm * v; f2[c.m2] -= c.norm * v; } } template<class DataTypes> void LagrangianMultiplierContactConstraint<DataTypes>::draw() { if (!getContext()->getShowForceFields()) return; VecCoord& p1 = *this->object1->getX(); VecCoord& p2 = *this->object2->getX(); LMVecCoord& lambda = *this->lambda->getX(); glDisable(GL_LIGHTING); glBegin(GL_LINES); for (unsigned int i=0; i<contacts.size(); i++) { const Contact& c = contacts[i]; Real d = c.dist - (p2[c.m2]-p1[c.m1])*c.norm; if (d > 0) glColor4f(1,0,0,1); else glColor4f(0,1,0,1); GL::glVertexT(p1[c.m1]); GL::glVertexT(p2[c.m2]); } glEnd(); //if (getContext()->getShowNormals()) { glColor4f(1,1,0,1); glBegin(GL_LINES); for (unsigned int i=0; i<contacts.size(); i++) { const Contact& c = contacts[i]; if (c.pen > 0) continue; Coord p = p1[c.m1] - c.norm * lambda[i]; GL::glVertexT(p1[c.m1]); GL::glVertexT(p); p = p2[c.m2] + c.norm * lambda[i]; GL::glVertexT(p2[c.m2]); GL::glVertexT(p); } glEnd(); } } } // namespace Components } // namespace Sofa #endif <commit_msg>r309/sofa-dev : Correction of the unilateral Lagrange multipliers response method: - test based on the Lagrange multipliers values to know if a contact should be considered or not ! - This test should be relative to 0...but for numerical issue, it is relative to the value -0.05<commit_after>#ifndef SOFA_COMPONENTS_LagrangianMultiplierContactConstraint_INL #define SOFA_COMPONENTS_LagrangianMultiplierContactConstraint_INL #include "LagrangianMultiplierContactConstraint.h" #include "Sofa/Core/Constraint.inl" #include "Sofa/Core/MechanicalObject.inl" #include "Common/config.h" #include <assert.h> #include <GL/gl.h> #include "GL/template.h" namespace Sofa { namespace Components { template<class DataTypes> void LagrangianMultiplierContactConstraint<DataTypes>::addContact(int m1, int m2, const Deriv& norm, Real dist, Real ks, Real mu_s, Real mu_v) { int i = contacts.size(); contacts.resize(i+1); lambda->resize(i+1); (*lambda->getX())[i] = 0; Contact& c = contacts[i]; c.m1 = m1; c.m2 = m2; c.norm = norm; c.dist = dist; c.ks = ks; c.mu_s = mu_s; c.mu_v = mu_v; c.pen = 0; } template<class DataTypes> void LagrangianMultiplierContactConstraint<DataTypes>::addForce() { assert(this->object1); assert(this->object2); VecDeriv& f1 = *this->object1->getF(); VecCoord& p1 = *this->object1->getX(); VecDeriv& v1 = *this->object1->getV(); VecDeriv& f2 = *this->object2->getF(); VecCoord& p2 = *this->object2->getX(); VecDeriv& v2 = *this->object2->getV(); f1.resize(p1.size()); f2.resize(p2.size()); LMVecCoord& lambda = *this->lambda->getX(); LMVecDeriv& flambda = *this->lambda->getF(); flambda.resize(lambda.size()); // Create list of active contact for (unsigned int i=0; i<contacts.size(); i++) { Contact& c = contacts[i]; c.pen = c.pen0 = (p2[c.m2]-p1[c.m1])*c.norm - c.dist;//c.dist - (p1[c.m1]-p2[c.m2])*c.norm; lambda[i] = c.pen0; } // flamdba += C . DOF for (unsigned int i=0; i<contacts.size(); i++) { Contact& c = contacts[i]; if (lambda[i] > -0.05) continue; flambda[i] += p2[c.m2]*c.norm - p1[c.m1]*c.norm - c.dist; } // f += Ct . lambda for (unsigned int i=0; i<contacts.size(); i++) { Contact& c = contacts[i]; Real v = lambda[i]; if (lambda[i] > -0.05) continue; f1[c.m1] += c.norm * v; f2[c.m2] -= c.norm * v; } } template<class DataTypes> void LagrangianMultiplierContactConstraint<DataTypes>::addDForce() { VecDeriv& f1 = *this->object1->getF(); VecCoord& p1 = *this->object1->getX(); VecDeriv& dx1 = *this->object1->getDx(); VecDeriv& f2 = *this->object2->getF(); VecCoord& p2 = *this->object2->getX(); VecDeriv& dx2 = *this->object2->getDx(); f1.resize(dx1.size()); f2.resize(dx2.size()); LMVecCoord& lambda = *this->lambda->getX(); LMVecCoord& dlambda = *this->lambda->getDx(); LMVecDeriv& flambda = *this->lambda->getF(); flambda.resize(dlambda.size()); // dflamdba += C . dX for (unsigned int i=0; i<contacts.size(); i++) { Contact& c = contacts[i]; if (lambda[i] > -0.05) continue; flambda[i] += dx2[c.m2]*c.norm - dx1[c.m1]*c.norm; } // df += Ct . dlambda for (unsigned int i=0; i<contacts.size(); i++) { Contact& c = contacts[i]; if (lambda[i] > -0.05) continue; Real v = dlambda[i]; f1[c.m1] += c.norm * v; f2[c.m2] -= c.norm * v; } } template<class DataTypes> void LagrangianMultiplierContactConstraint<DataTypes>::draw() { if (!getContext()->getShowForceFields()) return; VecCoord& p1 = *this->object1->getX(); VecCoord& p2 = *this->object2->getX(); LMVecCoord& lambda = *this->lambda->getX(); glDisable(GL_LIGHTING); glBegin(GL_LINES); for (unsigned int i=0; i<contacts.size(); i++) { const Contact& c = contacts[i]; Real d = c.dist - (p2[c.m2]-p1[c.m1])*c.norm; if (d > 0) glColor4f(1,0,0,1); else glColor4f(0,1,0,1); GL::glVertexT(p1[c.m1]); GL::glVertexT(p2[c.m2]); } glEnd(); //if (getContext()->getShowNormals()) { glColor4f(1,1,0,1); glBegin(GL_LINES); for (unsigned int i=0; i<contacts.size(); i++) { const Contact& c = contacts[i]; if (c.pen > 0) continue; Coord p = p1[c.m1] - c.norm * lambda[i]; GL::glVertexT(p1[c.m1]); GL::glVertexT(p); p = p2[c.m2] + c.norm * lambda[i]; GL::glVertexT(p2[c.m2]); GL::glVertexT(p); } glEnd(); } } } // namespace Components } // namespace Sofa #endif <|endoftext|>
<commit_before>#include "rubykokuban/BindImage.hpp" #include "mruby.h" #include "mruby/class.h" #include "mruby/data.h" #include "mruby/string.h" #include "ofMain.h" namespace rubykokuban { namespace { void free(mrb_state *mrb, void *p) { if (p) { delete ((ofImage*)p); } } struct mrb_data_type data_type = { "rubykokuban_image", free }; mrb_value load(mrb_state *mrb, mrb_value self) { ofImage* obj = new ofImage(); mrb_value str; mrb_get_args(mrb, "S", &str); string filename(mrb_string_value_ptr(mrb, str)); obj->loadImage(filename); struct RData *data = mrb_data_object_alloc(mrb, mrb_class_ptr(self), obj, &data_type); return mrb_obj_value(data); } mrb_value grab_screen(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value save(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value color(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value set_color(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value resize(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value set_image_type(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value crop_bang(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value crop(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value rotate90(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value mirror(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value update(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value set_anchor_percent(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value set_anchor_point(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value reset_anchor(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value draw(mrb_state *mrb, mrb_value self) { mrb_int x, y; mrb_get_args(mrb, "ii", &x, &y); ofImage* obj = (ofImage*)DATA_PTR(self); obj->draw(x, y); return mrb_nil_value(); } mrb_value draw_sub(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value height(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value width(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } } //-------------------------------------------------------------------------------- void BindImage::Bind(mrb_state* mrb) { struct RClass *cc = mrb_define_class(mrb, "Image", mrb->object_class); mrb_define_class_method(mrb , cc, "load", load, MRB_ARGS_REQ(1)); mrb_define_class_method(mrb , cc, "grab_screen", grab_screen, MRB_ARGS_REQ(4)); mrb_define_method(mrb, cc, "save", save, MRB_ARGS_ARG(2, 1)); mrb_define_method(mrb, cc, "color", color, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "set_color", set_color, MRB_ARGS_REQ(3)); mrb_define_method(mrb, cc, "resize", resize, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "set_image_type", set_image_type, MRB_ARGS_REQ(1)); mrb_define_method(mrb, cc, "crop", crop, MRB_ARGS_REQ(5)); mrb_define_method(mrb, cc, "crop!", crop_bang, MRB_ARGS_REQ(4)); mrb_define_method(mrb, cc, "rotate90", rotate90, MRB_ARGS_REQ(1)); mrb_define_method(mrb, cc, "mirror", mirror, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "update", update, MRB_ARGS_NONE()); mrb_define_method(mrb, cc, "set_anchor_percent", set_anchor_percent, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "set_anchor_point", set_anchor_point, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "reset_anchor", reset_anchor, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "draw", draw, MRB_ARGS_ARG(2, 3)); mrb_define_method(mrb, cc, "draw_sub", draw_sub, MRB_ARGS_ARG(6, 2)); mrb_define_method(mrb, cc, "height", height, MRB_ARGS_NONE()); mrb_define_method(mrb, cc, "width", width, MRB_ARGS_NONE()); } } <commit_msg>Add obj(mrb_value self)<commit_after>#include "rubykokuban/BindImage.hpp" #include "mruby.h" #include "mruby/class.h" #include "mruby/data.h" #include "mruby/string.h" #include "ofMain.h" namespace rubykokuban { namespace { ofImage& obj(mrb_value self) { return *((ofImage*)DATA_PTR(self)); } void free(mrb_state *mrb, void *p) { if (p) { delete ((ofImage*)p); } } struct mrb_data_type data_type = { "rubykokuban_image", free }; mrb_value load(mrb_state *mrb, mrb_value self) { ofImage* obj = new ofImage(); mrb_value str; mrb_get_args(mrb, "S", &str); string filename(mrb_string_value_ptr(mrb, str)); obj->loadImage(filename); struct RData *data = mrb_data_object_alloc(mrb, mrb_class_ptr(self), obj, &data_type); return mrb_obj_value(data); } mrb_value grab_screen(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value save(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value color(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value set_color(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value resize(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value set_image_type(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value crop_bang(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value crop(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value rotate90(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value mirror(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value update(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value set_anchor_percent(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value set_anchor_point(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value reset_anchor(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value draw(mrb_state *mrb, mrb_value self) { mrb_int x, y; mrb_get_args(mrb, "ii", &x, &y); obj(self).draw(x, y); return mrb_nil_value(); } mrb_value draw_sub(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value height(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value width(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } } //-------------------------------------------------------------------------------- void BindImage::Bind(mrb_state* mrb) { struct RClass *cc = mrb_define_class(mrb, "Image", mrb->object_class); mrb_define_class_method(mrb , cc, "load", load, MRB_ARGS_REQ(1)); mrb_define_class_method(mrb , cc, "grab_screen", grab_screen, MRB_ARGS_REQ(4)); mrb_define_method(mrb, cc, "save", save, MRB_ARGS_ARG(2, 1)); mrb_define_method(mrb, cc, "color", color, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "set_color", set_color, MRB_ARGS_REQ(3)); mrb_define_method(mrb, cc, "resize", resize, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "set_image_type", set_image_type, MRB_ARGS_REQ(1)); mrb_define_method(mrb, cc, "crop", crop, MRB_ARGS_REQ(5)); mrb_define_method(mrb, cc, "crop!", crop_bang, MRB_ARGS_REQ(4)); mrb_define_method(mrb, cc, "rotate90", rotate90, MRB_ARGS_REQ(1)); mrb_define_method(mrb, cc, "mirror", mirror, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "update", update, MRB_ARGS_NONE()); mrb_define_method(mrb, cc, "set_anchor_percent", set_anchor_percent, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "set_anchor_point", set_anchor_point, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "reset_anchor", reset_anchor, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "draw", draw, MRB_ARGS_ARG(2, 3)); mrb_define_method(mrb, cc, "draw_sub", draw_sub, MRB_ARGS_ARG(6, 2)); mrb_define_method(mrb, cc, "height", height, MRB_ARGS_NONE()); mrb_define_method(mrb, cc, "width", width, MRB_ARGS_NONE()); } } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #ifndef SOFA_COMPONENT_INTERACTIONFORCEFIELD_PLANEFORCEFIELD_INL #define SOFA_COMPONENT_INTERACTIONFORCEFIELD_PLANEFORCEFIELD_INL #include <sofa/core/behavior/ForceField.inl> #include <sofa/core/visual/VisualParams.h> #include <sofa/simulation/common/Simulation.h> #include <sofa/component/forcefield/PlaneForceField.h> #include <sofa/helper/system/config.h> #include <sofa/helper/accessor.h> #include <sofa/defaulttype/VecTypes.h> #include <sofa/helper/gl/template.h> #include <assert.h> #include <iostream> #include <sofa/defaulttype/BoundingBox.h> #include <limits> namespace sofa { namespace component { namespace forcefield { template<class DataTypes> void PlaneForceField<DataTypes>::setPlane(const Deriv& normal, Real d) { DPos tmpN = DataTypes::getDPos(normal); Real n = tmpN.norm(); planeNormal.setValue( tmpN / n); planeD.setValue( d / n ); } template<class DataTypes> void PlaneForceField<DataTypes>::addForce(const core::MechanicalParams* /* mparams */ /* PARAMS FIRST */, DataVecDeriv& f, const DataVecCoord& x, const DataVecDeriv& v) { sofa::helper::WriteAccessor< core::objectmodel::Data< VecDeriv > > f1 = f; sofa::helper::ReadAccessor< core::objectmodel::Data< VecCoord > > p1 = x; sofa::helper::ReadAccessor< core::objectmodel::Data< VecDeriv > > v1 = v; //this->dfdd.resize(p1.size()); this->contacts.clear(); f1.resize(p1.size()); unsigned int ibegin = 0; unsigned int iend = p1.size(); if (localRange.getValue()[0] >= 0) ibegin = localRange.getValue()[0]; if (localRange.getValue()[1] >= 0 && (unsigned int)localRange.getValue()[1]+1 < iend) iend = localRange.getValue()[1]+1; Real limit = this->maxForce.getValue(); limit *= limit; // squared Real stiff = this->stiffness.getValue(); Real damp = this->damping.getValue(); DPos planeN = planeNormal.getValue(); for (unsigned int i=ibegin; i<iend; i++) { Real d = DataTypes::getCPos(p1[i])*planeN-planeD.getValue(); if (bilateral.getValue() || d<0 ) { //serr<<"PlaneForceField<DataTypes>::addForce, d = "<<d<<sendl; Real forceIntensity = -stiff*d; //serr<<"PlaneForceField<DataTypes>::addForce, stiffness = "<<stiffness.getValue()<<sendl; Real dampingIntensity = -damp*d; //serr<<"PlaneForceField<DataTypes>::addForce, dampingIntensity = "<<dampingIntensity<<sendl; DPos force = planeN*forceIntensity - DataTypes::getDPos(v1[i])*dampingIntensity; Real amplitude = force.norm2(); if(limit && amplitude > limit) force *= sqrt(limit / amplitude); //serr<<"PlaneForceField<DataTypes>::addForce, force = "<<force<<sendl; Deriv tmpF; DataTypes::setDPos(tmpF, force); f1[i] += tmpF; //this->dfdd[i] = -this->stiffness; this->contacts.push_back(i); } } } template<class DataTypes> void PlaneForceField<DataTypes>::addDForce(const core::MechanicalParams* mparams /* PARAMS FIRST */, DataVecDeriv& df, const DataVecDeriv& dx) { sofa::helper::WriteAccessor< core::objectmodel::Data< VecDeriv > > df1 = df; sofa::helper::ReadAccessor< core::objectmodel::Data< VecDeriv > > dx1 = dx; df1.resize(dx1.size()); const Real fact = (Real)(-this->stiffness.getValue() * mparams->kFactorIncludingRayleighDamping(this->rayleighStiffness.getValue())); DPos planeN = planeNormal.getValue(); for (unsigned int i=0; i<this->contacts.size(); i++) { unsigned int p = this->contacts[i]; assert(p<dx1.size()); DataTypes::setDPos(df1[p], DataTypes::getDPos(df1[p]) + planeN * (fact * (DataTypes::getDPos(dx1[p]) * planeN))); } } template<class DataTypes> void PlaneForceField<DataTypes>::addKToMatrix(const core::MechanicalParams* mparams /* PARAMS FIRST */, const sofa::core::behavior::MultiMatrixAccessor* matrix ) { const Real fact = (Real)(-this->stiffness.getValue()*mparams->kFactorIncludingRayleighDamping(this->rayleighStiffness.getValue())); Deriv normal; DataTypes::setDPos(normal, planeNormal.getValue()); sofa::core::behavior::MultiMatrixAccessor::MatrixRef mref = matrix->getMatrix(this->mstate); sofa::defaulttype::BaseMatrix* mat = mref.matrix; unsigned int offset = mref.offset; for (unsigned int i=0; i<this->contacts.size(); i++) { unsigned int p = this->contacts[i]; for (int l=0; l<Deriv::total_size; ++l) for (int c=0; c<Deriv::total_size; ++c) { SReal coef = normal[l] * fact * normal[c]; mat->add(offset + p*Deriv::total_size + l, offset + p*Deriv::total_size + c, coef); } } } template<class DataTypes> void PlaneForceField<DataTypes>::updateStiffness( const VecCoord& vx ) { helper::ReadAccessor<VecCoord> x = vx; this->contacts.clear(); unsigned int ibegin = 0; unsigned int iend = x.size(); if (localRange.getValue()[0] >= 0) ibegin = localRange.getValue()[0]; if (localRange.getValue()[1] >= 0 && (unsigned int)localRange.getValue()[1]+1 < iend) iend = localRange.getValue()[1]+1; for (unsigned int i=ibegin; i<iend; i++) { Real d = DataTypes::getCPos(x[i])*planeNormal.getValue()-planeD.getValue(); if (d<0) this->contacts.push_back(i); } } // Rotate the plane. Note that the rotation is only applied on the 3 first coordinates template<class DataTypes> void PlaneForceField<DataTypes>::rotate( Deriv axe, Real angle ) { defaulttype::Vec3d axe3d(1,1,1); axe3d = DataTypes::getDPos(axe); defaulttype::Vec3d normal3d; normal3d = planeNormal.getValue(); defaulttype::Vec3d v = normal3d.cross(axe3d); if (v.norm2() < 1.0e-10) return; v.normalize(); v = normal3d * cos ( angle ) + v * sin ( angle ); *planeNormal.beginEdit() = v; planeNormal.endEdit(); } template<class DataTypes> void PlaneForceField<DataTypes>::draw(const core::visual::VisualParams* vparams) { if (!vparams->displayFlags().getShowForceFields()) return; //if (!vparams->isSupported(core::visual::API_OpenGL)) return; drawPlane(vparams); } template<class DataTypes> void PlaneForceField<DataTypes>::drawPlane(const core::visual::VisualParams* vparams,float size) { if (size == 0.0f) size = (float)drawSize.getValue(); helper::ReadAccessor<VecCoord> p1 = *this->mstate->getX(); defaulttype::Vec3d normal; normal = planeNormal.getValue(); // find a first vector inside the plane defaulttype::Vec3d v1; if( 0.0 != normal[0] ) v1 = defaulttype::Vec3d(-normal[1]/normal[0], 1.0, 0.0); else if ( 0.0 != normal[1] ) v1 = defaulttype::Vec3d(1.0, -normal[0]/normal[1],0.0); else if ( 0.0 != normal[2] ) v1 = defaulttype::Vec3d(1.0, 0.0, -normal[0]/normal[2]); v1.normalize(); // find a second vector inside the plane and orthogonal to the first defaulttype::Vec3d v2; v2 = v1.cross(normal); v2.normalize(); defaulttype::Vec3d center = normal*planeD.getValue(); defaulttype::Vec3d corners[4]; corners[0] = center-v1*size-v2*size; corners[1] = center+v1*size-v2*size; corners[2] = center+v1*size+v2*size; corners[3] = center-v1*size+v2*size; std::vector< defaulttype::Vector3 > points; points.push_back(corners[0]); points.push_back(corners[1]); points.push_back(corners[2]); points.push_back(corners[0]); points.push_back(corners[2]); points.push_back(corners[3]); vparams->drawTool()->setPolygonMode(2,false); //Cull Front face vparams->drawTool()->drawTriangles(points, defaulttype::Vec<4,float>(color.getValue()[0],color.getValue()[1],color.getValue()[2],0.5)); vparams->drawTool()->setPolygonMode(0,false); //No Culling std::vector< defaulttype::Vector3 > pointsLine; // lines for points penetrating the plane unsigned int ibegin = 0; unsigned int iend = p1.size(); if (localRange.getValue()[0] >= 0) ibegin = localRange.getValue()[0]; if (localRange.getValue()[1] >= 0 && (unsigned int)localRange.getValue()[1]+1 < iend) iend = localRange.getValue()[1]+1; defaulttype::Vector3 point1,point2; for (unsigned int i=ibegin; i<iend; i++) { Real d = DataTypes::getCPos(p1[i])*planeNormal.getValue()-planeD.getValue(); CPos p2 = DataTypes::getCPos(p1[i]); p2 += planeNormal.getValue()*(-d); if (d<0) { point1 = DataTypes::getCPos(p1[i]); point2 = p2; pointsLine.push_back(point1); pointsLine.push_back(point2); } } vparams->drawTool()->drawLines(pointsLine, 1, defaulttype::Vec<4,float>(1,0,0,1)); } template <class DataTypes> void PlaneForceField<DataTypes>::computeBBox(const core::ExecParams * params) { if (!bDraw.getValue()) return; const Real max_real = std::numeric_limits<Real>::max(); const Real min_real = std::numeric_limits<Real>::min(); Real maxBBox[3] = {min_real,min_real,min_real}; Real minBBox[3] = {max_real,max_real,max_real}; defaulttype::Vec3d normal; normal = planeNormal.getValue(params); double size=10.0; // find a first vector inside the plane defaulttype::Vec3d v1; if( 0.0 != normal[0] ) v1 = defaulttype::Vec3d(-normal[1]/normal[0], 1.0, 0.0); else if ( 0.0 != normal[1] ) v1 = defaulttype::Vec3d(1.0, -normal[0]/normal[1],0.0); else if ( 0.0 != normal[2] ) v1 = defaulttype::Vec3d(1.0, 0.0, -normal[0]/normal[2]); v1.normalize(); // find a second vector inside the plane and orthogonal to the first defaulttype::Vec3d v2; v2 = v1.cross(normal); v2.normalize(); defaulttype::Vec3d center = normal*planeD.getValue(); defaulttype::Vec3d corners[4]; corners[0] = center-v1*size-v2*size; corners[1] = center+v1*size-v2*size; corners[2] = center+v1*size+v2*size; corners[3] = center-v1*size+v2*size; for (unsigned int i=0; i<4; i++) { for (int c=0; c<3; c++) { if (corners[i][c] > maxBBox[c]) maxBBox[c] = (Real)corners[i][c]; if (corners[i][c] < minBBox[c]) minBBox[c] = (Real)corners[i][c]; } } this->f_bbox.setValue(params,sofa::defaulttype::TBoundingBox<Real>(minBBox,maxBBox)); } } // namespace forcefield } // namespace component } // namespace sofa #endif <commit_msg>r11306/sofa : fix PlaneForceField visu: use draw boolean to draw or not<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #ifndef SOFA_COMPONENT_INTERACTIONFORCEFIELD_PLANEFORCEFIELD_INL #define SOFA_COMPONENT_INTERACTIONFORCEFIELD_PLANEFORCEFIELD_INL #include <sofa/core/behavior/ForceField.inl> #include <sofa/core/visual/VisualParams.h> #include <sofa/simulation/common/Simulation.h> #include <sofa/component/forcefield/PlaneForceField.h> #include <sofa/helper/system/config.h> #include <sofa/helper/accessor.h> #include <sofa/defaulttype/VecTypes.h> #include <sofa/helper/gl/template.h> #include <assert.h> #include <iostream> #include <sofa/defaulttype/BoundingBox.h> #include <limits> namespace sofa { namespace component { namespace forcefield { template<class DataTypes> void PlaneForceField<DataTypes>::setPlane(const Deriv& normal, Real d) { DPos tmpN = DataTypes::getDPos(normal); Real n = tmpN.norm(); planeNormal.setValue( tmpN / n); planeD.setValue( d / n ); } template<class DataTypes> void PlaneForceField<DataTypes>::addForce(const core::MechanicalParams* /* mparams */ /* PARAMS FIRST */, DataVecDeriv& f, const DataVecCoord& x, const DataVecDeriv& v) { sofa::helper::WriteAccessor< core::objectmodel::Data< VecDeriv > > f1 = f; sofa::helper::ReadAccessor< core::objectmodel::Data< VecCoord > > p1 = x; sofa::helper::ReadAccessor< core::objectmodel::Data< VecDeriv > > v1 = v; //this->dfdd.resize(p1.size()); this->contacts.clear(); f1.resize(p1.size()); unsigned int ibegin = 0; unsigned int iend = p1.size(); if (localRange.getValue()[0] >= 0) ibegin = localRange.getValue()[0]; if (localRange.getValue()[1] >= 0 && (unsigned int)localRange.getValue()[1]+1 < iend) iend = localRange.getValue()[1]+1; Real limit = this->maxForce.getValue(); limit *= limit; // squared Real stiff = this->stiffness.getValue(); Real damp = this->damping.getValue(); DPos planeN = planeNormal.getValue(); for (unsigned int i=ibegin; i<iend; i++) { Real d = DataTypes::getCPos(p1[i])*planeN-planeD.getValue(); if (bilateral.getValue() || d<0 ) { //serr<<"PlaneForceField<DataTypes>::addForce, d = "<<d<<sendl; Real forceIntensity = -stiff*d; //serr<<"PlaneForceField<DataTypes>::addForce, stiffness = "<<stiffness.getValue()<<sendl; Real dampingIntensity = -damp*d; //serr<<"PlaneForceField<DataTypes>::addForce, dampingIntensity = "<<dampingIntensity<<sendl; DPos force = planeN*forceIntensity - DataTypes::getDPos(v1[i])*dampingIntensity; Real amplitude = force.norm2(); if(limit && amplitude > limit) force *= sqrt(limit / amplitude); //serr<<"PlaneForceField<DataTypes>::addForce, force = "<<force<<sendl; Deriv tmpF; DataTypes::setDPos(tmpF, force); f1[i] += tmpF; //this->dfdd[i] = -this->stiffness; this->contacts.push_back(i); } } } template<class DataTypes> void PlaneForceField<DataTypes>::addDForce(const core::MechanicalParams* mparams /* PARAMS FIRST */, DataVecDeriv& df, const DataVecDeriv& dx) { sofa::helper::WriteAccessor< core::objectmodel::Data< VecDeriv > > df1 = df; sofa::helper::ReadAccessor< core::objectmodel::Data< VecDeriv > > dx1 = dx; df1.resize(dx1.size()); const Real fact = (Real)(-this->stiffness.getValue() * mparams->kFactorIncludingRayleighDamping(this->rayleighStiffness.getValue())); DPos planeN = planeNormal.getValue(); for (unsigned int i=0; i<this->contacts.size(); i++) { unsigned int p = this->contacts[i]; assert(p<dx1.size()); DataTypes::setDPos(df1[p], DataTypes::getDPos(df1[p]) + planeN * (fact * (DataTypes::getDPos(dx1[p]) * planeN))); } } template<class DataTypes> void PlaneForceField<DataTypes>::addKToMatrix(const core::MechanicalParams* mparams /* PARAMS FIRST */, const sofa::core::behavior::MultiMatrixAccessor* matrix ) { const Real fact = (Real)(-this->stiffness.getValue()*mparams->kFactorIncludingRayleighDamping(this->rayleighStiffness.getValue())); Deriv normal; DataTypes::setDPos(normal, planeNormal.getValue()); sofa::core::behavior::MultiMatrixAccessor::MatrixRef mref = matrix->getMatrix(this->mstate); sofa::defaulttype::BaseMatrix* mat = mref.matrix; unsigned int offset = mref.offset; for (unsigned int i=0; i<this->contacts.size(); i++) { unsigned int p = this->contacts[i]; for (int l=0; l<Deriv::total_size; ++l) for (int c=0; c<Deriv::total_size; ++c) { SReal coef = normal[l] * fact * normal[c]; mat->add(offset + p*Deriv::total_size + l, offset + p*Deriv::total_size + c, coef); } } } template<class DataTypes> void PlaneForceField<DataTypes>::updateStiffness( const VecCoord& vx ) { helper::ReadAccessor<VecCoord> x = vx; this->contacts.clear(); unsigned int ibegin = 0; unsigned int iend = x.size(); if (localRange.getValue()[0] >= 0) ibegin = localRange.getValue()[0]; if (localRange.getValue()[1] >= 0 && (unsigned int)localRange.getValue()[1]+1 < iend) iend = localRange.getValue()[1]+1; for (unsigned int i=ibegin; i<iend; i++) { Real d = DataTypes::getCPos(x[i])*planeNormal.getValue()-planeD.getValue(); if (d<0) this->contacts.push_back(i); } } // Rotate the plane. Note that the rotation is only applied on the 3 first coordinates template<class DataTypes> void PlaneForceField<DataTypes>::rotate( Deriv axe, Real angle ) { defaulttype::Vec3d axe3d(1,1,1); axe3d = DataTypes::getDPos(axe); defaulttype::Vec3d normal3d; normal3d = planeNormal.getValue(); defaulttype::Vec3d v = normal3d.cross(axe3d); if (v.norm2() < 1.0e-10) return; v.normalize(); v = normal3d * cos ( angle ) + v * sin ( angle ); *planeNormal.beginEdit() = v; planeNormal.endEdit(); } template<class DataTypes> void PlaneForceField<DataTypes>::draw(const core::visual::VisualParams* vparams) { if (!vparams->displayFlags().getShowForceFields()) return; //if (!vparams->isSupported(core::visual::API_OpenGL)) return; if (bDraw.getValue()) drawPlane(vparams); } template<class DataTypes> void PlaneForceField<DataTypes>::drawPlane(const core::visual::VisualParams* vparams,float size) { if (size == 0.0f) size = (float)drawSize.getValue(); helper::ReadAccessor<VecCoord> p1 = *this->mstate->getX(); defaulttype::Vec3d normal; normal = planeNormal.getValue(); // find a first vector inside the plane defaulttype::Vec3d v1; if( 0.0 != normal[0] ) v1 = defaulttype::Vec3d(-normal[1]/normal[0], 1.0, 0.0); else if ( 0.0 != normal[1] ) v1 = defaulttype::Vec3d(1.0, -normal[0]/normal[1],0.0); else if ( 0.0 != normal[2] ) v1 = defaulttype::Vec3d(1.0, 0.0, -normal[0]/normal[2]); v1.normalize(); // find a second vector inside the plane and orthogonal to the first defaulttype::Vec3d v2; v2 = v1.cross(normal); v2.normalize(); defaulttype::Vec3d center = normal*planeD.getValue(); defaulttype::Vec3d corners[4]; corners[0] = center-v1*size-v2*size; corners[1] = center+v1*size-v2*size; corners[2] = center+v1*size+v2*size; corners[3] = center-v1*size+v2*size; std::vector< defaulttype::Vector3 > points; points.push_back(corners[0]); points.push_back(corners[1]); points.push_back(corners[2]); points.push_back(corners[0]); points.push_back(corners[2]); points.push_back(corners[3]); vparams->drawTool()->setPolygonMode(2,false); //Cull Front face vparams->drawTool()->drawTriangles(points, defaulttype::Vec<4,float>(color.getValue()[0],color.getValue()[1],color.getValue()[2],0.5)); vparams->drawTool()->setPolygonMode(0,false); //No Culling std::vector< defaulttype::Vector3 > pointsLine; // lines for points penetrating the plane unsigned int ibegin = 0; unsigned int iend = p1.size(); if (localRange.getValue()[0] >= 0) ibegin = localRange.getValue()[0]; if (localRange.getValue()[1] >= 0 && (unsigned int)localRange.getValue()[1]+1 < iend) iend = localRange.getValue()[1]+1; defaulttype::Vector3 point1,point2; for (unsigned int i=ibegin; i<iend; i++) { Real d = DataTypes::getCPos(p1[i])*planeNormal.getValue()-planeD.getValue(); CPos p2 = DataTypes::getCPos(p1[i]); p2 += planeNormal.getValue()*(-d); if (d<0) { point1 = DataTypes::getCPos(p1[i]); point2 = p2; pointsLine.push_back(point1); pointsLine.push_back(point2); } } vparams->drawTool()->drawLines(pointsLine, 1, defaulttype::Vec<4,float>(1,0,0,1)); } template <class DataTypes> void PlaneForceField<DataTypes>::computeBBox(const core::ExecParams * params) { if (!bDraw.getValue()) return; const Real max_real = std::numeric_limits<Real>::max(); const Real min_real = std::numeric_limits<Real>::min(); Real maxBBox[3] = {min_real,min_real,min_real}; Real minBBox[3] = {max_real,max_real,max_real}; defaulttype::Vec3d normal; normal = planeNormal.getValue(params); double size=10.0; // find a first vector inside the plane defaulttype::Vec3d v1; if( 0.0 != normal[0] ) v1 = defaulttype::Vec3d(-normal[1]/normal[0], 1.0, 0.0); else if ( 0.0 != normal[1] ) v1 = defaulttype::Vec3d(1.0, -normal[0]/normal[1],0.0); else if ( 0.0 != normal[2] ) v1 = defaulttype::Vec3d(1.0, 0.0, -normal[0]/normal[2]); v1.normalize(); // find a second vector inside the plane and orthogonal to the first defaulttype::Vec3d v2; v2 = v1.cross(normal); v2.normalize(); defaulttype::Vec3d center = normal*planeD.getValue(); defaulttype::Vec3d corners[4]; corners[0] = center-v1*size-v2*size; corners[1] = center+v1*size-v2*size; corners[2] = center+v1*size+v2*size; corners[3] = center-v1*size+v2*size; for (unsigned int i=0; i<4; i++) { for (int c=0; c<3; c++) { if (corners[i][c] > maxBBox[c]) maxBBox[c] = (Real)corners[i][c]; if (corners[i][c] < minBBox[c]) minBBox[c] = (Real)corners[i][c]; } } this->f_bbox.setValue(params,sofa::defaulttype::TBoundingBox<Real>(minBBox,maxBBox)); } } // namespace forcefield } // namespace component } // namespace sofa #endif <|endoftext|>
<commit_before>/* Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Gabriel Ebner */ #include "util/log_tree.h" #include "util/task_builder.h" #include <vector> #include <string> namespace lean { void log_tree::notify_core(std::vector<log_tree::event> const & events) { if (events.empty()) return; for (auto & l : m_listeners) l(events); } void log_tree::add_listener(log_tree::listener const & l) { unique_lock<mutex> lock(m_mutex); m_listeners.push_back(l); } log_tree::log_tree() { auto cell = new node_cell; cell->m_tree = this; m_root = node(cell); } log_tree::~log_tree() { std::vector<event> evs; m_root.detach_core(evs); m_root = node(); } void log_tree::print_to(std::ostream & out) const { get_root().print_to(out, 0); } void log_tree::print() const { print_to(std::cerr); } void log_tree::node::for_each(std::function<bool(log_tree::node const &)> const & fn) const { // NOLINT if (fn(*this)) { get_children().for_each([&] (name const &, log_tree::node const & c) { c.for_each(fn); }); } }; void log_tree::for_each(std::function<bool(log_tree::node const &)> const & fn) const { // NOLINT m_root.for_each(fn); }; void log_tree::node::detach_core(std::vector<log_tree::event> & events) const { if (m_ptr->m_detached) return; m_ptr->m_detached = true; m_ptr->m_children.for_each([&] (name const &, node const & c) { c.detach_core(events); }); for (auto & e : m_ptr->m_entries) events.push_back({ event::EntryRemoved, m_ptr, e }); if (m_ptr->m_producer) events.push_back({event::Finished, m_ptr, {}}); } void log_tree::node::notify(std::vector<log_tree::event> const & events, unique_lock<mutex> & l) const { if (!m_ptr->m_detached) { l.unlock(); m_ptr->m_tree->notify_core(events); } } log_tree::node log_tree::node::clone_core() const { auto copy = node(new node_cell); copy.m_ptr->m_children = m_ptr->m_children; m_ptr->m_children.clear(); copy.m_ptr->m_tree = m_ptr->m_tree; copy.m_ptr->m_detached = m_ptr->m_detached; copy.m_ptr->m_entries = m_ptr->m_entries; m_ptr->m_detached = true; return copy; } void log_tree::node::clear_entries() const { auto l = lock(); std::vector<event> events; for (auto & e : m_ptr->m_entries) { events.push_back({event::EntryRemoved, *this, std::move(e)}); } m_ptr->m_entries.clear(); notify(events, l); } void log_tree::node::add(log_entry const & entry) const { auto l = lock(); m_ptr->m_entries.push_back(entry); notify({{event::EntryAdded, *this, entry}}, l); } log_tree::node log_tree::node::mk_child(name n, std::string const & description, location const & loc, bool overwrite) { auto l = lock(); std::vector<event> events; if (!overwrite && (n.is_anonymous() || m_ptr->m_used_names.contains(n))) { for (unsigned i = 0;; i++) { name n_(n, i); if (!m_ptr->m_used_names.contains(n_)) { n = n_; break; } } } m_ptr->m_used_names.insert(n); node child; if (auto existing = m_ptr->m_children.find(n)) { child = existing->clone_core(); existing->detach_core(events); } else { child = node(new node_cell); child.m_ptr->m_tree = m_ptr->m_tree; child.m_ptr->m_detached = m_ptr->m_detached; } child.m_ptr->m_description = description; child.m_ptr->m_location = loc; m_ptr->m_children.insert(n, child); notify(events, l); return child; } void log_tree::node::set_producer(gtask const & prod) { auto l = lock(); m_ptr->m_producer = prod; notify({{event::ProducerSet, *this, {}}}, l); } void log_tree::node::finish() const { auto l = lock(); std::vector<event> events; m_ptr->m_producer.reset(); buffer<pair<name, node>> to_delete; m_ptr->m_children.for_each([&] (name const & n, node const & c) { if (!m_ptr->m_used_names.contains(n)) to_delete.emplace_back(n, c); }); for (auto & c : to_delete) { m_ptr->m_children.erase(c.first); c.second.detach_core(events); } events.push_back({event::Finished, *this, {}}); notify(events, l); } std::vector<log_entry> log_tree::node::get_entries() const { auto l = lock(); return m_ptr->m_entries; } name_map<lean::log_tree::node> log_tree::node::get_children() const { auto l = lock(); return m_ptr->m_children; } void log_tree::node::remove_child(name const & n) const { auto l = lock(); if (auto c = m_ptr->m_children.find(n)) { m_ptr->m_children.erase(n); std::vector<event> events; c->detach_core(events); notify(events, l); } } name_map<log_tree::node> log_tree::node::get_used_children() const { auto l = lock(); name_map<node> used_children; m_ptr->m_used_names.for_each([&] (name const & n) { if (auto c = m_ptr->m_children.find(n)) { used_children.insert(n, *c); } }); return used_children; } void log_tree::node::reuse(name const & n) const { auto l = lock(); m_ptr->m_used_names.insert(n); } name_set log_tree::node::get_used_names() const { auto l = lock(); return m_ptr->m_used_names; } gtask log_tree::node::get_producer() const { auto l = lock(); return m_ptr->m_producer; } void log_tree::node::print() const { print_to(std::cerr, 0); } void log_tree::node::print_to(std::ostream & out, unsigned indent) const { indent += 2; auto l = lock(); auto begin = m_ptr->m_location.m_range.m_begin, end = m_ptr->m_location.m_range.m_end; out << m_ptr->m_location.m_file_name << ": " << begin.first << ":" << begin.second << " -- " << end.first << ":" << end.second << ": " << m_ptr->m_description << " (" << m_ptr->m_entries.size() << " entries, producer = " << std::hex << reinterpret_cast<uintptr_t>(m_ptr->m_producer.get()) << std::dec << ")" << std::endl; if (auto prod = m_ptr->m_producer) { if (auto ex = prod->peek_exception()) { for (unsigned i = 0; i < indent; i++) out << ' '; out << "producer threw exception: "; try { std::rethrow_exception(ex); } catch (std::exception & ex) { out << ex.what(); } catch (cancellation_exception) { out << "<cancelled>"; } catch (...) { out << "<unknown exception>"; } out << "\n"; } } auto children = m_ptr->m_children; auto used_names = m_ptr->m_used_names; l.unlock(); children.for_each([&] (name const & n, log_tree::node const & c) { for (unsigned i = 0; i < indent; i++) out << ' '; out << n; if (!used_names.contains(n)) out << " (unused)"; out << ": "; c.print_to(out, indent); }); } gtask log_tree::node::wait_for_finish() const { auto t = *this; return mk_dependency_task([t] (buffer<gtask> & deps) { t.for_each([&] (node const & n) { if (auto prod = n.get_producer()) deps.push_back(prod); return true; }); }); } bool log_tree::node::has_entry_now(std::function<bool(log_entry const &)> const & fn) const { // NOLINT bool res = false; for_each([&] (node const & n) { if (res) return false; for (auto & e : n.get_entries()) { if (fn(e)) { res = true; break; } } return !res; }); return res; } task<bool> log_tree::node::has_entry(std::function<bool(log_entry const &)> const & fn) const { // NOLINT auto t = *this; return task_builder<bool>([t, fn] { return t.has_entry_now(fn); }).depends_on(wait_for_finish()).build(); } LEAN_THREAD_PTR(log_tree::node, g_log_tree); scope_log_tree_core::scope_log_tree_core(log_tree::node * lt) : flet<log_tree::node *>(g_log_tree, lt) {} log_tree::node & logtree() { if (g_log_tree) { return *g_log_tree; } else { throw exception("no log tree in scope"); } } scope_log_tree::scope_log_tree(log_tree::node const & lt) : m_node(lt), m_scope(&m_node) { m_node.clear_entries(); } scope_log_tree::~scope_log_tree() { logtree().finish(); } scope_log_tree::scope_log_tree(std::string const & desc, pos_range const & pos) : scope_log_tree(logtree().mk_child({}, desc, {logtree().get_location().m_file_name, pos})) {} scope_log_tree::scope_log_tree(std::string const & desc) : scope_log_tree(logtree().mk_child({}, desc, logtree().get_location())) {} scope_log_tree::scope_log_tree() : scope_log_tree(std::string()) {} } <commit_msg>fix(util/log_tree): fix reference cycle between log_tree and tasks<commit_after>/* Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Gabriel Ebner */ #include "util/log_tree.h" #include "util/task_builder.h" #include <vector> #include <string> namespace lean { void log_tree::notify_core(std::vector<log_tree::event> const & events) { if (events.empty()) return; for (auto & l : m_listeners) l(events); } void log_tree::add_listener(log_tree::listener const & l) { unique_lock<mutex> lock(m_mutex); m_listeners.push_back(l); } log_tree::log_tree() { auto cell = new node_cell; cell->m_tree = this; m_root = node(cell); } log_tree::~log_tree() { std::vector<event> evs; m_root.detach_core(evs); m_root = node(); } void log_tree::print_to(std::ostream & out) const { get_root().print_to(out, 0); } void log_tree::print() const { print_to(std::cerr); } void log_tree::node::for_each(std::function<bool(log_tree::node const &)> const & fn) const { // NOLINT if (fn(*this)) { get_children().for_each([&] (name const &, log_tree::node const & c) { c.for_each(fn); }); } }; void log_tree::for_each(std::function<bool(log_tree::node const &)> const & fn) const { // NOLINT m_root.for_each(fn); }; void log_tree::node::detach_core(std::vector<log_tree::event> & events) const { if (m_ptr->m_detached) return; m_ptr->m_detached = true; m_ptr->m_children.for_each([&] (name const &, node const & c) { c.detach_core(events); }); for (auto & e : m_ptr->m_entries) events.push_back({ event::EntryRemoved, m_ptr, e }); if (m_ptr->m_producer) events.push_back({event::Finished, m_ptr, {}}); m_ptr->m_producer = nullptr; } void log_tree::node::notify(std::vector<log_tree::event> const & events, unique_lock<mutex> & l) const { if (!m_ptr->m_detached) { l.unlock(); m_ptr->m_tree->notify_core(events); } } log_tree::node log_tree::node::clone_core() const { auto copy = node(new node_cell); copy.m_ptr->m_children = m_ptr->m_children; m_ptr->m_children.clear(); copy.m_ptr->m_tree = m_ptr->m_tree; copy.m_ptr->m_detached = m_ptr->m_detached; copy.m_ptr->m_entries = m_ptr->m_entries; m_ptr->m_detached = true; return copy; } void log_tree::node::clear_entries() const { auto l = lock(); std::vector<event> events; for (auto & e : m_ptr->m_entries) { events.push_back({event::EntryRemoved, *this, std::move(e)}); } m_ptr->m_entries.clear(); notify(events, l); } void log_tree::node::add(log_entry const & entry) const { auto l = lock(); m_ptr->m_entries.push_back(entry); notify({{event::EntryAdded, *this, entry}}, l); } log_tree::node log_tree::node::mk_child(name n, std::string const & description, location const & loc, bool overwrite) { auto l = lock(); std::vector<event> events; if (!overwrite && (n.is_anonymous() || m_ptr->m_used_names.contains(n))) { for (unsigned i = 0;; i++) { name n_(n, i); if (!m_ptr->m_used_names.contains(n_)) { n = n_; break; } } } m_ptr->m_used_names.insert(n); node child; if (auto existing = m_ptr->m_children.find(n)) { child = existing->clone_core(); existing->detach_core(events); } else { child = node(new node_cell); child.m_ptr->m_tree = m_ptr->m_tree; child.m_ptr->m_detached = m_ptr->m_detached; } child.m_ptr->m_description = description; child.m_ptr->m_location = loc; m_ptr->m_children.insert(n, child); notify(events, l); return child; } void log_tree::node::set_producer(gtask const & prod) { auto l = lock(); if (m_ptr->m_detached) return; m_ptr->m_producer = prod; notify({{event::ProducerSet, *this, {}}}, l); } void log_tree::node::finish() const { auto l = lock(); std::vector<event> events; m_ptr->m_producer.reset(); buffer<pair<name, node>> to_delete; m_ptr->m_children.for_each([&] (name const & n, node const & c) { if (!m_ptr->m_used_names.contains(n)) to_delete.emplace_back(n, c); }); for (auto & c : to_delete) { m_ptr->m_children.erase(c.first); c.second.detach_core(events); } events.push_back({event::Finished, *this, {}}); notify(events, l); } std::vector<log_entry> log_tree::node::get_entries() const { auto l = lock(); return m_ptr->m_entries; } name_map<lean::log_tree::node> log_tree::node::get_children() const { auto l = lock(); return m_ptr->m_children; } void log_tree::node::remove_child(name const & n) const { auto l = lock(); if (auto c = m_ptr->m_children.find(n)) { m_ptr->m_children.erase(n); std::vector<event> events; c->detach_core(events); notify(events, l); } } name_map<log_tree::node> log_tree::node::get_used_children() const { auto l = lock(); name_map<node> used_children; m_ptr->m_used_names.for_each([&] (name const & n) { if (auto c = m_ptr->m_children.find(n)) { used_children.insert(n, *c); } }); return used_children; } void log_tree::node::reuse(name const & n) const { auto l = lock(); m_ptr->m_used_names.insert(n); } name_set log_tree::node::get_used_names() const { auto l = lock(); return m_ptr->m_used_names; } gtask log_tree::node::get_producer() const { auto l = lock(); return m_ptr->m_producer; } void log_tree::node::print() const { print_to(std::cerr, 0); } void log_tree::node::print_to(std::ostream & out, unsigned indent) const { indent += 2; auto l = lock(); auto begin = m_ptr->m_location.m_range.m_begin, end = m_ptr->m_location.m_range.m_end; out << m_ptr->m_location.m_file_name << ": " << begin.first << ":" << begin.second << " -- " << end.first << ":" << end.second << ": " << m_ptr->m_description << " (" << m_ptr->m_entries.size() << " entries, producer = " << std::hex << reinterpret_cast<uintptr_t>(m_ptr->m_producer.get()) << std::dec << ")" << std::endl; if (auto prod = m_ptr->m_producer) { if (auto ex = prod->peek_exception()) { for (unsigned i = 0; i < indent; i++) out << ' '; out << "producer threw exception: "; try { std::rethrow_exception(ex); } catch (std::exception & ex) { out << ex.what(); } catch (cancellation_exception) { out << "<cancelled>"; } catch (...) { out << "<unknown exception>"; } out << "\n"; } } auto children = m_ptr->m_children; auto used_names = m_ptr->m_used_names; l.unlock(); children.for_each([&] (name const & n, log_tree::node const & c) { for (unsigned i = 0; i < indent; i++) out << ' '; out << n; if (!used_names.contains(n)) out << " (unused)"; out << ": "; c.print_to(out, indent); }); } gtask log_tree::node::wait_for_finish() const { auto t = *this; return mk_dependency_task([t] (buffer<gtask> & deps) { t.for_each([&] (node const & n) { if (auto prod = n.get_producer()) deps.push_back(prod); return true; }); }); } bool log_tree::node::has_entry_now(std::function<bool(log_entry const &)> const & fn) const { // NOLINT bool res = false; for_each([&] (node const & n) { if (res) return false; for (auto & e : n.get_entries()) { if (fn(e)) { res = true; break; } } return !res; }); return res; } task<bool> log_tree::node::has_entry(std::function<bool(log_entry const &)> const & fn) const { // NOLINT auto t = *this; return task_builder<bool>([t, fn] { return t.has_entry_now(fn); }).depends_on(wait_for_finish()).build(); } LEAN_THREAD_PTR(log_tree::node, g_log_tree); scope_log_tree_core::scope_log_tree_core(log_tree::node * lt) : flet<log_tree::node *>(g_log_tree, lt) {} log_tree::node & logtree() { if (g_log_tree) { return *g_log_tree; } else { throw exception("no log tree in scope"); } } scope_log_tree::scope_log_tree(log_tree::node const & lt) : m_node(lt), m_scope(&m_node) { m_node.clear_entries(); } scope_log_tree::~scope_log_tree() { logtree().finish(); } scope_log_tree::scope_log_tree(std::string const & desc, pos_range const & pos) : scope_log_tree(logtree().mk_child({}, desc, {logtree().get_location().m_file_name, pos})) {} scope_log_tree::scope_log_tree(std::string const & desc) : scope_log_tree(logtree().mk_child({}, desc, logtree().get_location())) {} scope_log_tree::scope_log_tree() : scope_log_tree(std::string()) {} } <|endoftext|>
<commit_before>#include "rubykokuban/BindImage.hpp" #include "mruby.h" #include "mruby/class.h" #include "mruby/data.h" #include "mruby/string.h" #include "ofMain.h" namespace rubykokuban { namespace { void free(mrb_state *mrb, void *p) { if (p) { delete ((ofImage*)p); } } struct mrb_data_type data_type = { "rubykokuban_image", free }; mrb_value load(mrb_state *mrb, mrb_value self) { ofImage* obj = new ofImage(); mrb_value str; mrb_get_args(mrb, "S", &str); string filename(mrb_string_value_ptr(mrb, str)); obj->loadImage(filename); struct RData *data = mrb_data_object_alloc(mrb, mrb_class_ptr(self), obj, &data_type); return mrb_obj_value(data); } mrb_value draw(mrb_state *mrb, mrb_value self) { mrb_int x, y; mrb_get_args(mrb, "ii", &x, &y); ofImage* obj = (ofImage*)DATA_PTR(self); obj->draw(x, y); return mrb_nil_value(); } } //-------------------------------------------------------------------------------- void BindImage::Bind(mrb_state* mrb) { struct RClass *cc = mrb_define_class(mrb, "Image", mrb->object_class); mrb_define_class_method(mrb , cc, "load", load, MRB_ARGS_REQ(1)); mrb_define_method(mrb, cc, "draw", draw, MRB_ARGS_REQ(2));} } <commit_msg>Add Image class empty interface<commit_after>#include "rubykokuban/BindImage.hpp" #include "mruby.h" #include "mruby/class.h" #include "mruby/data.h" #include "mruby/string.h" #include "ofMain.h" namespace rubykokuban { namespace { void free(mrb_state *mrb, void *p) { if (p) { delete ((ofImage*)p); } } struct mrb_data_type data_type = { "rubykokuban_image", free }; mrb_value load(mrb_state *mrb, mrb_value self) { ofImage* obj = new ofImage(); mrb_value str; mrb_get_args(mrb, "S", &str); string filename(mrb_string_value_ptr(mrb, str)); obj->loadImage(filename); struct RData *data = mrb_data_object_alloc(mrb, mrb_class_ptr(self), obj, &data_type); return mrb_obj_value(data); } mrb_value grab_screen(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value save(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value color(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value set_color(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value resize(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value set_image_type(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value crop_bang(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value crop(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value rotate90(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value mirror(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value update(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value set_anchor_percent(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value set_anchor_point(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value reset_anchor(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value draw(mrb_state *mrb, mrb_value self) { mrb_int x, y; mrb_get_args(mrb, "ii", &x, &y); ofImage* obj = (ofImage*)DATA_PTR(self); obj->draw(x, y); return mrb_nil_value(); } mrb_value draw_sub(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value height(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } mrb_value width(mrb_state *mrb, mrb_value self) { return mrb_nil_value(); } } //-------------------------------------------------------------------------------- void BindImage::Bind(mrb_state* mrb) { struct RClass *cc = mrb_define_class(mrb, "Image", mrb->object_class); mrb_define_class_method(mrb , cc, "load", load, MRB_ARGS_REQ(1)); mrb_define_class_method(mrb , cc, "grab_screen", grab_screen, MRB_ARGS_REQ(4)); mrb_define_method(mrb, cc, "save", save, MRB_ARGS_ARG(2, 1)); mrb_define_method(mrb, cc, "color", color, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "set_color", set_color, MRB_ARGS_REQ(3)); mrb_define_method(mrb, cc, "resize", resize, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "set_image_type", set_image_type, MRB_ARGS_REQ(1)); mrb_define_method(mrb, cc, "crop", crop, MRB_ARGS_REQ(5)); mrb_define_method(mrb, cc, "crop!", crop_bang, MRB_ARGS_REQ(4)); mrb_define_method(mrb, cc, "rotate90", rotate90, MRB_ARGS_REQ(1)); mrb_define_method(mrb, cc, "mirror", mirror, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "update", update, MRB_ARGS_NONE()); mrb_define_method(mrb, cc, "set_anchor_percent", set_anchor_percent, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "set_anchor_point", set_anchor_point, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "reset_anchor", reset_anchor, MRB_ARGS_REQ(2)); mrb_define_method(mrb, cc, "draw", draw, MRB_ARGS_ARG(2, 3)); mrb_define_method(mrb, cc, "draw_sub", draw_sub, MRB_ARGS_ARG(6, 2)); mrb_define_method(mrb, cc, "height", height, MRB_ARGS_NONE()); mrb_define_method(mrb, cc, "width", width, MRB_ARGS_NONE()); } } <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <algorithm> /* for lower_bound() */ #include <cstring> #include <fstream> #include <curl/curl.h> #include <zorba/config.h> #ifdef WIN32 #include "system/globalenv.h" #endif /* WIN32 */ #ifndef ZORBA_WITH_REST #include "zorbaerrors/error_manager.h" #endif #include "zorbatypes/zstring.h" #include "fs_util.h" #include "less.h" #include "string_util.h" #include "uri_util.h" using namespace std; namespace zorba { namespace uri { /////////////////////////////////////////////////////////////////////////////// // This MUST be sorted. char const *const scheme_string[] = { "#none", "#unknown", "file", "ftp", "http", "https", "mailto" }; /////////////////////////////////////////////////////////////////////////////// ZORBA_DLL_PUBLIC extern signed char const hex2dec[] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ /* 0 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 1 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 2 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 3 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1, /* 4 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 5 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 6 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 7 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 8 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 9 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* A */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* B */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* C */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* D */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* E */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* F */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1 }; /** * Characters that need not be percent-encoded (%xx) in URIs. See RFC 3986. */ ZORBA_DLL_PUBLIC extern char const uri_safe[256] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ /* 0 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, /* 1 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, /* ! " # $ % & ' ( ) * + , - . / */ /* 2 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,1,1,0, /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */ /* 3 */ 1,1,1,1, 1,1,1,1, 1,1,0,0, 0,0,0,0, /* @ A B C D E F G H I J K L M N O */ /* 4 */ 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, /* P Q R S T U V W X Y Z [ \ ] ^ _ */ /* 5 */ 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,1, /* ` a b c d e f g h i j k l m n o */ /* 6 */ 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, /* p q r s t u v w x y z { | } ~ */ /* 7 */ 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,1,0, }; /////////////////////////////////////////////////////////////////////////////// static size_t curl_write_fn( void *ptr, size_t size, size_t nmemb, void *data ) { char const *const char_buf = static_cast<char const*>( ptr ); size_t const real_size = size * nmemb; iostream &stream = *static_cast<iostream*>( data ); stream.write( char_buf, static_cast<streamsize>( real_size ) ); // TODO: should check to see if write() failed return real_size; } void fetch( char const *uri, iostream &result ) { #ifdef ZORBA_WITH_REST // // Having cURL initialization wrapped by a class and using a singleton static // instance guarantees that cURL is initialized exactly once before use and // and also is cleaned-up at program termination (when destructors for static // objects are called). // struct curl_initializer { curl_initializer() { if ( CURLcode curl_code = curl_global_init( CURL_GLOBAL_ALL ) ) throw fetch_exception( curl_easy_strerror( curl_code ) ); } ~curl_initializer() { curl_global_cleanup(); } }; static curl_initializer initializer; CURL *curl = curl_easy_init(); curl_easy_setopt( curl, CURLOPT_URL, uri ); curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, curl_write_fn ); curl_easy_setopt( curl, CURLOPT_WRITEDATA, static_cast<void*>( &result ) ); // Tells cURL to fail silently if the HTTP code returned >= 400. curl_easy_setopt( curl, CURLOPT_FAILONERROR, 1 ); // Tells cURL to follow redirects. CURLOPT_MAXREDIRS is by default set to -1 // thus cURL will do an infinite number of redirects. curl_easy_setopt( curl, CURLOPT_FOLLOWLOCATION, 1 ); #ifndef ZORBA_VERIFY_PEER_SSL_CERTIFICATE curl_easy_setopt( curl, CURLOPT_SSL_VERIFYPEER, 0 ); // // CURLOPT_SSL_VERIFYHOST is left default, value 2, meaning verify that the // Common Name or Subject Alternate Name field in the certificate matches the // name of the server. // // tested with https://www.npr.org/rss/rss.php?id=1001 // about using ssl certs in curl: http://curl.haxx.se/docs/sslcerts.html #else # ifdef WIN32 // set the root CA certificates file path if ( GENV.g_curl_root_CA_certificates_path[0] ) curl_easy_setopt( curl, CURLOPT_CAINFO, GENV.g_curl_root_CA_certificates_path ); # endif /* WIN32 */ #endif /* ZORBA_VERIFY_PEER_SSL_CERTIFICATE */ // // Some servers don't like requests that are made without a user-agent field, // so we provide one. // curl_easy_setopt( curl, CURLOPT_USERAGENT, "libcurl-agent/1.0" ); CURLcode const curl_code = curl_easy_perform( curl ); if ( curl_code ) { // // Workaround for a problem in cURL: curl_easy_cleanup() fails if // curl_easy_perform() returned an error. // curl_easy_reset( curl ); } curl_easy_cleanup( curl ); if ( curl_code ) throw fetch_exception( curl_easy_strerror( curl_code ) ); #else ZORBA_ERROR_PARAM( XQP0004_SYSTEM_NOT_SUPPORTED, "HTTP GET" , "" ); #endif /* ZORBA_WITH_REST */ } void fetch_to_path_impl( char const *uri, char *path, bool *is_temp ) { zstring zpath; bool temp = false; switch ( get_scheme( uri ) ) { case file: case none: zpath = fs::get_normalized_path( uri ); break; default: fs::get_temp_file( &zpath ); fstream stream( zpath.c_str() ); fetch( uri, stream ); temp = true; break; } ::strncpy( path, zpath.c_str(), MAX_PATH ); path[ MAX_PATH - 1 ] = '\0'; if ( is_temp ) *is_temp = temp; } scheme get_scheme( char const *uri ) { zstring scheme_name; if ( split( uri, ':', &scheme_name, NULL ) ) { static char const *const *const begin = scheme_string; static char const *const *const end = scheme_string + sizeof( scheme_string ) / sizeof( char* ); char const *const s = scheme_name.c_str(); char const *const *const entry = ::lower_bound( begin, end, s, less<char const*>() ); return entry != end && ::strcmp( s, *entry ) == 0 ? static_cast<scheme>( entry - begin ) : unknown; } return none; } /////////////////////////////////////////////////////////////////////////////// } // namespace uri } // namespace zorba /* vim:set et sw=2 ts=2: */ <commit_msg>Added #ifdef ZORBA_WITH_REST.<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <algorithm> /* for lower_bound() */ #include <cstring> #include <fstream> #include <zorba/config.h> #ifdef ZORBA_WITH_REST #include <curl/curl.h> #endif #ifdef WIN32 #include "system/globalenv.h" #endif /* WIN32 */ #ifndef ZORBA_WITH_REST #include "zorbaerrors/error_manager.h" #endif #include "zorbatypes/zstring.h" #include "fs_util.h" #include "less.h" #include "string_util.h" #include "uri_util.h" using namespace std; namespace zorba { namespace uri { /////////////////////////////////////////////////////////////////////////////// // This MUST be sorted. char const *const scheme_string[] = { "#none", "#unknown", "file", "ftp", "http", "https", "mailto" }; /////////////////////////////////////////////////////////////////////////////// ZORBA_DLL_PUBLIC extern signed char const hex2dec[] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ /* 0 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 1 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 2 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 3 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1, /* 4 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 5 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 6 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 7 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 8 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 9 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* A */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* B */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* C */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* D */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* E */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* F */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1 }; /** * Characters that need not be percent-encoded (%xx) in URIs. See RFC 3986. */ ZORBA_DLL_PUBLIC extern char const uri_safe[256] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ /* 0 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, /* 1 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, /* ! " # $ % & ' ( ) * + , - . / */ /* 2 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,1,1,0, /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */ /* 3 */ 1,1,1,1, 1,1,1,1, 1,1,0,0, 0,0,0,0, /* @ A B C D E F G H I J K L M N O */ /* 4 */ 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, /* P Q R S T U V W X Y Z [ \ ] ^ _ */ /* 5 */ 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,1, /* ` a b c d e f g h i j k l m n o */ /* 6 */ 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, /* p q r s t u v w x y z { | } ~ */ /* 7 */ 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,1,0, }; /////////////////////////////////////////////////////////////////////////////// static size_t curl_write_fn( void *ptr, size_t size, size_t nmemb, void *data ) { char const *const char_buf = static_cast<char const*>( ptr ); size_t const real_size = size * nmemb; iostream &stream = *static_cast<iostream*>( data ); stream.write( char_buf, static_cast<streamsize>( real_size ) ); // TODO: should check to see if write() failed return real_size; } void fetch( char const *uri, iostream &result ) { #ifdef ZORBA_WITH_REST // // Having cURL initialization wrapped by a class and using a singleton static // instance guarantees that cURL is initialized exactly once before use and // and also is cleaned-up at program termination (when destructors for static // objects are called). // struct curl_initializer { curl_initializer() { if ( CURLcode curl_code = curl_global_init( CURL_GLOBAL_ALL ) ) throw fetch_exception( curl_easy_strerror( curl_code ) ); } ~curl_initializer() { curl_global_cleanup(); } }; static curl_initializer initializer; CURL *curl = curl_easy_init(); curl_easy_setopt( curl, CURLOPT_URL, uri ); curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, curl_write_fn ); curl_easy_setopt( curl, CURLOPT_WRITEDATA, static_cast<void*>( &result ) ); // Tells cURL to fail silently if the HTTP code returned >= 400. curl_easy_setopt( curl, CURLOPT_FAILONERROR, 1 ); // Tells cURL to follow redirects. CURLOPT_MAXREDIRS is by default set to -1 // thus cURL will do an infinite number of redirects. curl_easy_setopt( curl, CURLOPT_FOLLOWLOCATION, 1 ); #ifndef ZORBA_VERIFY_PEER_SSL_CERTIFICATE curl_easy_setopt( curl, CURLOPT_SSL_VERIFYPEER, 0 ); // // CURLOPT_SSL_VERIFYHOST is left default, value 2, meaning verify that the // Common Name or Subject Alternate Name field in the certificate matches the // name of the server. // // tested with https://www.npr.org/rss/rss.php?id=1001 // about using ssl certs in curl: http://curl.haxx.se/docs/sslcerts.html #else # ifdef WIN32 // set the root CA certificates file path if ( GENV.g_curl_root_CA_certificates_path[0] ) curl_easy_setopt( curl, CURLOPT_CAINFO, GENV.g_curl_root_CA_certificates_path ); # endif /* WIN32 */ #endif /* ZORBA_VERIFY_PEER_SSL_CERTIFICATE */ // // Some servers don't like requests that are made without a user-agent field, // so we provide one. // curl_easy_setopt( curl, CURLOPT_USERAGENT, "libcurl-agent/1.0" ); CURLcode const curl_code = curl_easy_perform( curl ); if ( curl_code ) { // // Workaround for a problem in cURL: curl_easy_cleanup() fails if // curl_easy_perform() returned an error. // curl_easy_reset( curl ); } curl_easy_cleanup( curl ); if ( curl_code ) throw fetch_exception( curl_easy_strerror( curl_code ) ); #else ZORBA_ERROR_PARAM( XQP0004_SYSTEM_NOT_SUPPORTED, "HTTP GET" , "" ); #endif /* ZORBA_WITH_REST */ } void fetch_to_path_impl( char const *uri, char *path, bool *is_temp ) { zstring zpath; bool temp = false; switch ( get_scheme( uri ) ) { case file: case none: zpath = fs::get_normalized_path( uri ); break; default: fs::get_temp_file( &zpath ); fstream stream( zpath.c_str() ); fetch( uri, stream ); temp = true; break; } ::strncpy( path, zpath.c_str(), MAX_PATH ); path[ MAX_PATH - 1 ] = '\0'; if ( is_temp ) *is_temp = temp; } scheme get_scheme( char const *uri ) { zstring scheme_name; if ( split( uri, ':', &scheme_name, NULL ) ) { static char const *const *const begin = scheme_string; static char const *const *const end = scheme_string + sizeof( scheme_string ) / sizeof( char* ); char const *const s = scheme_name.c_str(); char const *const *const entry = ::lower_bound( begin, end, s, less<char const*>() ); return entry != end && ::strcmp( s, *entry ) == 0 ? static_cast<scheme>( entry - begin ) : unknown; } return none; } /////////////////////////////////////////////////////////////////////////////// } // namespace uri } // namespace zorba /* vim:set et sw=2 ts=2: */ <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "PressureAction.h" #include "Factory.h" #include "FEProblem.h" #include "Conversion.h" registerMooseAction("TensorMechanicsApp", PressureAction, "add_bc"); InputParameters PressureAction::validParams() { InputParameters params = Action::validParams(); params.addClassDescription("Set up Pressure boundary conditions"); params.addRequiredParam<std::vector<BoundaryName>>( "boundary", "The list of boundary IDs from the mesh where the pressure will be applied"); params.addParam<std::vector<VariableName>>( "displacements", "The displacements appropriate for the simulation geometry and coordinate system"); params.addParam<std::vector<AuxVariableName>>("save_in_disp_x", "The save_in variables for x displacement"); params.addParam<std::vector<AuxVariableName>>("save_in_disp_y", "The save_in variables for y displacement"); params.addParam<std::vector<AuxVariableName>>("save_in_disp_z", "The save_in variables for z displacement"); params.addParam<Real>("factor", 1.0, "The factor to use in computing the pressure"); params.addParam<bool>("use_displaced_mesh", true, "Whether to use the displaced mesh."); params.addParam<Real>("hht_alpha", 0, "alpha parameter for mass dependent numerical damping induced " "by HHT time integration scheme"); params.addDeprecatedParam<Real>( "alpha", "alpha parameter for HHT time integration", "Please use hht_alpha"); params.addParam<FunctionName>("function", "The function that describes the pressure"); params.addParam<bool>("use_automatic_differentiation", false, "Flag to use automatic differentiation (AD) objects when possible"); return params; } PressureAction::PressureAction(const InputParameters & params) : Action(params), _use_ad(getParam<bool>("use_automatic_differentiation")) { _save_in_vars.push_back(getParam<std::vector<AuxVariableName>>("save_in_disp_x")); _save_in_vars.push_back(getParam<std::vector<AuxVariableName>>("save_in_disp_y")); _save_in_vars.push_back(getParam<std::vector<AuxVariableName>>("save_in_disp_z")); _has_save_in_vars.push_back(params.isParamValid("save_in_disp_x")); _has_save_in_vars.push_back(params.isParamValid("save_in_disp_y")); _has_save_in_vars.push_back(params.isParamValid("save_in_disp_z")); } void PressureAction::act() { std::string ad_prepend = ""; if (_use_ad) ad_prepend = "AD"; std::string kernel_name = ad_prepend + "Pressure"; std::vector<VariableName> displacements = getParam<std::vector<VariableName>>("displacements"); // Create pressure BCs for (unsigned int i = 0; i < displacements.size(); ++i) { // Create unique kernel name for each of the components std::string unique_kernel_name = kernel_name + "_" + _name + "_" + Moose::stringify(i); InputParameters params = _factory.getValidParams(kernel_name); params.applyParameters(parameters(), {"factor"}); params.set<bool>("use_displaced_mesh") = getParam<bool>("use_displaced_mesh"); params.set<Real>("alpha") = isParamValid("alpha") ? getParam<Real>("alpha") : getParam<Real>("hht_alpha"); if (_use_ad) params.set<unsigned int>("component") = i; params.set<NonlinearVariableName>("variable") = displacements[i]; if (_has_save_in_vars[i]) params.set<std::vector<AuxVariableName>>("save_in") = _save_in_vars[i]; if (_use_ad) params.set<Real>("constant") = getParam<Real>("factor"); else params.set<Real>("factor") = getParam<Real>("factor"); _problem->addBoundaryCondition(kernel_name, unique_kernel_name, params); } } <commit_msg>'component' is a deprecated parameter in Pressure BC (#15915)<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "PressureAction.h" #include "Factory.h" #include "FEProblem.h" #include "Conversion.h" registerMooseAction("TensorMechanicsApp", PressureAction, "add_bc"); InputParameters PressureAction::validParams() { InputParameters params = Action::validParams(); params.addClassDescription("Set up Pressure boundary conditions"); params.addRequiredParam<std::vector<BoundaryName>>( "boundary", "The list of boundary IDs from the mesh where the pressure will be applied"); params.addParam<std::vector<VariableName>>( "displacements", "The displacements appropriate for the simulation geometry and coordinate system"); params.addParam<std::vector<AuxVariableName>>("save_in_disp_x", "The save_in variables for x displacement"); params.addParam<std::vector<AuxVariableName>>("save_in_disp_y", "The save_in variables for y displacement"); params.addParam<std::vector<AuxVariableName>>("save_in_disp_z", "The save_in variables for z displacement"); params.addParam<Real>("factor", 1.0, "The factor to use in computing the pressure"); params.addParam<bool>("use_displaced_mesh", true, "Whether to use the displaced mesh."); params.addParam<Real>("hht_alpha", 0, "alpha parameter for mass dependent numerical damping induced " "by HHT time integration scheme"); params.addDeprecatedParam<Real>( "alpha", "alpha parameter for HHT time integration", "Please use hht_alpha"); params.addParam<FunctionName>("function", "The function that describes the pressure"); params.addParam<bool>("use_automatic_differentiation", false, "Flag to use automatic differentiation (AD) objects when possible"); return params; } PressureAction::PressureAction(const InputParameters & params) : Action(params), _use_ad(getParam<bool>("use_automatic_differentiation")) { _save_in_vars.push_back(getParam<std::vector<AuxVariableName>>("save_in_disp_x")); _save_in_vars.push_back(getParam<std::vector<AuxVariableName>>("save_in_disp_y")); _save_in_vars.push_back(getParam<std::vector<AuxVariableName>>("save_in_disp_z")); _has_save_in_vars.push_back(params.isParamValid("save_in_disp_x")); _has_save_in_vars.push_back(params.isParamValid("save_in_disp_y")); _has_save_in_vars.push_back(params.isParamValid("save_in_disp_z")); } void PressureAction::act() { std::string ad_prepend = ""; if (_use_ad) ad_prepend = "AD"; std::string kernel_name = ad_prepend + "Pressure"; std::vector<VariableName> displacements = getParam<std::vector<VariableName>>("displacements"); // Create pressure BCs for (unsigned int i = 0; i < displacements.size(); ++i) { // Create unique kernel name for each of the components std::string unique_kernel_name = kernel_name + "_" + _name + "_" + Moose::stringify(i); InputParameters params = _factory.getValidParams(kernel_name); params.applyParameters(parameters(), {"factor"}); params.set<bool>("use_displaced_mesh") = getParam<bool>("use_displaced_mesh"); params.set<Real>("alpha") = isParamValid("alpha") ? getParam<Real>("alpha") : getParam<Real>("hht_alpha"); params.set<NonlinearVariableName>("variable") = displacements[i]; if (_has_save_in_vars[i]) params.set<std::vector<AuxVariableName>>("save_in") = _save_in_vars[i]; if (_use_ad) params.set<Real>("constant") = getParam<Real>("factor"); else params.set<Real>("factor") = getParam<Real>("factor"); _problem->addBoundaryCondition(kernel_name, unique_kernel_name, params); } } <|endoftext|>
<commit_before>#include <jni.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <srt/srt.h> #define DEBUG #ifdef DEBUG #include <android/log.h> #define LOG_TAG "SRT-JNI" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__) #else #define LOGI(...) #define LOGD(...) #define LOGE(...) #define LOGW(...) #endif /** * JNI のパッケージ名、クラス名を定義. */ #define JNI_METHOD_NAME(name) Java_org_deviceconnect_android_libsrt_NdkHelper_##name #ifdef __cplusplus extern "C" { #endif JNIEXPORT void JNICALL JNI_METHOD_NAME(startup)(JNIEnv *env, jclass clazz) { LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_startup()"); srt_startup(); } JNIEXPORT void JNICALL JNI_METHOD_NAME(cleanup)(JNIEnv *env, jclass clazz) { LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_cleanup()"); srt_cleanup(); } JNIEXPORT jlong JNICALL JNI_METHOD_NAME(createSrtSocket)(JNIEnv *env, jclass clazz, jstring address, jint port, jint backlog) { LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_createSrtSocket()"); int yes = 1; int st; int ss = srt_create_socket(); if (ss == SRT_ERROR) { LOGE("srt_socket: %s", srt_getlasterror_str()); return -1; } const char *addressString = env->GetStringUTFChars(address, nullptr); struct sockaddr_in sa; sa.sin_family = AF_INET; sa.sin_port = htons(port); if (inet_pton(AF_INET, addressString, &sa.sin_addr) != 1) { LOGE("inet_pton error."); env->ReleaseStringUTFChars(address, addressString); return -1; } env->ReleaseStringUTFChars(address, addressString); srt_setsockflag(ss, SRTO_RCVSYN, &yes, sizeof yes); st = srt_bind(ss, (struct sockaddr*)&sa, sizeof sa); if (st == SRT_ERROR) { LOGE("srt_bind: %s", srt_getlasterror_str()); return -1; } st = srt_listen(ss, backlog); if (st == SRT_ERROR) { LOGE("srt_listen: %s\n", srt_getlasterror_str()); return -1; } return ss; } JNIEXPORT void JNICALL JNI_METHOD_NAME(closeSrtSocket)(JNIEnv *env, jclass clazz, jlong ptr) { LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_closeSrtSocket()"); int st = srt_close((int) ptr); if (st == SRT_ERROR) { LOGE("srt_close: %s\n", srt_getlasterror_str()); } } JNIEXPORT void JNICALL JNI_METHOD_NAME(accept)(JNIEnv *env, jclass clazz, jlong ptr, jobject socket) { LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_accept()"); struct sockaddr addr; int addrlen; int st = srt_accept((int) ptr, &addr, &addrlen); if (st == SRT_ERROR) { LOGE("srt_accept: %s\n", srt_getlasterror_str()); return; } // クライアント側のソケットへのポインタ jclass socketCls = env->FindClass("org/deviceconnect/android/libsrt/SRTSocket"); jfieldID socketPtr = env->GetFieldID(socketCls, "mNativePtr", "J"); env->SetLongField(socket, socketPtr, st); // クライアントのIPアドレス char format[] = "%d.%d.%d.%d"; char buf[15]; sprintf(buf, format, addr.sa_data[2], addr.sa_data[3], addr.sa_data[4], addr.sa_data[5]); jstring address = env->NewStringUTF(buf); jfieldID addressField = env->GetFieldID(socketCls, "mSocketAddress", "Ljava/lang/String;"); env->SetObjectField(socket, addressField, address); } JNIEXPORT int JNICALL JNI_METHOD_NAME(sendMessage)(JNIEnv *env, jclass clazz, jlong ptr, jbyteArray byteArray, jint offset, jint length) { jboolean isCopy; jbyte* data = env->GetByteArrayElements(byteArray, &isCopy); if (data == nullptr) { return -1; } int result = srt_sendmsg((int) ptr, (const char *) &data[offset], length, -1, 0); if (result < SRT_ERROR) { LOGE("srt_send: %s\n", srt_getlasterror_str()); } env->ReleaseByteArrayElements(byteArray, data, 0); return result; } JNIEXPORT int JNICALL JNI_METHOD_NAME(recvMessage)(JNIEnv *env, jclass clazz, jlong ptr, jbyteArray byteArray, jint length) { jboolean isCopy; jbyte* data = env->GetByteArrayElements(byteArray, &isCopy); if (data == nullptr) { return -1; } int result = srt_recvmsg((int) ptr, (char *) data, length); if (result < SRT_ERROR) { LOGE("srt_send: %s\n", srt_getlasterror_str()); } env->ReleaseByteArrayElements(byteArray, data, 0); return result; } JNIEXPORT void JNICALL JNI_METHOD_NAME(dumpStats)(JNIEnv *env, jclass clazz, jlong ptr) { LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_dumpStats(): ptr=%d", ptr); SRT_TRACEBSTATS stats; int result = srt_bstats((int) ptr, &stats, 0); if (result == SRT_ERROR) { return; } LOGD("dumpStats: pktSentTotal=%ld, pktRetransTotal=%d, pktSndLossTotal=%d", stats.pktSentTotal, stats.pktRetransTotal, stats.pktSndLossTotal); LOGD("dumpStats: mbpsBandwidth=%f, mbpsMaxBW=%f, byteAvailSndBuf=%d", stats.mbpsBandwidth, stats.mbpsMaxBW, stats.byteAvailSndBuf); } #ifdef __cplusplus } #endif <commit_msg>SRTO_MAXBW の値を 0 に設定し、SRTO_INPUTBW と SRTO_OHEADBW の値でBandwidth の値を設定するように修正<commit_after>#include <jni.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <srt/srt.h> #define DEBUG #ifdef DEBUG #include <android/log.h> #define LOG_TAG "SRT-JNI" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__) #else #define LOGI(...) #define LOGD(...) #define LOGE(...) #define LOGW(...) #endif /** * JNI のパッケージ名、クラス名を定義. */ #define JNI_METHOD_NAME(name) Java_org_deviceconnect_android_libsrt_NdkHelper_##name #ifdef __cplusplus extern "C" { #endif JNIEXPORT void JNICALL JNI_METHOD_NAME(startup)(JNIEnv *env, jclass clazz) { LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_startup()"); srt_startup(); } JNIEXPORT void JNICALL JNI_METHOD_NAME(cleanup)(JNIEnv *env, jclass clazz) { LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_cleanup()"); srt_cleanup(); } JNIEXPORT jlong JNICALL JNI_METHOD_NAME(createSrtSocket)(JNIEnv *env, jclass clazz, jstring address, jint port, jint backlog) { LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_createSrtSocket()"); int result; int server_socket = srt_create_socket(); if (server_socket == SRT_INVALID_SOCK) { LOGE("srt_socket: %s", srt_getlasterror_str()); return -1; } const char *addressString = env->GetStringUTFChars(address, nullptr); struct sockaddr_in sa; sa.sin_family = AF_INET; sa.sin_port = htons(port); if (inet_pton(AF_INET, addressString, &sa.sin_addr) != 1) { LOGE("inet_pton error."); env->ReleaseStringUTFChars(address, addressString); srt_close(server_socket); return -1; } env->ReleaseStringUTFChars(address, addressString); int64_t maxBW = 0; srt_setsockflag(server_socket, SRTO_MAXBW, &maxBW, sizeof maxBW); result = srt_bind(server_socket, (struct sockaddr *) &sa, sizeof sa); if (result == SRT_ERROR) { LOGE("srt_bind: %s", srt_getlasterror_str()); srt_close(server_socket); return -1; } result = srt_listen(server_socket, backlog); if (result == SRT_ERROR) { LOGE("srt_listen: %s\n", srt_getlasterror_str()); srt_close(server_socket); return -1; } return server_socket; } JNIEXPORT void JNICALL JNI_METHOD_NAME(closeSrtSocket)(JNIEnv *env, jclass clazz, jlong ptr) { LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_closeSrtSocket()"); int result = srt_close((int) ptr); if (result == SRT_ERROR) { LOGE("srt_close: %s\n", srt_getlasterror_str()); } } JNIEXPORT void JNICALL JNI_METHOD_NAME(accept)(JNIEnv *env, jclass clazz, jlong ptr, jobject socket) { LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_accept()"); struct sockaddr addr; int addrlen; int accepted_socket = srt_accept((int) ptr, &addr, &addrlen); if (accepted_socket == SRT_INVALID_SOCK) { LOGE("srt_accept: %s\n", srt_getlasterror_str()); return; } int64_t inputBW = 2 * 1024 * 1024; int ohdadBW = 50; srt_setsockflag(accepted_socket, SRTO_INPUTBW, &inputBW, sizeof inputBW); srt_setsockflag(accepted_socket, SRTO_OHEADBW, &ohdadBW, sizeof ohdadBW); // クライアント側のソケットへのポインタ jclass socketCls = env->FindClass("org/deviceconnect/android/libsrt/SRTSocket"); jfieldID socketPtr = env->GetFieldID(socketCls, "mNativePtr", "J"); env->SetLongField(socket, socketPtr, accepted_socket); // クライアントのIPアドレス char buf[15]; sprintf(buf, "%d.%d.%d.%d", addr.sa_data[2], addr.sa_data[3], addr.sa_data[4], addr.sa_data[5]); jstring address = env->NewStringUTF(buf); jfieldID addressField = env->GetFieldID(socketCls, "mSocketAddress", "Ljava/lang/String;"); env->SetObjectField(socket, addressField, address); } JNIEXPORT jint JNICALL JNI_METHOD_NAME(sendMessage)(JNIEnv *env, jclass clazz, jlong ptr, jbyteArray byteArray, jint offset, jint length) { jboolean isCopy; jbyte* data = env->GetByteArrayElements(byteArray, &isCopy); if (data == nullptr) { return -1; } SRT_MSGCTRL mc = srt_msgctrl_default; int result = srt_sendmsg2((int) ptr, (const char *) &data[offset], length, &mc); if (result <= SRT_ERROR) { LOGE("srt_send: %s\n", srt_getlasterror_str()); } env->ReleaseByteArrayElements(byteArray, data, 0); return result; } JNIEXPORT jint JNICALL JNI_METHOD_NAME(recvMessage)(JNIEnv *env, jclass clazz, jlong ptr, jbyteArray byteArray, jint length) { jboolean isCopy; jbyte* data = env->GetByteArrayElements(byteArray, &isCopy); if (data == nullptr) { return -1; } int result = srt_recvmsg((int) ptr, (char *) data, length); if (result <= SRT_ERROR) { LOGE("srt_send: %s\n", srt_getlasterror_str()); } env->ReleaseByteArrayElements(byteArray, data, 0); return result; } JNIEXPORT void JNICALL JNI_METHOD_NAME(dumpStats)(JNIEnv *env, jclass clazz, jlong ptr) { LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_dumpStats(): ptr=%d", ptr); SRT_TRACEBSTATS stats; int result = srt_bstats((int) ptr, &stats, 0); if (result == SRT_ERROR) { return; } LOGD("dumpStats: pktSentTotal=%ld, pktSndLossTotal=%d, pktSndDropTotal=%d, pktRetransTotal=%d", stats.pktSentTotal, stats.pktSndLossTotal, stats.pktSndDropTotal, stats.pktRetransTotal); LOGD("dumpStats: mbpsBandwidth=%f, mbpsMaxBW=%f, byteAvailSndBuf=%d", stats.mbpsBandwidth, stats.mbpsMaxBW, stats.byteAvailSndBuf); } #ifdef __cplusplus } #endif <|endoftext|>
<commit_before>/* vi:set ts=8 sts=8 sw=8 noet: * * Practical Music Search * Copyright (c) 2006-2011 Kim Tore Jensen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "window.h" #include "curses.h" #include "config.h" extern Windowmanager * wm; extern Curses * curses; extern Config * config; void Window::draw() { unsigned int i, h; if (!rect || !visible()) return; need_draw = false; h = height(); for (i = 0; i <= h; i++) drawline(i); } inline void Window::qdraw() { need_draw = true; } void Window::clear() { curses->wipe(rect, config->colors.standard); } unsigned int Window::height() { if (!rect) return 0; return rect->bottom - rect->top; } Wmain::Wmain() { position = 0; cursor = 0; } unsigned int Wmain::height() { if (!rect) return 0; return rect->bottom - rect->top - (config->show_window_title ? 1 : 0); } void Wmain::draw() { if (!rect || !visible()) return; if (config->show_window_title) { curses->clearline(rect, 0, config->colors.windowtitle); curses->print(rect, config->colors.windowtitle, 0, 0, title.c_str()); } Window::draw(); wm->readout->draw(); } void Wmain::scroll_window(int offset) { int limit = static_cast<int>(content_size() - height() - 1); if (limit < 0) limit = 0; offset = position + offset; if (offset < 0) { offset = 0; curses->bell(); } if (offset > limit) { offset = limit; curses->bell(); } if ((int)position == offset) return; position = offset; if (config->scroll_mode == SCROLL_MODE_NORMAL) { if (cursor < position) cursor = position; else if (cursor > position + height()) cursor = position + height(); } else if (config->scroll_mode == SCROLL_MODE_CENTERED) { cursor = position + (height() / 2); } qdraw(); } void Wmain::set_position(unsigned int absolute) { scroll_window(absolute - position); } void Wmain::move_cursor(int offset) { offset = cursor + offset; if (offset < 0) { offset = 0; curses->bell(); } else if (offset > (int)content_size() - 1) { offset = content_size() - 1; curses->bell(); } if ((int)cursor == offset) return; cursor = offset; if (config->scroll_mode == SCROLL_MODE_NORMAL) { if (cursor < position) set_position(cursor); else if (cursor > position + height()) set_position(cursor - height()); } else if (config->scroll_mode == SCROLL_MODE_CENTERED) { offset = height() / 2; if ((int)cursor < offset) position = 0; else if (cursor + offset >= content_size()) { if (content_size() > height()) position = content_size() - height() - 1; else position = 0; } else position = cursor - offset; } qdraw(); } void Wmain::set_cursor(unsigned int absolute) { move_cursor(absolute - cursor); } bool Wmain::visible() { return wm->active == this; } <commit_msg>Fix centered scroll mode scroll bug.<commit_after>/* vi:set ts=8 sts=8 sw=8 noet: * * Practical Music Search * Copyright (c) 2006-2011 Kim Tore Jensen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <math.h> #include "window.h" #include "curses.h" #include "config.h" extern Windowmanager * wm; extern Curses * curses; extern Config * config; void Window::draw() { unsigned int i, h; if (!rect || !visible()) return; need_draw = false; h = height(); for (i = 0; i <= h; i++) drawline(i); } inline void Window::qdraw() { need_draw = true; } void Window::clear() { curses->wipe(rect, config->colors.standard); } unsigned int Window::height() { if (!rect) return 0; return rect->bottom - rect->top; } Wmain::Wmain() { position = 0; cursor = 0; } unsigned int Wmain::height() { if (!rect) return 0; return rect->bottom - rect->top - (config->show_window_title ? 1 : 0); } void Wmain::draw() { if (!rect || !visible()) return; if (config->show_window_title) { curses->clearline(rect, 0, config->colors.windowtitle); curses->print(rect, config->colors.windowtitle, 0, 0, title.c_str()); } Window::draw(); wm->readout->draw(); } void Wmain::scroll_window(int offset) { int limit = static_cast<int>(content_size() - height() - 1); if (limit < 0) limit = 0; offset = position + offset; if (offset < 0) { offset = 0; curses->bell(); } if (offset > limit) { offset = limit; curses->bell(); } if ((int)position == offset) return; position = offset; if (config->scroll_mode == SCROLL_MODE_NORMAL) { if (cursor < position) cursor = position; else if (cursor > position + height()) cursor = position + height(); } else if (config->scroll_mode == SCROLL_MODE_CENTERED) { cursor = position + (height() / 2); } qdraw(); } void Wmain::set_position(unsigned int absolute) { scroll_window(absolute - position); } void Wmain::move_cursor(int offset) { offset = cursor + offset; if (offset < 0) { offset = 0; curses->bell(); } else if (offset > (int)content_size() - 1) { offset = content_size() - 1; curses->bell(); } if ((int)cursor == offset) return; cursor = offset; if (config->scroll_mode == SCROLL_MODE_NORMAL) { if (cursor < position) set_position(cursor); else if (cursor > position + height()) set_position(cursor - height()); } else if (config->scroll_mode == SCROLL_MODE_CENTERED) { offset = floorl(height() / 2); if ((int)cursor < offset) { position = 0; } else if (cursor + offset + 1 >= content_size()) { if (content_size() > height()) position = content_size() - height() - 1; else position = 0; } else { position = cursor - offset; } } qdraw(); } void Wmain::set_cursor(unsigned int absolute) { move_cursor(absolute - cursor); } bool Wmain::visible() { return wm->active == this; } <|endoftext|>
<commit_before>#include "Updater.h" #pragma comment(lib, "Version.lib") #pragma comment(lib, "wininet.lib") #include <Windows.h> #include <WinInet.h> #include <sstream> #include "Settings.h" #include "StringUtils.h" #include "Logger.h" const std::wstring Updater::LATEST_URL = L"https://3rvx.com/releases/latest_version"; const std::wstring Updater::DOWNLOAD_URL = L"https://3rvx.com/releases/"; bool Updater::NewerVersionAvailable() { std::pair<int, int> remote = RemoteVersion(); std::pair<int, int> local = MainAppVersion(); CLOG(L"Remote version: %d.%d\n Local version: %d.%d", remote.first, remote.second, local.first, local.second); if (remote.first == 0 && remote.second == 0 || local.first == 0 && local.second == 0) { /* One of the version checks failed, so say that there is no new * version. No need to bother the user with (hopefully) temporary * errors. */ return false; } if (remote.first > local.first || remote.second > local.second) { return true; } return false; } std::pair<int, int> Updater::MainAppVersion() { std::wstring mainExe = Settings::Instance()->MainApp(); BOOL result; std::pair<int, int> version = std::pair<int, int>(0, 0); DWORD size = GetFileVersionInfoSize(mainExe.c_str(), NULL); if (size == 0) { CLOG(L"Could not determine version info size"); return version; } unsigned char *block = new unsigned char[size]; result = GetFileVersionInfo(mainExe.c_str(), NULL, size, block); if (result == 0) { CLOG(L"Failed to retrieve file version info"); delete[] block; return version; } unsigned int dataSz; VS_FIXEDFILEINFO *vers; result = VerQueryValue(block, L"\\", (void **) &vers, &dataSz); if (result == 0) { CLOG(L"Could not query root block for version info"); delete[] block; return version; } if (vers->dwSignature != 0xFEEF04BD) { CLOG(L"Invalid version signature"); delete[] block; return version; } unsigned long verl = vers->dwProductVersionMS; int hi = (verl >> 16) & 0xFF; int lo = verl & 0xFF; version = std::pair<int, int>(hi, lo); delete[] block; return version; } std::wstring Updater::MainAppVersionString() { std::pair<int, int> vers = MainAppVersion(); return std::to_wstring(vers.first) + L"." + std::to_wstring(vers.second); } std::pair<int, int> Updater::RemoteVersion() { HINTERNET internet = InternetOpen( L"3RVX Updater", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL); HINTERNET connection = InternetOpenUrl( internet, LATEST_URL.c_str(), NULL, 0, INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_PRAGMA_NOCACHE, 0); if (connection == NULL) { CLOG(L"Could not connect to URL!"); return std::pair<int, int>(0, 0); } std::string str(""); char buf[32]; DWORD read; while (InternetReadFile(connection, buf, 16, &read) == TRUE && read != 0) { str.append(buf); } /* Only consider the first line */ str.erase(str.find('\n'), str.size() - 1); int dot = str.find('.'); std::string major = str.substr(0, dot); std::string minor = str.substr(dot + 1, str.size()); std::pair<int, int> version; std::istringstream ss; ss = std::istringstream(major); ss >> version.first; ss = std::istringstream(minor); ss >> version.second; return version; }<commit_msg>Redefine the latest version URL<commit_after>#include "Updater.h" #pragma comment(lib, "Version.lib") #pragma comment(lib, "wininet.lib") #include <Windows.h> #include <WinInet.h> #include <sstream> #include "Settings.h" #include "StringUtils.h" #include "Logger.h" const std::wstring Updater::LATEST_URL = DOWNLOAD_URL + L"latest_version"; const std::wstring Updater::DOWNLOAD_URL = L"https://3rvx.com/releases/"; bool Updater::NewerVersionAvailable() { std::pair<int, int> remote = RemoteVersion(); std::pair<int, int> local = MainAppVersion(); CLOG(L"Remote version: %d.%d\n Local version: %d.%d", remote.first, remote.second, local.first, local.second); if (remote.first == 0 && remote.second == 0 || local.first == 0 && local.second == 0) { /* One of the version checks failed, so say that there is no new * version. No need to bother the user with (hopefully) temporary * errors. */ return false; } if (remote.first > local.first || remote.second > local.second) { return true; } return false; } std::pair<int, int> Updater::MainAppVersion() { std::wstring mainExe = Settings::Instance()->MainApp(); BOOL result; std::pair<int, int> version = std::pair<int, int>(0, 0); DWORD size = GetFileVersionInfoSize(mainExe.c_str(), NULL); if (size == 0) { CLOG(L"Could not determine version info size"); return version; } unsigned char *block = new unsigned char[size]; result = GetFileVersionInfo(mainExe.c_str(), NULL, size, block); if (result == 0) { CLOG(L"Failed to retrieve file version info"); delete[] block; return version; } unsigned int dataSz; VS_FIXEDFILEINFO *vers; result = VerQueryValue(block, L"\\", (void **) &vers, &dataSz); if (result == 0) { CLOG(L"Could not query root block for version info"); delete[] block; return version; } if (vers->dwSignature != 0xFEEF04BD) { CLOG(L"Invalid version signature"); delete[] block; return version; } unsigned long verl = vers->dwProductVersionMS; int hi = (verl >> 16) & 0xFF; int lo = verl & 0xFF; version = std::pair<int, int>(hi, lo); delete[] block; return version; } std::wstring Updater::MainAppVersionString() { std::pair<int, int> vers = MainAppVersion(); return std::to_wstring(vers.first) + L"." + std::to_wstring(vers.second); } std::pair<int, int> Updater::RemoteVersion() { HINTERNET internet = InternetOpen( L"3RVX Updater", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL); HINTERNET connection = InternetOpenUrl( internet, LATEST_URL.c_str(), NULL, 0, INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_PRAGMA_NOCACHE, 0); if (connection == NULL) { CLOG(L"Could not connect to URL!"); return std::pair<int, int>(0, 0); } std::string str(""); char buf[32]; DWORD read; while (InternetReadFile(connection, buf, 16, &read) == TRUE && read != 0) { str.append(buf); } /* Only consider the first line */ str.erase(str.find('\n'), str.size() - 1); int dot = str.find('.'); std::string major = str.substr(0, dot); std::string minor = str.substr(dot + 1, str.size()); std::pair<int, int> version; std::istringstream ss; ss = std::istringstream(major); ss >> version.first; ss = std::istringstream(minor); ss >> version.second; return version; }<|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/chrome_tab_contents_view_wrapper_gtk.h" #include "chrome/browser/browser_shutdown.h" #include "chrome/browser/tab_contents/render_view_context_menu_gtk.h" #include "chrome/browser/tab_contents/tab_contents_view_gtk.h" #include "chrome/browser/tab_contents/web_drag_bookmark_handler_gtk.h" #include "chrome/browser/ui/gtk/constrained_window_gtk.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/interstitial_page.h" #include "content/browser/tab_contents/tab_contents.h" #include "ui/base/gtk/gtk_floating_container.h" ChromeTabContentsViewWrapperGtk::ChromeTabContentsViewWrapperGtk() : floating_(gtk_floating_container_new()), view_(NULL), constrained_window_(NULL) { gtk_widget_set_name(floating_.get(), "chrome-tab-contents-wrapper-view"); g_signal_connect(floating_.get(), "set-floating-position", G_CALLBACK(OnSetFloatingPositionThunk), this); } ChromeTabContentsViewWrapperGtk::~ChromeTabContentsViewWrapperGtk() { floating_.Destroy(); } void ChromeTabContentsViewWrapperGtk::AttachConstrainedWindow( ConstrainedWindowGtk* constrained_window) { DCHECK(constrained_window_ == NULL); constrained_window_ = constrained_window; gtk_floating_container_add_floating(GTK_FLOATING_CONTAINER(floating_.get()), constrained_window->widget()); } void ChromeTabContentsViewWrapperGtk::RemoveConstrainedWindow( ConstrainedWindowGtk* constrained_window) { DCHECK(constrained_window == constrained_window_); constrained_window_ = NULL; gtk_container_remove(GTK_CONTAINER(floating_.get()), constrained_window->widget()); } void ChromeTabContentsViewWrapperGtk::WrapView(TabContentsViewGtk* view) { view_ = view; gtk_container_add(GTK_CONTAINER(floating_.get()), view_->expanded_container()); gtk_widget_show(floating_.get()); } gfx::NativeView ChromeTabContentsViewWrapperGtk::GetNativeView() const { return floating_.get(); } void ChromeTabContentsViewWrapperGtk::OnCreateViewForWidget() { // We install a chrome specific handler to intercept bookmark drags for the // bookmark manager/extension API. bookmark_handler_gtk_.reset(new WebDragBookmarkHandlerGtk); view_->SetDragDestDelegate(bookmark_handler_gtk_.get()); } void ChromeTabContentsViewWrapperGtk::Focus() { if (!constrained_window_) { GtkWidget* widget = view_->GetContentNativeView(); if (widget) gtk_widget_grab_focus(widget); } } gboolean ChromeTabContentsViewWrapperGtk::OnNativeViewFocusEvent( GtkWidget* widget, GtkDirectionType type, gboolean* return_value) { // If we are showing a constrained window, don't allow the native view to take // focus. if (constrained_window_) { // If we return false, it will revert to the default handler, which will // take focus. We don't want that. But if we return true, the event will // stop being propagated, leaving focus wherever it is currently. That is // also bad. So we return false to let the default handler run, but take // focus first so as to trick it into thinking the view was already focused // and allowing the event to propagate. gtk_widget_grab_focus(widget); *return_value = FALSE; return TRUE; } // Let the default TabContentsViewGtk::OnFocus() behaviour run. return FALSE; } void ChromeTabContentsViewWrapperGtk::ShowContextMenu( const ContextMenuParams& params) { // Find out the RenderWidgetHostView that corresponds to the render widget on // which this context menu is showed, so that we can retrieve the last mouse // down event on the render widget and use it as the timestamp of the // activation event to show the context menu. RenderWidgetHostView* view = NULL; if (params.custom_context.render_widget_id != webkit_glue::CustomContextMenuContext::kCurrentRenderWidget) { IPC::Channel::Listener* listener = view_->tab_contents()->render_view_host()->process()->GetListenerByID( params.custom_context.render_widget_id); if (!listener) { NOTREACHED(); return; } view = static_cast<RenderWidgetHost*>(listener)->view(); } else { view = view_->tab_contents()->GetRenderWidgetHostView(); } if (!view) return; context_menu_.reset(new RenderViewContextMenuGtk( view_->tab_contents(), params, GDK_CURRENT_TIME)); context_menu_->Init(); gfx::Rect bounds; view_->GetContainerBounds(&bounds); gfx::Point point = bounds.origin(); point.Offset(params.x, params.y); context_menu_->Popup(point); } void ChromeTabContentsViewWrapperGtk::OnSetFloatingPosition( GtkWidget* floating_container, GtkAllocation* allocation) { if (!constrained_window_) return; // Place each ConstrainedWindow in the center of the view. GtkWidget* widget = constrained_window_->widget(); DCHECK(widget->parent == floating_.get()); GtkRequisition requisition; gtk_widget_size_request(widget, &requisition); GValue value = { 0, }; g_value_init(&value, G_TYPE_INT); int child_x = std::max((allocation->width - requisition.width) / 2, 0); g_value_set_int(&value, child_x); gtk_container_child_set_property(GTK_CONTAINER(floating_container), widget, "x", &value); int child_y = std::max((allocation->height - requisition.height) / 2, 0); g_value_set_int(&value, child_y); gtk_container_child_set_property(GTK_CONTAINER(floating_container), widget, "y", &value); g_value_unset(&value); } <commit_msg>GTK: Speculative revert of r109465 to fix right clicking.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/chrome_tab_contents_view_wrapper_gtk.h" #include "chrome/browser/browser_shutdown.h" #include "chrome/browser/tab_contents/render_view_context_menu_gtk.h" #include "chrome/browser/tab_contents/tab_contents_view_gtk.h" #include "chrome/browser/tab_contents/web_drag_bookmark_handler_gtk.h" #include "chrome/browser/ui/gtk/constrained_window_gtk.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/renderer_host/render_widget_host_view_gtk.h" #include "content/browser/tab_contents/interstitial_page.h" #include "content/browser/tab_contents/tab_contents.h" #include "ui/base/gtk/gtk_floating_container.h" ChromeTabContentsViewWrapperGtk::ChromeTabContentsViewWrapperGtk() : floating_(gtk_floating_container_new()), view_(NULL), constrained_window_(NULL) { gtk_widget_set_name(floating_.get(), "chrome-tab-contents-wrapper-view"); g_signal_connect(floating_.get(), "set-floating-position", G_CALLBACK(OnSetFloatingPositionThunk), this); } ChromeTabContentsViewWrapperGtk::~ChromeTabContentsViewWrapperGtk() { floating_.Destroy(); } void ChromeTabContentsViewWrapperGtk::AttachConstrainedWindow( ConstrainedWindowGtk* constrained_window) { DCHECK(constrained_window_ == NULL); constrained_window_ = constrained_window; gtk_floating_container_add_floating(GTK_FLOATING_CONTAINER(floating_.get()), constrained_window->widget()); } void ChromeTabContentsViewWrapperGtk::RemoveConstrainedWindow( ConstrainedWindowGtk* constrained_window) { DCHECK(constrained_window == constrained_window_); constrained_window_ = NULL; gtk_container_remove(GTK_CONTAINER(floating_.get()), constrained_window->widget()); } void ChromeTabContentsViewWrapperGtk::WrapView(TabContentsViewGtk* view) { view_ = view; gtk_container_add(GTK_CONTAINER(floating_.get()), view_->expanded_container()); gtk_widget_show(floating_.get()); } gfx::NativeView ChromeTabContentsViewWrapperGtk::GetNativeView() const { return floating_.get(); } void ChromeTabContentsViewWrapperGtk::OnCreateViewForWidget() { // We install a chrome specific handler to intercept bookmark drags for the // bookmark manager/extension API. bookmark_handler_gtk_.reset(new WebDragBookmarkHandlerGtk); view_->SetDragDestDelegate(bookmark_handler_gtk_.get()); } void ChromeTabContentsViewWrapperGtk::Focus() { if (!constrained_window_) { GtkWidget* widget = view_->GetContentNativeView(); if (widget) gtk_widget_grab_focus(widget); } } gboolean ChromeTabContentsViewWrapperGtk::OnNativeViewFocusEvent( GtkWidget* widget, GtkDirectionType type, gboolean* return_value) { // If we are showing a constrained window, don't allow the native view to take // focus. if (constrained_window_) { // If we return false, it will revert to the default handler, which will // take focus. We don't want that. But if we return true, the event will // stop being propagated, leaving focus wherever it is currently. That is // also bad. So we return false to let the default handler run, but take // focus first so as to trick it into thinking the view was already focused // and allowing the event to propagate. gtk_widget_grab_focus(widget); *return_value = FALSE; return TRUE; } // Let the default TabContentsViewGtk::OnFocus() behaviour run. return FALSE; } void ChromeTabContentsViewWrapperGtk::ShowContextMenu( const ContextMenuParams& params) { // Find out the RenderWidgetHostView that corresponds to the render widget on // which this context menu is showed, so that we can retrieve the last mouse // down event on the render widget and use it as the timestamp of the // activation event to show the context menu. RenderWidgetHostView* view = NULL; if (params.custom_context.render_widget_id != webkit_glue::CustomContextMenuContext::kCurrentRenderWidget) { IPC::Channel::Listener* listener = view_->tab_contents()->render_view_host()->process()->GetListenerByID( params.custom_context.render_widget_id); if (!listener) { NOTREACHED(); return; } view = static_cast<RenderWidgetHost*>(listener)->view(); } else { view = view_->tab_contents()->GetRenderWidgetHostView(); } RenderWidgetHostViewGtk* view_gtk = static_cast<RenderWidgetHostViewGtk*>(view); if (!view_gtk) return; context_menu_.reset(new RenderViewContextMenuGtk( view_->tab_contents(), params, view_gtk->last_mouse_down() ? view_gtk->last_mouse_down()->time : GDK_CURRENT_TIME)); context_menu_->Init(); gfx::Rect bounds; view_->GetContainerBounds(&bounds); gfx::Point point = bounds.origin(); point.Offset(params.x, params.y); context_menu_->Popup(point); } void ChromeTabContentsViewWrapperGtk::OnSetFloatingPosition( GtkWidget* floating_container, GtkAllocation* allocation) { if (!constrained_window_) return; // Place each ConstrainedWindow in the center of the view. GtkWidget* widget = constrained_window_->widget(); DCHECK(widget->parent == floating_.get()); GtkRequisition requisition; gtk_widget_size_request(widget, &requisition); GValue value = { 0, }; g_value_init(&value, G_TYPE_INT); int child_x = std::max((allocation->width - requisition.width) / 2, 0); g_value_set_int(&value, child_x); gtk_container_child_set_property(GTK_CONTAINER(floating_container), widget, "x", &value); int child_y = std::max((allocation->height - requisition.height) / 2, 0); g_value_set_int(&value, child_y); gtk_container_child_set_property(GTK_CONTAINER(floating_container), widget, "y", &value); g_value_unset(&value); } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Fredrik Mellbin * * This file is part of VapourSynth. * * VapourSynth is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * VapourSynth is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with VapourSynth; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <QtCore/QMutex> #include <QtCore/QMutexLocker> #include <QtCore/QWaitCondition> #include <QtCore/QFile> #include <QtCore/QMap> #include "VSScript.h" #include "VSHelper.h" const VSAPI *vsapi = NULL; VSScript *se = NULL; VSNodeRef *node = NULL; FILE *outfile = NULL; int requests = 0; int index = 0; int outputFrames = 0; int requestedFrames = 0; int completedFrames = 0; int totalFrames = 0; int numPlanes = 0; bool y4m = false; bool outputError = false; QMap<int, const VSFrameRef *> reorderMap; QString errorMessage; QWaitCondition condition; QMutex mutex; void VS_CC frameDoneCallback(void *userData, const VSFrameRef *f, int n, VSNodeRef *, const char *errorMsg) { completedFrames++; if (f) { reorderMap.insert(n, f); while (reorderMap.contains(outputFrames)) { const VSFrameRef *frame = reorderMap.take(outputFrames); if (outputError) goto fwriteError; if (y4m) { if (!fwrite("FRAME\n", 6, 1, outfile)) { errorMessage = "Error: fwrite() call failed"; totalFrames = requestedFrames; outputError = true; goto fwriteError; } } const VSFormat *fi = vsapi->getFrameFormat(frame); for (int p = 0; p < fi->numPlanes; p++) { int stride = vsapi->getStride(frame, p); const uint8_t *readPtr = vsapi->getReadPtr(frame, p); int rowSize = vsapi->getFrameWidth(frame, p) * fi->bytesPerSample; int height = vsapi->getFrameHeight(frame, p); for (int y = 0; y < height; y++) { if (!fwrite(readPtr, rowSize, 1, outfile)) { errorMessage = "Error: fwrite() call failed"; totalFrames = requestedFrames; outputError = true; goto fwriteError; } readPtr += stride; } } fwriteError: vsapi->freeFrame(frame); outputFrames++; } } else { outputError = true; totalFrames = requestedFrames; if (errorMsg) errorMessage = QString("Error: Failed to retrieve frame ") + n + QString(" with error: ") + QString::fromUtf8(errorMsg); else errorMessage = QString("Error: Failed to retrieve frame ") + n; } if (requestedFrames < totalFrames) { vsapi->getFrameAsync(requestedFrames, node, frameDoneCallback, NULL); requestedFrames++; } if (totalFrames == completedFrames) { QMutexLocker lock(&mutex); condition.wakeOne(); } } bool outputNode() { if (requests < 1) { const VSCoreInfo *info = vsapi->getCoreInfo(vseval_getCore()); requests = info->numThreads; } const VSVideoInfo *vi = vsapi->getVideoInfo(node); totalFrames = vi->numFrames; if (y4m && (vi->format->colorFamily != cmGray && vi->format->colorFamily != cmYUV)) { errorMessage = "Error: Can only apply y4m headers to YUV and Gray format clips"; fprintf(stderr, "%s", errorMessage.toUtf8().constData()); outputError = true; return outputError; } QString y4mFormat; QString numBits; if (y4m) { if (vi->format->colorFamily == cmGray) { y4mFormat = "mono"; if (vi->format->bitsPerSample > 8) y4mFormat = y4mFormat + QString::number(vi->format->bitsPerSample); } else if (vi->format->colorFamily == cmYUV) { if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 1) y4mFormat = "420"; else if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 0) y4mFormat = "422"; else if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 0) y4mFormat = "444"; else if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 2) y4mFormat = "410"; else if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 0) y4mFormat = "411"; else if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 1) y4mFormat = "440"; if (vi->format->bitsPerSample > 8) y4mFormat = y4mFormat + "p" + QString::number(vi->format->bitsPerSample); } } if (!y4mFormat.isEmpty()) y4mFormat = "C" + y4mFormat + " "; QString header = "YUV4MPEG2 " + y4mFormat + "W" + QString::number(vi->width) + " H" + QString::number(vi->height) + " F" + QString::number(vi->fpsNum) + ":" + QString::number(vi->fpsDen) + " Ip A0:0\n"; QByteArray rawHeader = header.toUtf8(); if (y4m) { if (!fwrite(rawHeader.constData(), rawHeader.size(), 1, outfile)) { errorMessage = "Error: fwrite() call failed"; fprintf(stderr, "%s", errorMessage.toUtf8().constData()); outputError = true; return outputError; } } QMutexLocker lock(&mutex); int intitalRequestSize = std::min(requests, totalFrames); requestedFrames = intitalRequestSize; for (int n = 0; n < intitalRequestSize; n++) vsapi->getFrameAsync(n, node, frameDoneCallback, NULL); condition.wait(&mutex); if (outputError) { fprintf(stderr, "%s", errorMessage.toUtf8().constData()); } return outputError; } // script output y4m index requests #ifdef _WIN32 int wmain(int argc, wchar_t **argv) { #else int main(int argc, char **argv) { #endif if (argc < 3) { fprintf(stderr, "VSPipe\n"); fprintf(stderr, "Write to stdout: vspipe script.vpy - [options]\n"); fprintf(stderr, "Write to file: vspipe script.vpy <outfile> [options]\n"); fprintf(stderr, "Available options:\n"); fprintf(stderr, "Select output index: -index N (default: 0)\n"); fprintf(stderr, "Set number of concurrent frame requests: -requests N (default: number of threads)\n"); fprintf(stderr, "Add YUV4MPEG headers: -y4m (default: off)\n"); return 1; } for (int arg = 3; arg < argc; arg++) { QString argString = QString::fromWCharArray(argv[arg]);; if (argString == "-y4m") { y4m = true; } else if (argString == "-index") { bool ok = false; if (argc <= arg + 1) { fprintf(stderr, "No index number specified"); return 1; } QString numString = QString::fromWCharArray(argv[arg+1]); index = numString.toInt(&ok); if (!ok) { fprintf(stderr, "Couldn't convert %s to an integer", numString.toUtf8().constData()); return 1; } arg++; } else if (argString == "-requests") { bool ok = false; if (argc <= arg + 1) { fprintf(stderr, "No request number specified"); return 1; } QString numString = QString::fromWCharArray(argv[arg+1]); requests = numString.toInt(&ok); if (!ok) { fprintf(stderr, "Couldn't convert %s to an integer", numString.toUtf8().constData()); return 1; } arg++; } else { fprintf(stderr, "Unknown argument: %s\n", argString.toUtf8().constData()); return 1; } } if (!vseval_init()) { fprintf(stderr, "Failed to initialize VapourSynth environment\n"); return 1; } vsapi = vseval_getVSApi(); if (!vsapi) { fprintf(stderr, "Failed to get VapourSynth API\n"); vseval_finalize(); return 1; } QFile scriptFile(QString::fromWCharArray(argv[1])); if (!scriptFile.open(QIODevice::ReadOnly)) { fprintf(stderr, "Failed to to open script file for reading\n"); vseval_finalize(); return 1; } if (scriptFile.size() > 1024*1024*16) { fprintf(stderr, "Script files bigger than 16MB not allowed\n"); vseval_finalize(); return 1; } QByteArray scriptData = scriptFile.readAll(); if (scriptData.isEmpty()) { fprintf(stderr, "Failed to read script file or file is empty\n"); vseval_finalize(); return 1; } if (vseval_evaluateScript(&se, scriptData.constData(), QString::fromWCharArray(argv[1]).toUtf8())) { fprintf(stderr, "Script evaluation failed:\n%s", vseval_getError(se)); vseval_freeScript(se); vseval_finalize(); return 1; } node = vseval_getOutput(se, index); if (!node) { fprintf(stderr, "Failed to retrieve output node. Invalid index specified?\n"); vseval_freeScript(se); vseval_finalize(); return 1; } const VSVideoInfo *vi = vsapi->getVideoInfo(node); if (!isConstantFormat(vi) || vi->numFrames == 0) { fprintf(stderr, "Cannot output clips with varying dimensions or unknown length\n"); vseval_freeScript(se); vseval_finalize(); return 1; } outfile = stdout; bool error = outputNode(); vseval_freeScript(se); vseval_finalize(); return error ? 1 : 0; } /* VapourSynthFile::~VapourSynthFile() { if (vi) { vi = NULL; while (pending_requests > 0) {}; vseval_freeScript(se); } } */ <commit_msg>Proper unicode support in vspipe<commit_after>/* * Copyright (c) 2013 Fredrik Mellbin * * This file is part of VapourSynth. * * VapourSynth is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * VapourSynth is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with VapourSynth; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <QtCore/QMutex> #include <QtCore/QMutexLocker> #include <QtCore/QWaitCondition> #include <QtCore/QFile> #include <QtCore/QMap> #include "VSScript.h" #include "VSHelper.h" #ifdef _WIN32 static inline QString nativeToQString(const wchar_t *str) { return QString::fromWCharArray(str); } #else static inline QString nativeToQString(const char *str) { return QString::fromLocal8Bit(str); } #endif const VSAPI *vsapi = NULL; VSScript *se = NULL; VSNodeRef *node = NULL; FILE *outfile = NULL; int requests = 0; int index = 0; int outputFrames = 0; int requestedFrames = 0; int completedFrames = 0; int totalFrames = 0; int numPlanes = 0; bool y4m = false; bool outputError = false; QMap<int, const VSFrameRef *> reorderMap; QString errorMessage; QWaitCondition condition; QMutex mutex; void VS_CC frameDoneCallback(void *userData, const VSFrameRef *f, int n, VSNodeRef *, const char *errorMsg) { completedFrames++; if (f) { reorderMap.insert(n, f); while (reorderMap.contains(outputFrames)) { const VSFrameRef *frame = reorderMap.take(outputFrames); if (outputError) goto fwriteError; if (y4m) { if (!fwrite("FRAME\n", 6, 1, outfile)) { errorMessage = "Error: fwrite() call failed"; totalFrames = requestedFrames; outputError = true; goto fwriteError; } } const VSFormat *fi = vsapi->getFrameFormat(frame); for (int p = 0; p < fi->numPlanes; p++) { int stride = vsapi->getStride(frame, p); const uint8_t *readPtr = vsapi->getReadPtr(frame, p); int rowSize = vsapi->getFrameWidth(frame, p) * fi->bytesPerSample; int height = vsapi->getFrameHeight(frame, p); for (int y = 0; y < height; y++) { if (!fwrite(readPtr, rowSize, 1, outfile)) { errorMessage = "Error: fwrite() call failed"; totalFrames = requestedFrames; outputError = true; goto fwriteError; } readPtr += stride; } } fwriteError: vsapi->freeFrame(frame); outputFrames++; } } else { outputError = true; totalFrames = requestedFrames; if (errorMsg) errorMessage = QString("Error: Failed to retrieve frame ") + n + QString(" with error: ") + QString::fromUtf8(errorMsg); else errorMessage = QString("Error: Failed to retrieve frame ") + n; } if (requestedFrames < totalFrames) { vsapi->getFrameAsync(requestedFrames, node, frameDoneCallback, NULL); requestedFrames++; } if (totalFrames == completedFrames) { QMutexLocker lock(&mutex); condition.wakeOne(); } } bool outputNode() { if (requests < 1) { const VSCoreInfo *info = vsapi->getCoreInfo(vseval_getCore()); requests = info->numThreads; } const VSVideoInfo *vi = vsapi->getVideoInfo(node); totalFrames = vi->numFrames; if (y4m && (vi->format->colorFamily != cmGray && vi->format->colorFamily != cmYUV)) { errorMessage = "Error: Can only apply y4m headers to YUV and Gray format clips"; fprintf(stderr, "%s", errorMessage.toUtf8().constData()); outputError = true; return outputError; } QString y4mFormat; QString numBits; if (y4m) { if (vi->format->colorFamily == cmGray) { y4mFormat = "mono"; if (vi->format->bitsPerSample > 8) y4mFormat = y4mFormat + QString::number(vi->format->bitsPerSample); } else if (vi->format->colorFamily == cmYUV) { if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 1) y4mFormat = "420"; else if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 0) y4mFormat = "422"; else if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 0) y4mFormat = "444"; else if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 2) y4mFormat = "410"; else if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 0) y4mFormat = "411"; else if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 1) y4mFormat = "440"; if (vi->format->bitsPerSample > 8) y4mFormat = y4mFormat + "p" + QString::number(vi->format->bitsPerSample); } } if (!y4mFormat.isEmpty()) y4mFormat = "C" + y4mFormat + " "; QString header = "YUV4MPEG2 " + y4mFormat + "W" + QString::number(vi->width) + " H" + QString::number(vi->height) + " F" + QString::number(vi->fpsNum) + ":" + QString::number(vi->fpsDen) + " Ip A0:0\n"; QByteArray rawHeader = header.toUtf8(); if (y4m) { if (!fwrite(rawHeader.constData(), rawHeader.size(), 1, outfile)) { errorMessage = "Error: fwrite() call failed"; fprintf(stderr, "%s", errorMessage.toUtf8().constData()); outputError = true; return outputError; } } QMutexLocker lock(&mutex); int intitalRequestSize = std::min(requests, totalFrames); requestedFrames = intitalRequestSize; for (int n = 0; n < intitalRequestSize; n++) vsapi->getFrameAsync(n, node, frameDoneCallback, NULL); condition.wait(&mutex); if (outputError) { fprintf(stderr, "%s", errorMessage.toUtf8().constData()); } return outputError; } // script output y4m index requests #ifdef _WIN32 int wmain(int argc, wchar_t **argv) { #else int main(int argc, char **argv) { #endif if (argc < 3) { fprintf(stderr, "VSPipe\n"); fprintf(stderr, "Write to stdout: vspipe script.vpy - [options]\n"); fprintf(stderr, "Write to file: vspipe script.vpy <outfile> [options]\n"); fprintf(stderr, "Available options:\n"); fprintf(stderr, "Select output index: -index N (default: 0)\n"); fprintf(stderr, "Set number of concurrent frame requests: -requests N (default: number of threads)\n"); fprintf(stderr, "Add YUV4MPEG headers: -y4m (default: off)\n"); return 1; } for (int arg = 3; arg < argc; arg++) { QString argString = nativeToQString(argv[arg]); if (argString == "-y4m") { y4m = true; } else if (argString == "-index") { bool ok = false; if (argc <= arg + 1) { fprintf(stderr, "No index number specified"); return 1; } QString numString = nativeToQString(argv[arg+1]); index = numString.toInt(&ok); if (!ok) { fprintf(stderr, "Couldn't convert %s to an integer", numString.toUtf8().constData()); return 1; } arg++; } else if (argString == "-requests") { bool ok = false; if (argc <= arg + 1) { fprintf(stderr, "No request number specified"); return 1; } QString numString = nativeToQString(argv[arg+1]); requests = numString.toInt(&ok); if (!ok) { fprintf(stderr, "Couldn't convert %s to an integer", numString.toUtf8().constData()); return 1; } arg++; } else { fprintf(stderr, "Unknown argument: %s\n", argString.toUtf8().constData()); return 1; } } if (!vseval_init()) { fprintf(stderr, "Failed to initialize VapourSynth environment\n"); return 1; } vsapi = vseval_getVSApi(); if (!vsapi) { fprintf(stderr, "Failed to get VapourSynth API\n"); vseval_finalize(); return 1; } QFile scriptFile(nativeToQString(argv[1])); if (!scriptFile.open(QIODevice::ReadOnly)) { fprintf(stderr, "Failed to to open script file for reading\n"); vseval_finalize(); return 1; } if (scriptFile.size() > 1024*1024*16) { fprintf(stderr, "Script files bigger than 16MB not allowed\n"); vseval_finalize(); return 1; } QByteArray scriptData = scriptFile.readAll(); if (scriptData.isEmpty()) { fprintf(stderr, "Failed to read script file or file is empty\n"); vseval_finalize(); return 1; } if (vseval_evaluateScript(&se, scriptData.constData(), nativeToQString(argv[1]).toUtf8())) { fprintf(stderr, "Script evaluation failed:\n%s", vseval_getError(se)); vseval_freeScript(se); vseval_finalize(); return 1; } node = vseval_getOutput(se, index); if (!node) { fprintf(stderr, "Failed to retrieve output node. Invalid index specified?\n"); vseval_freeScript(se); vseval_finalize(); return 1; } const VSVideoInfo *vi = vsapi->getVideoInfo(node); if (!isConstantFormat(vi) || vi->numFrames == 0) { fprintf(stderr, "Cannot output clips with varying dimensions or unknown length\n"); vseval_freeScript(se); vseval_finalize(); return 1; } outfile = stdout; bool error = outputNode(); vseval_freeScript(se); vseval_finalize(); return error ? 1 : 0; } /* VapourSynthFile::~VapourSynthFile() { if (vi) { vi = NULL; while (pending_requests > 0) {}; vseval_freeScript(se); } } */ <|endoftext|>
<commit_before>#include <glt/window.hpp> #include <glt/app.hpp> #include <algorithm> #include <sstream> #include <iostream> namespace glt { void setupCallbacks(GLFWwindow *window) { glfwSetKeyCallback(window, OnKeyEvent); glfwSetCharCallback(window, OnTextInput); glfwSetCursorEnterCallback(window, OnCursorEnter); glfwSetCursorPosCallback(window, OnMouseMove); glfwSetMouseButtonCallback(window, OnMouseButtonEvent); glfwSetScrollCallback(window, OnScroll); } Window::Window(int width, int height, const char *title, GLFWmonitor *monitor, GLFWwindow *share) : _window(nullptr) { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, GLT_OPEN_GL_MAJOR_VERSION); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, GLT_OPEN_GL_MINOR_VERSION); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); _window = glfwCreateWindow(width, height, title, monitor, share); glfwSetWindowUserPointer(_window, (void*) this); setupCallbacks(_window); } inline void destory(GLFWwindow *window) { if (window != nullptr) { glfwDestroyWindow(window); window = nullptr; } } Window::~Window() { destory(_window); } Window::Window(Window&& rhs) : Window() { std::swap(_window, rhs._window); glfwSetWindowUserPointer(_window, (void*) this); setupCallbacks(_window); } Window& Window::operator=(Window&& rhs) { destory(_window); std::swap(_window, rhs._window); glfwSetWindowUserPointer(_window, (void*) this); setupCallbacks(_window); return *this; } inline void Window::makeCurrentContext() { glfwMakeContextCurrent(_window); } inline void Window::show() { glfwShowWindow(_window); } inline void Window::hide() { glfwHideWindow(_window); } inline bool Window::shouldClose() { return static_cast<bool>(glfwWindowShouldClose(_window)); } inline void Window::swapBuffers() { glfwSwapBuffers(_window); } std::tuple<int, int> Window::getFramebufferSize() { int width, height; glfwGetFramebufferSize(_window, &width, &height); return std::make_tuple(width, height); } std::tuple<int, int> Window::getSize() { int width, height; glfwGetWindowSize(_window, &width, &height); return std::make_tuple(width, height); } inline void Window::setInputMode(int mode, int value) { glfwSetInputMode(_window, mode, value); } inline void Window::setCursor(GLFWcursor *cursor) { glfwSetCursor(_window, cursor); } void OnKeyEvent(GLFWwindow *win, int key, int scancode, int action, int mods) { auto window = (Window*) glfwGetWindowUserPointer(win); window->_onKeyEvent(key, scancode, action, mods); } void OnTextInput(GLFWwindow * win, unsigned int codepoint) { auto window = (Window*) glfwGetWindowUserPointer(win); window->_onTextInput(codepoint); } void OnCursorEnter(GLFWwindow *win, int entered) { auto window = (Window*) glfwGetWindowUserPointer(win); window->_onCursorEnter(entered); } void OnMouseMove(GLFWwindow *win, double xpos, double ypos) { auto window = (Window*) glfwGetWindowUserPointer(win); window->_onMouseMove(xpos, ypos); } void OnMouseButtonEvent(GLFWwindow * win, int button, int action, int mods) { auto window = (Window*) glfwGetWindowUserPointer(win); window->_onMouseButtonEvent(button, action, mods); } void OnScroll(GLFWwindow *win, double xoffset, double yoffset) { auto window = (Window*) glfwGetWindowUserPointer(win); window->_onScroll(xoffset, yoffset); } inline void pollEvents() { glfwPollEvents(); } const int WIDTH = 1024; const int HEIGHT = 768; const char *TITLE = "OpenGL Window"; Window easyWindow(int width, int height, const char *title, std::ostream &out) { Window window(width, height, title, nullptr, nullptr); if (window.valid() == false) { out << "Could not create window.\n" << "Has an App been created?" << std::endl; exit(EXIT_FAILURE); } window.makeCurrentContext(); if (initGlTools() == false) { out << "Failed to load OpenGL." << std::endl; exit(EXIT_FAILURE); } return window; } inline Window easyWindow(int width, int height, const char *title) { return easyWindow(width, height, title, std::cerr); } inline Window easyWindow(int width, int height, std::ostream &out) { return easyWindow(width, height, TITLE, out); } inline Window easyWindow(int width, int height) { return easyWindow(width, height, TITLE, std::cerr); } inline Window easyWindow(const char *title, std::ostream &out) { return easyWindow(WIDTH, HEIGHT, title, out); } inline Window easyWindow(const char *title) { return easyWindow(WIDTH, HEIGHT, title, std::cerr); } inline Window easyWindow(std::ostream &out) { return easyWindow(WIDTH, HEIGHT, TITLE, out); } inline Window easyWindow() { return easyWindow(WIDTH, HEIGHT, TITLE, std::cerr); } } // end namespace glt <commit_msg>Initialize Window callbacks to empty functions<commit_after>#include <glt/window.hpp> #include <glt/app.hpp> #include <algorithm> #include <sstream> #include <iostream> namespace glt { void setupCallbacks(GLFWwindow *window) { glfwSetKeyCallback(window, OnKeyEvent); glfwSetCharCallback(window, OnTextInput); glfwSetCursorEnterCallback(window, OnCursorEnter); glfwSetCursorPosCallback(window, OnMouseMove); glfwSetMouseButtonCallback(window, OnMouseButtonEvent); glfwSetScrollCallback(window, OnScroll); } Window::Window(int width, int height, const char *title, GLFWmonitor *monitor, GLFWwindow *share) : _window(nullptr) , _onCursorEnter([](int){}) , _onKeyEvent([](int,int,int,int){}) , _onTextInput([](unsigned int){}) , _onMouseMove([](double,double){}) , _onMouseButtonEvent([](int,int,int){}) , _onScroll([](double, double){}) { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, GLT_OPEN_GL_MAJOR_VERSION); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, GLT_OPEN_GL_MINOR_VERSION); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); _window = glfwCreateWindow(width, height, title, monitor, share); glfwSetWindowUserPointer(_window, (void*) this); setupCallbacks(_window); } inline void destory(GLFWwindow *window) { if (window != nullptr) { glfwDestroyWindow(window); window = nullptr; } } Window::~Window() { destory(_window); } Window::Window(Window&& rhs) : Window() { std::swap(_window, rhs._window); std::swap(_onCursorEnter, rhs._onCursorEnter); std::swap(_onKeyEvent, rhs._onKeyEvent); std::swap(_onTextInput, rhs._onTextInput); std::swap(_onMouseMove, rhs._onMouseMove); std::swap(_onMouseButtonEvent, rhs._onMouseButtonEvent); std::swap(_onScroll, rhs._onScroll); glfwSetWindowUserPointer(_window, (void*) this); setupCallbacks(_window); } Window& Window::operator=(Window&& rhs) { destory(_window); std::swap(_window, rhs._window); std::swap(_onCursorEnter, rhs._onCursorEnter); std::swap(_onKeyEvent, rhs._onKeyEvent); std::swap(_onTextInput, rhs._onTextInput); std::swap(_onMouseMove, rhs._onMouseMove); std::swap(_onMouseButtonEvent, rhs._onMouseButtonEvent); std::swap(_onScroll, rhs._onScroll); glfwSetWindowUserPointer(_window, (void*) this); setupCallbacks(_window); return *this; } inline void Window::makeCurrentContext() { glfwMakeContextCurrent(_window); } inline void Window::show() { glfwShowWindow(_window); } inline void Window::hide() { glfwHideWindow(_window); } inline bool Window::shouldClose() { return static_cast<bool>(glfwWindowShouldClose(_window)); } inline void Window::swapBuffers() { glfwSwapBuffers(_window); } std::tuple<int, int> Window::getFramebufferSize() { int width, height; glfwGetFramebufferSize(_window, &width, &height); return std::make_tuple(width, height); } std::tuple<int, int> Window::getSize() { int width, height; glfwGetWindowSize(_window, &width, &height); return std::make_tuple(width, height); } inline void Window::setInputMode(int mode, int value) { glfwSetInputMode(_window, mode, value); } inline void Window::setCursor(GLFWcursor *cursor) { glfwSetCursor(_window, cursor); } void OnKeyEvent(GLFWwindow *win, int key, int scancode, int action, int mods) { auto window = (Window*) glfwGetWindowUserPointer(win); window->_onKeyEvent(key, scancode, action, mods); } void OnTextInput(GLFWwindow * win, unsigned int codepoint) { auto window = (Window*) glfwGetWindowUserPointer(win); window->_onTextInput(codepoint); } void OnCursorEnter(GLFWwindow *win, int entered) { auto window = (Window*) glfwGetWindowUserPointer(win); window->_onCursorEnter(entered); } void OnMouseMove(GLFWwindow *win, double xpos, double ypos) { auto window = (Window*) glfwGetWindowUserPointer(win); window->_onMouseMove(xpos, ypos); } void OnMouseButtonEvent(GLFWwindow * win, int button, int action, int mods) { auto window = (Window*) glfwGetWindowUserPointer(win); window->_onMouseButtonEvent(button, action, mods); } void OnScroll(GLFWwindow *win, double xoffset, double yoffset) { auto window = (Window*) glfwGetWindowUserPointer(win); window->_onScroll(xoffset, yoffset); } inline void pollEvents() { glfwPollEvents(); } const int WIDTH = 1024; const int HEIGHT = 768; const char *TITLE = "OpenGL Window"; Window easyWindow(int width, int height, const char *title, std::ostream &out) { Window window(width, height, title, nullptr, nullptr); if (window.valid() == false) { out << "Could not create window.\n" << "Has an App been created?" << std::endl; exit(EXIT_FAILURE); } window.makeCurrentContext(); if (initGlTools() == false) { out << "Failed to load OpenGL." << std::endl; exit(EXIT_FAILURE); } return window; } inline Window easyWindow(int width, int height, const char *title) { return easyWindow(width, height, title, std::cerr); } inline Window easyWindow(int width, int height, std::ostream &out) { return easyWindow(width, height, TITLE, out); } inline Window easyWindow(int width, int height) { return easyWindow(width, height, TITLE, std::cerr); } inline Window easyWindow(const char *title, std::ostream &out) { return easyWindow(WIDTH, HEIGHT, title, out); } inline Window easyWindow(const char *title) { return easyWindow(WIDTH, HEIGHT, title, std::cerr); } inline Window easyWindow(std::ostream &out) { return easyWindow(WIDTH, HEIGHT, TITLE, out); } inline Window easyWindow() { return easyWindow(WIDTH, HEIGHT, TITLE, std::cerr); } } // end namespace glt <|endoftext|>
<commit_before>#include "stdafx.h" #include "AlembicXform.h" #include "CommonProfiler.h" using namespace XSI; using namespace MATH; void SaveXformSample(XSI::CRef parentKineStateRef, XSI::CRef kineStateRef, AbcG::OXformSchema & schema,AbcG::XformSample & sample, double time, bool xformCache, bool globalSpace, bool flattenHierarchy) { // check if we are exporting in global space if(globalSpace) { if(schema.getNumSamples() > 0) return; // store identity matrix sample.setTranslation(Imath::V3d(0.0,0.0,0.0)); sample.setRotation(Imath::V3d(1.0,0.0,0.0),0.0); sample.setScale(Imath::V3d(1.0,1.0,1.0)); // save the sample schema.set(sample); return; } // check if the transform is animated //if(schema.getNumSamples() > 0) //{ // X3DObject parent(kineState.GetParent3DObject()); // if(!isRefAnimated(kineState.GetParent3DObject().GetRef(),xformCache)) // return; //} KinematicState kineState(kineStateRef); CTransformation globalTransform = kineState.GetTransform(time); CTransformation transform; if(flattenHierarchy){ transform = globalTransform; } else{ KinematicState parentKineState(parentKineStateRef); CMatrix4 parentGlobalTransform4 = parentKineState.GetTransform(time).GetMatrix4(); CMatrix4 transform4 = globalTransform.GetMatrix4(); parentGlobalTransform4.InvertInPlace(); transform4.MulInPlace(parentGlobalTransform4); transform.SetMatrix4(transform4); } // store the transform CVector3 trans = transform.GetTranslation(); CVector3 axis; double angle = transform.GetRotationAxisAngle(axis); CVector3 scale = transform.GetScaling(); sample.setTranslation(Imath::V3d(trans.GetX(),trans.GetY(),trans.GetZ())); sample.setRotation(Imath::V3d(axis.GetX(),axis.GetY(),axis.GetZ()),RadiansToDegrees(angle)); sample.setScale(Imath::V3d(scale.GetX(),scale.GetY(),scale.GetZ())); //ESS_LOG_WARNING("time: "<<time<<" trans: ("<<trans.GetX()<<", "<<trans.GetY()<<", "<<trans.GetZ()<<") angle: "<<angle<<" axis: ("<<axis.GetX()<<", "<<axis.GetY()<<", "<<axis.GetZ()); // save the sample schema.set(sample); } ESS_CALLBACK_START( alembic_xform_Define, CRef& ) return alembicOp_Define(in_ctxt); ESS_CALLBACK_END ESS_CALLBACK_START( alembic_xform_DefineLayout, CRef& ) return alembicOp_DefineLayout(in_ctxt); ESS_CALLBACK_END ESS_CALLBACK_START( alembic_xform_Update, CRef& ) ESS_PROFILE_SCOPE("alembic_xform_Update"); OperatorContext ctxt( in_ctxt ); if((bool)ctxt.GetParameterValue(L"muted")) return CStatus::OK; CValue udVal = ctxt.GetUserData(); alembic_UD * p = (alembic_UD*)(CValue::siPtrType)udVal; CString path = ctxt.GetParameterValue(L"path"); CString identifier = ctxt.GetParameterValue(L"identifier"); AbcG::IObject iObj = getObjectFromArchive(path,identifier); if(!iObj.valid()) { return CStatus::OK; } AbcG::IXform obj(iObj,Abc::kWrapExisting); if(!obj.valid()) { return CStatus::OK; } double time = ctxt.GetParameterValue(L"time"); if(p->times.size() == 0 || abs(p->lastTime - time) < 0.001) { p->times.clear(); for(size_t i=0;i<obj.getSchema().getNumSamples();i++) { p->times.push_back((double)obj.getSchema().getTimeSampling()->getSampleTime( i )); } } Abc::M44d matrix; // constructor creates an identity matrix // if no time samples, default to identity matrix if( p->times.size() > 0 ) { SampleInfo sampleInfo = getSampleInfo( time, obj.getSchema().getTimeSampling(), obj.getSchema().getNumSamples() ); if( p->indexToMatrices.find(sampleInfo.floorIndex) == p->indexToMatrices.end() ) { AbcG::XformSample sample; obj.getSchema().get(sample,sampleInfo.floorIndex); p->indexToMatrices.insert( std::map<size_t,Abc::M44d>::value_type( sampleInfo.floorIndex, sample.getMatrix() ) ); } if( sampleInfo.ceilIndex < p->times.size() ) { if( p->indexToMatrices.find(sampleInfo.ceilIndex) == p->indexToMatrices.end() ) { AbcG::XformSample sample; obj.getSchema().get(sample,sampleInfo.ceilIndex); p->indexToMatrices.insert( std::map<size_t,Abc::M44d>::value_type( sampleInfo.ceilIndex, sample.getMatrix() ) ); } } if( sampleInfo.alpha == 1.0f ) { matrix = p->indexToMatrices[ sampleInfo.floorIndex ]; } else { matrix = p->indexToMatrices[ sampleInfo.floorIndex ] * sampleInfo.alpha + p->indexToMatrices[ sampleInfo.ceilIndex ] * ( 1 - sampleInfo.alpha ); } } p->lastTime = time; CMatrix4 xsiMatrix; xsiMatrix.Set( matrix.getValue()[0],matrix.getValue()[1],matrix.getValue()[2],matrix.getValue()[3], matrix.getValue()[4],matrix.getValue()[5],matrix.getValue()[6],matrix.getValue()[7], matrix.getValue()[8],matrix.getValue()[9],matrix.getValue()[10],matrix.getValue()[11], matrix.getValue()[12],matrix.getValue()[13],matrix.getValue()[14],matrix.getValue()[15]); CTransformation xsiTransform; xsiTransform.SetMatrix4(xsiMatrix); KinematicState state(ctxt.GetOutputTarget()); state.PutTransform(xsiTransform); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START( alembic_xform_Init, CRef& ) Context ctxt( in_ctxt ); CustomOperator op(ctxt.GetSource()); CValue val = (CValue::siPtrType) new alembic_UD(op.GetObjectID()); ctxt.PutUserData( val ) ; return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START( alembic_xform_Term, CRef& ) Context ctxt( in_ctxt ); CustomOperator op(ctxt.GetSource()); delRefArchive(op.GetParameterValue(L"path").GetAsText()); CValue udVal = ctxt.GetUserData(); alembic_UD * p = (alembic_UD*)(CValue::siPtrType)udVal; if(p!=NULL) { delete(p); p = NULL; } return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START( alembic_visibility_Define, CRef& ) return alembicOp_Define(in_ctxt); ESS_CALLBACK_END ESS_CALLBACK_START( alembic_visibility_DefineLayout, CRef& ) return alembicOp_DefineLayout(in_ctxt); ESS_CALLBACK_END ESS_CALLBACK_START( alembic_visibility_Update, CRef& ) ESS_PROFILE_SCOPE("alembic_visibility_Update"); OperatorContext ctxt( in_ctxt ); if((bool)ctxt.GetParameterValue(L"muted")) return CStatus::OK; CString path = ctxt.GetParameterValue(L"path"); CString identifier = ctxt.GetParameterValue(L"identifier"); AbcG::IObject obj = getObjectFromArchive(path,identifier); if(!obj.valid()) return CStatus::OK; AbcG::IVisibilityProperty visibilityProperty = AbcG::GetVisibilityProperty(obj); if(!visibilityProperty.valid()) return CStatus::OK; SampleInfo sampleInfo = getSampleInfo( ctxt.GetParameterValue(L"time"), getTimeSamplingFromObject(obj), visibilityProperty.getNumSamples() ); AbcA::int8_t rawVisibilityValue = visibilityProperty.getValue ( sampleInfo.floorIndex ); AbcG::ObjectVisibility visibilityValue =AbcG::ObjectVisibility ( rawVisibilityValue ); Property prop(ctxt.GetOutputTarget()); switch(visibilityValue) { case AbcG::kVisibilityVisible: { prop.PutParameterValue(L"viewvis",true); prop.PutParameterValue(L"rendvis",true); break; } case AbcG::kVisibilityHidden: { prop.PutParameterValue(L"viewvis",false); prop.PutParameterValue(L"rendvis",false); break; } default: { break; } } return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START( alembic_visibility_Term, CRef& ) return alembicOp_Term(in_ctxt); ESS_CALLBACK_END <commit_msg>fixed #205<commit_after>#include "stdafx.h" #include "AlembicXform.h" #include "CommonProfiler.h" using namespace XSI; using namespace MATH; void SaveXformSample(XSI::CRef parentKineStateRef, XSI::CRef kineStateRef, AbcG::OXformSchema & schema,AbcG::XformSample & sample, double time, bool xformCache, bool globalSpace, bool flattenHierarchy) { // check if we are exporting in global space if(globalSpace) { if(schema.getNumSamples() > 0) return; // store identity matrix sample.setTranslation(Imath::V3d(0.0,0.0,0.0)); sample.setRotation(Imath::V3d(1.0,0.0,0.0),0.0); sample.setScale(Imath::V3d(1.0,1.0,1.0)); // save the sample schema.set(sample); return; } // check if the transform is animated //if(schema.getNumSamples() > 0) //{ // X3DObject parent(kineState.GetParent3DObject()); // if(!isRefAnimated(kineState.GetParent3DObject().GetRef(),xformCache)) // return; //} KinematicState kineState(kineStateRef); CTransformation globalTransform = kineState.GetTransform(time); CTransformation transform; if(flattenHierarchy){ transform = globalTransform; } else{ KinematicState parentKineState(parentKineStateRef); CMatrix4 parentGlobalTransform4 = parentKineState.GetTransform(time).GetMatrix4(); CMatrix4 transform4 = globalTransform.GetMatrix4(); parentGlobalTransform4.InvertInPlace(); transform4.MulInPlace(parentGlobalTransform4); transform.SetMatrix4(transform4); } // store the transform CVector3 trans = transform.GetTranslation(); CVector3 axis; double angle = transform.GetRotationAxisAngle(axis); CVector3 scale = transform.GetScaling(); sample.setTranslation(Imath::V3d(trans.GetX(),trans.GetY(),trans.GetZ())); sample.setRotation(Imath::V3d(axis.GetX(),axis.GetY(),axis.GetZ()),RadiansToDegrees(angle)); sample.setScale(Imath::V3d(scale.GetX(),scale.GetY(),scale.GetZ())); //ESS_LOG_WARNING("time: "<<time<<" trans: ("<<trans.GetX()<<", "<<trans.GetY()<<", "<<trans.GetZ()<<") angle: "<<angle<<" axis: ("<<axis.GetX()<<", "<<axis.GetY()<<", "<<axis.GetZ()); // save the sample schema.set(sample); } ESS_CALLBACK_START( alembic_xform_Define, CRef& ) return alembicOp_Define(in_ctxt); ESS_CALLBACK_END ESS_CALLBACK_START( alembic_xform_DefineLayout, CRef& ) return alembicOp_DefineLayout(in_ctxt); ESS_CALLBACK_END ESS_CALLBACK_START( alembic_xform_Update, CRef& ) ESS_PROFILE_SCOPE("alembic_xform_Update"); OperatorContext ctxt( in_ctxt ); if((bool)ctxt.GetParameterValue(L"muted")) return CStatus::OK; CValue udVal = ctxt.GetUserData(); alembic_UD * p = (alembic_UD*)(CValue::siPtrType)udVal; CString path = ctxt.GetParameterValue(L"path"); CString identifier = ctxt.GetParameterValue(L"identifier"); AbcG::IObject iObj = getObjectFromArchive(path,identifier); if(!iObj.valid()) { return CStatus::OK; } AbcG::IXform obj(iObj,Abc::kWrapExisting); if(!obj.valid()) { return CStatus::OK; } double time = ctxt.GetParameterValue(L"time"); Abc::M44d matrix; // constructor creates an identity matrix // if no time samples, default to identity matrix if( obj.getSchema().getNumSamples() > 0 ) { SampleInfo sampleInfo = getSampleInfo( time, obj.getSchema().getTimeSampling(), obj.getSchema().getNumSamples() ); if( p->indexToMatrices.find(sampleInfo.floorIndex) == p->indexToMatrices.end() ) { AbcG::XformSample sample; obj.getSchema().get(sample,sampleInfo.floorIndex); p->indexToMatrices.insert( std::map<size_t,Abc::M44d>::value_type( sampleInfo.floorIndex, sample.getMatrix() ) ); } if( sampleInfo.ceilIndex < obj.getSchema().getNumSamples() ) { if( p->indexToMatrices.find(sampleInfo.ceilIndex) == p->indexToMatrices.end() ) { AbcG::XformSample sample; obj.getSchema().get(sample,sampleInfo.ceilIndex); p->indexToMatrices.insert( std::map<size_t,Abc::M44d>::value_type( sampleInfo.ceilIndex, sample.getMatrix() ) ); } } if( sampleInfo.alpha == 1.0f ) { matrix = p->indexToMatrices[ sampleInfo.floorIndex ]; } else { matrix = p->indexToMatrices[ sampleInfo.floorIndex ] * sampleInfo.alpha + p->indexToMatrices[ sampleInfo.ceilIndex ] * ( 1 - sampleInfo.alpha ); } } CMatrix4 xsiMatrix; xsiMatrix.Set( matrix.getValue()[0],matrix.getValue()[1],matrix.getValue()[2],matrix.getValue()[3], matrix.getValue()[4],matrix.getValue()[5],matrix.getValue()[6],matrix.getValue()[7], matrix.getValue()[8],matrix.getValue()[9],matrix.getValue()[10],matrix.getValue()[11], matrix.getValue()[12],matrix.getValue()[13],matrix.getValue()[14],matrix.getValue()[15]); CTransformation xsiTransform; xsiTransform.SetMatrix4(xsiMatrix); KinematicState state(ctxt.GetOutputTarget()); state.PutTransform(xsiTransform); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START( alembic_xform_Init, CRef& ) Context ctxt( in_ctxt ); CustomOperator op(ctxt.GetSource()); CValue val = (CValue::siPtrType) new alembic_UD(op.GetObjectID()); ctxt.PutUserData( val ) ; return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START( alembic_xform_Term, CRef& ) Context ctxt( in_ctxt ); CustomOperator op(ctxt.GetSource()); delRefArchive(op.GetParameterValue(L"path").GetAsText()); CValue udVal = ctxt.GetUserData(); alembic_UD * p = (alembic_UD*)(CValue::siPtrType)udVal; if(p!=NULL) { delete(p); p = NULL; } return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START( alembic_visibility_Define, CRef& ) return alembicOp_Define(in_ctxt); ESS_CALLBACK_END ESS_CALLBACK_START( alembic_visibility_DefineLayout, CRef& ) return alembicOp_DefineLayout(in_ctxt); ESS_CALLBACK_END ESS_CALLBACK_START( alembic_visibility_Update, CRef& ) ESS_PROFILE_SCOPE("alembic_visibility_Update"); OperatorContext ctxt( in_ctxt ); if((bool)ctxt.GetParameterValue(L"muted")) return CStatus::OK; CString path = ctxt.GetParameterValue(L"path"); CString identifier = ctxt.GetParameterValue(L"identifier"); AbcG::IObject obj = getObjectFromArchive(path,identifier); if(!obj.valid()) return CStatus::OK; AbcG::IVisibilityProperty visibilityProperty = AbcG::GetVisibilityProperty(obj); if(!visibilityProperty.valid()) return CStatus::OK; SampleInfo sampleInfo = getSampleInfo( ctxt.GetParameterValue(L"time"), getTimeSamplingFromObject(obj), visibilityProperty.getNumSamples() ); AbcA::int8_t rawVisibilityValue = visibilityProperty.getValue ( sampleInfo.floorIndex ); AbcG::ObjectVisibility visibilityValue =AbcG::ObjectVisibility ( rawVisibilityValue ); Property prop(ctxt.GetOutputTarget()); switch(visibilityValue) { case AbcG::kVisibilityVisible: { prop.PutParameterValue(L"viewvis",true); prop.PutParameterValue(L"rendvis",true); break; } case AbcG::kVisibilityHidden: { prop.PutParameterValue(L"viewvis",false); prop.PutParameterValue(L"rendvis",false); break; } default: { break; } } return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START( alembic_visibility_Term, CRef& ) return alembicOp_Term(in_ctxt); ESS_CALLBACK_END <|endoftext|>
<commit_before>// Copyright 2015-2018 Elviss Strazdins. All rights reserved. #include "core/Setup.h" #if OUZEL_COMPILE_DIRECT3D11 #include "DepthStencilStateResourceD3D11.hpp" #include "RenderDeviceD3D11.hpp" namespace ouzel { namespace graphics { static D3D11_COMPARISON_FUNC getCompareFunction(DepthStencilState::CompareFunction compareFunction) { switch (compareFunction) { case DepthStencilState::CompareFunction::NEVER: return D3D11_COMPARISON_NEVER; case DepthStencilState::CompareFunction::LESS: return D3D11_COMPARISON_LESS; case DepthStencilState::CompareFunction::EQUAL: return D3D11_COMPARISON_EQUAL; case DepthStencilState::CompareFunction::LESS_EQUAL: return D3D11_COMPARISON_LESS_EQUAL; case DepthStencilState::CompareFunction::GREATER: return D3D11_COMPARISON_GREATER; case DepthStencilState::CompareFunction::NOT_EQUAL: return D3D11_COMPARISON_NOT_EQUAL; case DepthStencilState::CompareFunction::GREATER_EQUAL: return D3D11_COMPARISON_GREATER_EQUAL; case DepthStencilState::CompareFunction::ALWAYS: return D3D11_COMPARISON_ALWAYS; } return D3D11_COMPARISON_NEVER; } DepthStencilStateResourceD3D11::DepthStencilStateResourceD3D11(RenderDeviceD3D11& renderDeviceD3D11, bool initDepthTest, bool initDepthWrite, DepthStencilState::CompareFunction initCompareFunction): RenderResourceD3D11(renderDeviceD3D11) { D3D11_DEPTH_STENCIL_DESC depthStencilStateDesc; depthStencilStateDesc.DepthEnable = initDepthTest ? TRUE : FALSE; depthStencilStateDesc.DepthWriteMask = initDepthWrite ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO; depthStencilStateDesc.DepthFunc = getCompareFunction(initCompareFunction); depthStencilStateDesc.StencilEnable = FALSE; depthStencilStateDesc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK; depthStencilStateDesc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK; depthStencilStateDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; depthStencilStateDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; depthStencilStateDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilStateDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilStateDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; depthStencilStateDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; depthStencilStateDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilStateDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; hr = device->CreateDepthStencilState(&depthStencilStateDesc, &depthStencilState); if (FAILED(hr)) throw SystemError("Failed to create Direct3D 11 depth stencil state, error: " + std::to_string(hr)); } DepthStencilStateResourceD3D11::~DepthStencilStateResourceD3D11() { if (depthStencilState) depthStencilState->Release(); } } // namespace graphics } // namespace ouzel #endif <commit_msg>Fix the Windows build<commit_after>// Copyright 2015-2018 Elviss Strazdins. All rights reserved. #include "core/Setup.h" #if OUZEL_COMPILE_DIRECT3D11 #include "DepthStencilStateResourceD3D11.hpp" #include "RenderDeviceD3D11.hpp" #include "utils/Errors.hpp" namespace ouzel { namespace graphics { static D3D11_COMPARISON_FUNC getCompareFunction(DepthStencilState::CompareFunction compareFunction) { switch (compareFunction) { case DepthStencilState::CompareFunction::NEVER: return D3D11_COMPARISON_NEVER; case DepthStencilState::CompareFunction::LESS: return D3D11_COMPARISON_LESS; case DepthStencilState::CompareFunction::EQUAL: return D3D11_COMPARISON_EQUAL; case DepthStencilState::CompareFunction::LESS_EQUAL: return D3D11_COMPARISON_LESS_EQUAL; case DepthStencilState::CompareFunction::GREATER: return D3D11_COMPARISON_GREATER; case DepthStencilState::CompareFunction::NOT_EQUAL: return D3D11_COMPARISON_NOT_EQUAL; case DepthStencilState::CompareFunction::GREATER_EQUAL: return D3D11_COMPARISON_GREATER_EQUAL; case DepthStencilState::CompareFunction::ALWAYS: return D3D11_COMPARISON_ALWAYS; } return D3D11_COMPARISON_NEVER; } DepthStencilStateResourceD3D11::DepthStencilStateResourceD3D11(RenderDeviceD3D11& renderDeviceD3D11, bool initDepthTest, bool initDepthWrite, DepthStencilState::CompareFunction initCompareFunction): RenderResourceD3D11(renderDeviceD3D11) { D3D11_DEPTH_STENCIL_DESC depthStencilStateDesc; depthStencilStateDesc.DepthEnable = initDepthTest ? TRUE : FALSE; depthStencilStateDesc.DepthWriteMask = initDepthWrite ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO; depthStencilStateDesc.DepthFunc = getCompareFunction(initCompareFunction); depthStencilStateDesc.StencilEnable = FALSE; depthStencilStateDesc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK; depthStencilStateDesc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK; depthStencilStateDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; depthStencilStateDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; depthStencilStateDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilStateDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilStateDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; depthStencilStateDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; depthStencilStateDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilStateDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; HRESULT hr = renderDevice.getDevice()->CreateDepthStencilState(&depthStencilStateDesc, &depthStencilState); if (FAILED(hr)) throw SystemError("Failed to create Direct3D 11 depth stencil state, error: " + std::to_string(hr)); } DepthStencilStateResourceD3D11::~DepthStencilStateResourceD3D11() { if (depthStencilState) depthStencilState->Release(); } } // namespace graphics } // namespace ouzel #endif <|endoftext|>
<commit_before>#ifndef WIZARDBATTLE_RULES_WIZARD_H #define WIZARDBATTLE_RULES_WIZARD_H namespace WizardBattle { namespace Rules { class Wizard { private: public: const unsigned int x, y; const bool alive; Wizard(unsigned int x, unsigned int y) : x(x), y(y), alive(false) { }; const Wizard kill() const; }; } } #endif <commit_msg>shuffled wizard constructor a bit, added definition for kill<commit_after>#ifndef WIZARDBATTLE_RULES_WIZARD_H #define WIZARDBATTLE_RULES_WIZARD_H namespace WizardBattle { namespace Rules { class Wizard { private: Wizard(unsigned int x, unsigned int y, bool alive) : x(x), y(y), alive(alive) { }; public: const unsigned int x, y; const bool alive; Wizard(unsigned int x, unsigned int y) : Wizard(x, y, true) { }; const Wizard kill() const { return Wizard(x, y, false); }; }; } } #endif <|endoftext|>
<commit_before>#include "File.h" #include "Index.h" #include "RegExpIndexer.h" #include "ConsoleLog.h" #include "FieldIndexer.h" #include <tclap/CmdLine.h> #include <iostream> #include <stdexcept> #include <limits.h> #include "ExternalIndexer.h" using namespace std; using namespace TCLAP; namespace { string getRealPath(const string &relPath) { char realPathBuf[PATH_MAX]; auto result = realpath(relPath.c_str(), realPathBuf); if (result == nullptr) return relPath; return string(relPath); } } int Main(int argc, const char *argv[]) { CmdLine cmd("Create indices in a compressed text file"); UnlabeledValueArg<string> inputFile( "input-file", "Read input from <file>", true, "", "file", cmd); SwitchArg verbose("v", "verbose", "Be more verbose", cmd); SwitchArg debug("", "debug", "Be even more verbose", cmd); SwitchArg forceColour("", "colour", "Use colour even on non-TTY", cmd); SwitchArg forceColor("", "color", "Use color even on non-TTY", cmd); SwitchArg numeric("n", "numeric", "Assume the index is numeric", cmd); SwitchArg unique("u", "unique", "Assume each line's index is unique", cmd); ValueArg<uint64_t> checkpointEvery( "", "checkpoint-every", "Create an compression checkpoint every <bytes>", false, 0, "bytes", cmd); ValueArg<string> regex("", "regex", "Create an index using <regex>", false, "", "regex", cmd); ValueArg<uint64_t> skipFirst("", "skip-first", "Skip the first <num> lines", false, 0, "num", cmd); ValueArg<int> field("f", "field", "Create an index using field <num> " "(delimited by -d/--delimiter)", false, 0, "num", cmd); ValueArg<char> delimiter("d", "delimiter", "Use <char> as the field delimiter", false, ' ', "char", cmd); ValueArg<string> externalIndexer( "p", "pipe", "Create indices by piping output through <CMD> which should output " "a single line for each input line. " "Multiple keys should be separated by the --delimiter " "character (which defaults to a space). " "The CMD should be unbuffered " "(man stdbuf(1) for one way of doing this).\n" "Example: --pipe 'jq --raw-output --unbuffered .eventId')", false, "", "CMD", cmd); ValueArg<string> indexFilename("", "index-file", "Store index in <index-file> " "(default <file>.zindex)", false, "", "index-file", cmd); cmd.parse(argc, argv); ConsoleLog log( debug.isSet() ? Log::Severity::Debug : verbose.isSet() ? Log::Severity::Info : Log::Severity::Warning, forceColour.isSet() || forceColor.isSet()); try { auto realPath = getRealPath(inputFile.getValue()); File in(fopen(realPath.c_str(), "rb")); if (in.get() == nullptr) { log.debug("Unable to open ", inputFile.getValue(), " (as ", realPath, ")"); log.error("Could not open ", inputFile.getValue(), " for reading"); return 1; } auto outputFile = indexFilename.isSet() ? indexFilename.getValue() : inputFile.getValue() + ".zindex"; Index::Builder builder(log, move(in), realPath, outputFile, skipFirst.getValue()); if (regex.isSet() && field.isSet()) { throw std::runtime_error( "Sorry; multiple indices are not supported yet"); } if (regex.isSet()) { builder.addIndexer("default", regex.getValue(), numeric.isSet(), unique.isSet(), std::unique_ptr<LineIndexer>( new RegExpIndexer(regex.getValue()))); } if (field.isSet()) { ostringstream name; name << "Field " << field.getValue() << " delimited by '" << delimiter.getValue() << "'"; builder.addIndexer("default", name.str(), numeric.isSet(), unique.isSet(), std::unique_ptr<LineIndexer>( new FieldIndexer(delimiter.getValue(), field.getValue()))); } if (externalIndexer.isSet()) { auto indexer = std::unique_ptr<LineIndexer>( new ExternalIndexer(log, externalIndexer.getValue(), delimiter.getValue())); builder.addIndexer("default", externalIndexer.getValue(), numeric.isSet(), unique.isSet(), std::move(indexer)); } if (checkpointEvery.isSet()) builder.indexEvery(checkpointEvery.getValue()); builder.build(); } catch (const exception &e) { log.error(e.what()); } return 0; } int main(int argc, const char *argv[]) { try { return Main(argc, argv); } catch (const exception &e) { cerr << e.what() << endl; return 1; } } <commit_msg>Typo in the help message<commit_after>#include "File.h" #include "Index.h" #include "RegExpIndexer.h" #include "ConsoleLog.h" #include "FieldIndexer.h" #include <tclap/CmdLine.h> #include <iostream> #include <stdexcept> #include <limits.h> #include "ExternalIndexer.h" using namespace std; using namespace TCLAP; namespace { string getRealPath(const string &relPath) { char realPathBuf[PATH_MAX]; auto result = realpath(relPath.c_str(), realPathBuf); if (result == nullptr) return relPath; return string(relPath); } } int Main(int argc, const char *argv[]) { CmdLine cmd("Create indices in a compressed text file"); UnlabeledValueArg<string> inputFile( "input-file", "Read input from <file>", true, "", "file", cmd); SwitchArg verbose("v", "verbose", "Be more verbose", cmd); SwitchArg debug("", "debug", "Be even more verbose", cmd); SwitchArg forceColour("", "colour", "Use colour even on non-TTY", cmd); SwitchArg forceColor("", "color", "Use color even on non-TTY", cmd); SwitchArg numeric("n", "numeric", "Assume the index is numeric", cmd); SwitchArg unique("u", "unique", "Assume each line's index is unique", cmd); ValueArg<uint64_t> checkpointEvery( "", "checkpoint-every", "Create a compression checkpoint every <bytes>", false, 0, "bytes", cmd); ValueArg<string> regex("", "regex", "Create an index using <regex>", false, "", "regex", cmd); ValueArg<uint64_t> skipFirst("", "skip-first", "Skip the first <num> lines", false, 0, "num", cmd); ValueArg<int> field("f", "field", "Create an index using field <num> " "(delimited by -d/--delimiter)", false, 0, "num", cmd); ValueArg<char> delimiter("d", "delimiter", "Use <char> as the field delimiter", false, ' ', "char", cmd); ValueArg<string> externalIndexer( "p", "pipe", "Create indices by piping output through <CMD> which should output " "a single line for each input line. " "Multiple keys should be separated by the --delimiter " "character (which defaults to a space). " "The CMD should be unbuffered " "(man stdbuf(1) for one way of doing this).\n" "Example: --pipe 'jq --raw-output --unbuffered .eventId')", false, "", "CMD", cmd); ValueArg<string> indexFilename("", "index-file", "Store index in <index-file> " "(default <file>.zindex)", false, "", "index-file", cmd); cmd.parse(argc, argv); ConsoleLog log( debug.isSet() ? Log::Severity::Debug : verbose.isSet() ? Log::Severity::Info : Log::Severity::Warning, forceColour.isSet() || forceColor.isSet()); try { auto realPath = getRealPath(inputFile.getValue()); File in(fopen(realPath.c_str(), "rb")); if (in.get() == nullptr) { log.debug("Unable to open ", inputFile.getValue(), " (as ", realPath, ")"); log.error("Could not open ", inputFile.getValue(), " for reading"); return 1; } auto outputFile = indexFilename.isSet() ? indexFilename.getValue() : inputFile.getValue() + ".zindex"; Index::Builder builder(log, move(in), realPath, outputFile, skipFirst.getValue()); if (regex.isSet() && field.isSet()) { throw std::runtime_error( "Sorry; multiple indices are not supported yet"); } if (regex.isSet()) { builder.addIndexer("default", regex.getValue(), numeric.isSet(), unique.isSet(), std::unique_ptr<LineIndexer>( new RegExpIndexer(regex.getValue()))); } if (field.isSet()) { ostringstream name; name << "Field " << field.getValue() << " delimited by '" << delimiter.getValue() << "'"; builder.addIndexer("default", name.str(), numeric.isSet(), unique.isSet(), std::unique_ptr<LineIndexer>( new FieldIndexer(delimiter.getValue(), field.getValue()))); } if (externalIndexer.isSet()) { auto indexer = std::unique_ptr<LineIndexer>( new ExternalIndexer(log, externalIndexer.getValue(), delimiter.getValue())); builder.addIndexer("default", externalIndexer.getValue(), numeric.isSet(), unique.isSet(), std::move(indexer)); } if (checkpointEvery.isSet()) builder.indexEvery(checkpointEvery.getValue()); builder.build(); } catch (const exception &e) { log.error(e.what()); } return 0; } int main(int argc, const char *argv[]) { try { return Main(argc, argv); } catch (const exception &e) { cerr << e.what() << endl; return 1; } } <|endoftext|>
<commit_before>#ifndef slic3r_GUI_Utils_hpp_ #define slic3r_GUI_Utils_hpp_ #include <memory> #include <string> #include <ostream> #include <functional> #include <boost/optional.hpp> #include <wx/frame.h> #include <wx/dialog.h> #include <wx/event.h> #include <wx/filedlg.h> #include <wx/gdicmn.h> #include <wx/panel.h> #include <wx/dcclient.h> #include <wx/debug.h> class wxCheckBox; class wxTopLevelWindow; class wxRect; namespace Slic3r { namespace GUI { wxTopLevelWindow* find_toplevel_parent(wxWindow *window); void on_window_geometry(wxTopLevelWindow *tlw, std::function<void()> callback); enum { DPI_DEFAULT = 96 }; int get_dpi_for_window(wxWindow *window); struct DpiChangedEvent : public wxEvent { int dpi; wxRect rect; DpiChangedEvent(wxEventType eventType, int dpi, wxRect rect) : wxEvent(0, eventType), dpi(dpi), rect(rect) {} virtual wxEvent *Clone() const { return new DpiChangedEvent(*this); } }; wxDECLARE_EVENT(EVT_DPI_CHANGED, DpiChangedEvent); template<class P> class DPIAware : public P { public: DPIAware(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxDefaultSize, long style=wxDEFAULT_FRAME_STYLE, const wxString &name=wxFrameNameStr) : P(parent, id, title, pos, size, style, name) { m_scale_factor = (float)get_dpi_for_window(this) / (float)DPI_DEFAULT; m_normal_font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); // An analog of em_unit value from GUI_App. m_em_unit = std::max<size_t>(10, 10 * m_scale_factor); m_prev_scale_factor = m_scale_factor; recalc_font(); this->Bind(EVT_DPI_CHANGED, [this](const DpiChangedEvent &evt) { m_scale_factor = (float)evt.dpi / (float)DPI_DEFAULT; if (!m_can_rescale) return; if (is_new_scale_factor()) rescale(evt.rect); }); this->Bind(wxEVT_MOVE_START, [this](wxMoveEvent& event) { event.Skip(); // Suppress application rescaling, when a MainFrame moving is not ended m_can_rescale = false; }); this->Bind(wxEVT_MOVE_END, [this](wxMoveEvent& event) { event.Skip(); m_can_rescale = is_new_scale_factor(); // If scale factor is different after moving of MainFrame ... if (m_can_rescale) // ... rescale application rescale(event.GetRect()); else // set value to _true_ in purpose of possibility of a display dpi changing from System Settings m_can_rescale = true; }); } virtual ~DPIAware() {} float scale_factor() const { return m_scale_factor; } float prev_scale_factor() const { return m_prev_scale_factor; } int em_unit() const { return m_em_unit; } int font_size() const { return m_font_size; } const wxFont& normal_font() const { return m_normal_font; } protected: virtual void on_dpi_changed(const wxRect &suggested_rect) = 0; private: float m_scale_factor; int m_em_unit; int m_font_size; wxFont m_normal_font; float m_prev_scale_factor; bool m_can_rescale{ true }; void recalc_font() { wxClientDC dc(this); const auto metrics = dc.GetFontMetrics(); m_font_size = metrics.height; // m_em_unit = metrics.averageWidth; } // check if new scale is differ from previous bool is_new_scale_factor() const { return fabs(m_scale_factor - m_prev_scale_factor) > 0.001; } // recursive function for scaling fonts for all controls in Window void scale_controls_fonts(wxWindow *window, const float scale_f) { auto children = window->GetChildren(); for (auto child : children) { scale_controls_fonts(child, scale_f); child->SetFont(child->GetFont().Scaled(scale_f)); } window->Layout(); } void rescale(const wxRect &suggested_rect) { this->Freeze(); const float relative_scale_factor = m_scale_factor / m_prev_scale_factor; // rescale fonts of all controls scale_controls_fonts(this, relative_scale_factor); this->SetFont(this->GetFont().Scaled(relative_scale_factor)); // rescale normal_font value m_normal_font = m_normal_font.Scaled(relative_scale_factor); // An analog of em_unit value from GUI_App. m_em_unit = std::max<size_t>(10, 10 * m_scale_factor); // rescale missed controls sizes and images on_dpi_changed(suggested_rect); this->Layout(); this->Thaw(); // reset previous scale factor from current scale factor value m_prev_scale_factor = m_scale_factor; } }; typedef DPIAware<wxFrame> DPIFrame; typedef DPIAware<wxDialog> DPIDialog; class EventGuard { // This is a RAII-style smart-ptr-like guard that will bind any event to any event handler // and unbind it as soon as it goes out of scope or unbind() is called. // This can be used to solve the annoying problem of wx events being delivered to freed objects. private: // This is a way to type-erase both the event type as well as the handler: struct EventStorageBase { virtual ~EventStorageBase() {} }; template<class EvTag, class Fun> struct EventStorageFun : EventStorageBase { wxEvtHandler *emitter; EvTag tag; Fun fun; EventStorageFun(wxEvtHandler *emitter, const EvTag &tag, Fun fun) : emitter(emitter) , tag(tag) , fun(std::move(fun)) { emitter->Bind(this->tag, this->fun); } virtual ~EventStorageFun() { emitter->Unbind(tag, fun); } }; template<typename EvTag, typename Class, typename EvArg, typename EvHandler> struct EventStorageMethod : EventStorageBase { typedef void(Class::* MethodPtr)(EvArg &); wxEvtHandler *emitter; EvTag tag; MethodPtr method; EvHandler *handler; EventStorageMethod(wxEvtHandler *emitter, const EvTag &tag, MethodPtr method, EvHandler *handler) : emitter(emitter) , tag(tag) , method(method) , handler(handler) { emitter->Bind(tag, method, handler); } virtual ~EventStorageMethod() { emitter->Unbind(tag, method, handler); } }; std::unique_ptr<EventStorageBase> event_storage; public: EventGuard() {} EventGuard(const EventGuard&) = delete; EventGuard(EventGuard &&other) : event_storage(std::move(other.event_storage)) {} template<class EvTag, class Fun> EventGuard(wxEvtHandler *emitter, const EvTag &tag, Fun fun) :event_storage(new EventStorageFun<EvTag, Fun>(emitter, tag, std::move(fun))) {} template<typename EvTag, typename Class, typename EvArg, typename EvHandler> EventGuard(wxEvtHandler *emitter, const EvTag &tag, void(Class::* method)(EvArg &), EvHandler *handler) :event_storage(new EventStorageMethod<EvTag, Class, EvArg, EvHandler>(emitter, tag, method, handler)) {} EventGuard& operator=(const EventGuard&) = delete; EventGuard& operator=(EventGuard &&other) { event_storage = std::move(other.event_storage); return *this; } void unbind() { event_storage.reset(nullptr); } explicit operator bool() const { return !!event_storage; } }; class CheckboxFileDialog : public wxFileDialog { public: CheckboxFileDialog(wxWindow *parent, const wxString &checkbox_label, bool checkbox_value, const wxString &message = wxFileSelectorPromptStr, const wxString &default_dir = wxEmptyString, const wxString &default_file = wxEmptyString, const wxString &wildcard = wxFileSelectorDefaultWildcardStr, long style = wxFD_DEFAULT_STYLE, const wxPoint &pos = wxDefaultPosition, const wxSize &size = wxDefaultSize, const wxString &name = wxFileDialogNameStr ); bool get_checkbox_value() const; private: struct ExtraPanel : public wxPanel { wxCheckBox *cbox; ExtraPanel(wxWindow *parent); static wxWindow* ctor(wxWindow *parent); }; wxString checkbox_label; }; class WindowMetrics { private: wxRect rect; bool maximized; WindowMetrics() : maximized(false) {} public: static WindowMetrics from_window(wxTopLevelWindow *window); static boost::optional<WindowMetrics> deserialize(const std::string &str); wxRect get_rect() const { return rect; } bool get_maximized() const { return maximized; } void sanitize_for_display(const wxRect &screen_rect); std::string serialize() const; }; std::ostream& operator<<(std::ostream &os, const WindowMetrics& metrics); }} #endif <commit_msg>Another missing include<commit_after>#ifndef slic3r_GUI_Utils_hpp_ #define slic3r_GUI_Utils_hpp_ #include <memory> #include <string> #include <ostream> #include <functional> #include <boost/optional.hpp> #include <wx/frame.h> #include <wx/dialog.h> #include <wx/event.h> #include <wx/filedlg.h> #include <wx/gdicmn.h> #include <wx/panel.h> #include <wx/dcclient.h> #include <wx/debug.h> #include <wx/settings.h> class wxCheckBox; class wxTopLevelWindow; class wxRect; namespace Slic3r { namespace GUI { wxTopLevelWindow* find_toplevel_parent(wxWindow *window); void on_window_geometry(wxTopLevelWindow *tlw, std::function<void()> callback); enum { DPI_DEFAULT = 96 }; int get_dpi_for_window(wxWindow *window); struct DpiChangedEvent : public wxEvent { int dpi; wxRect rect; DpiChangedEvent(wxEventType eventType, int dpi, wxRect rect) : wxEvent(0, eventType), dpi(dpi), rect(rect) {} virtual wxEvent *Clone() const { return new DpiChangedEvent(*this); } }; wxDECLARE_EVENT(EVT_DPI_CHANGED, DpiChangedEvent); template<class P> class DPIAware : public P { public: DPIAware(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxDefaultSize, long style=wxDEFAULT_FRAME_STYLE, const wxString &name=wxFrameNameStr) : P(parent, id, title, pos, size, style, name) { m_scale_factor = (float)get_dpi_for_window(this) / (float)DPI_DEFAULT; m_normal_font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); // An analog of em_unit value from GUI_App. m_em_unit = std::max<size_t>(10, 10 * m_scale_factor); m_prev_scale_factor = m_scale_factor; recalc_font(); this->Bind(EVT_DPI_CHANGED, [this](const DpiChangedEvent &evt) { m_scale_factor = (float)evt.dpi / (float)DPI_DEFAULT; if (!m_can_rescale) return; if (is_new_scale_factor()) rescale(evt.rect); }); this->Bind(wxEVT_MOVE_START, [this](wxMoveEvent& event) { event.Skip(); // Suppress application rescaling, when a MainFrame moving is not ended m_can_rescale = false; }); this->Bind(wxEVT_MOVE_END, [this](wxMoveEvent& event) { event.Skip(); m_can_rescale = is_new_scale_factor(); // If scale factor is different after moving of MainFrame ... if (m_can_rescale) // ... rescale application rescale(event.GetRect()); else // set value to _true_ in purpose of possibility of a display dpi changing from System Settings m_can_rescale = true; }); } virtual ~DPIAware() {} float scale_factor() const { return m_scale_factor; } float prev_scale_factor() const { return m_prev_scale_factor; } int em_unit() const { return m_em_unit; } int font_size() const { return m_font_size; } const wxFont& normal_font() const { return m_normal_font; } protected: virtual void on_dpi_changed(const wxRect &suggested_rect) = 0; private: float m_scale_factor; int m_em_unit; int m_font_size; wxFont m_normal_font; float m_prev_scale_factor; bool m_can_rescale{ true }; void recalc_font() { wxClientDC dc(this); const auto metrics = dc.GetFontMetrics(); m_font_size = metrics.height; // m_em_unit = metrics.averageWidth; } // check if new scale is differ from previous bool is_new_scale_factor() const { return fabs(m_scale_factor - m_prev_scale_factor) > 0.001; } // recursive function for scaling fonts for all controls in Window void scale_controls_fonts(wxWindow *window, const float scale_f) { auto children = window->GetChildren(); for (auto child : children) { scale_controls_fonts(child, scale_f); child->SetFont(child->GetFont().Scaled(scale_f)); } window->Layout(); } void rescale(const wxRect &suggested_rect) { this->Freeze(); const float relative_scale_factor = m_scale_factor / m_prev_scale_factor; // rescale fonts of all controls scale_controls_fonts(this, relative_scale_factor); this->SetFont(this->GetFont().Scaled(relative_scale_factor)); // rescale normal_font value m_normal_font = m_normal_font.Scaled(relative_scale_factor); // An analog of em_unit value from GUI_App. m_em_unit = std::max<size_t>(10, 10 * m_scale_factor); // rescale missed controls sizes and images on_dpi_changed(suggested_rect); this->Layout(); this->Thaw(); // reset previous scale factor from current scale factor value m_prev_scale_factor = m_scale_factor; } }; typedef DPIAware<wxFrame> DPIFrame; typedef DPIAware<wxDialog> DPIDialog; class EventGuard { // This is a RAII-style smart-ptr-like guard that will bind any event to any event handler // and unbind it as soon as it goes out of scope or unbind() is called. // This can be used to solve the annoying problem of wx events being delivered to freed objects. private: // This is a way to type-erase both the event type as well as the handler: struct EventStorageBase { virtual ~EventStorageBase() {} }; template<class EvTag, class Fun> struct EventStorageFun : EventStorageBase { wxEvtHandler *emitter; EvTag tag; Fun fun; EventStorageFun(wxEvtHandler *emitter, const EvTag &tag, Fun fun) : emitter(emitter) , tag(tag) , fun(std::move(fun)) { emitter->Bind(this->tag, this->fun); } virtual ~EventStorageFun() { emitter->Unbind(tag, fun); } }; template<typename EvTag, typename Class, typename EvArg, typename EvHandler> struct EventStorageMethod : EventStorageBase { typedef void(Class::* MethodPtr)(EvArg &); wxEvtHandler *emitter; EvTag tag; MethodPtr method; EvHandler *handler; EventStorageMethod(wxEvtHandler *emitter, const EvTag &tag, MethodPtr method, EvHandler *handler) : emitter(emitter) , tag(tag) , method(method) , handler(handler) { emitter->Bind(tag, method, handler); } virtual ~EventStorageMethod() { emitter->Unbind(tag, method, handler); } }; std::unique_ptr<EventStorageBase> event_storage; public: EventGuard() {} EventGuard(const EventGuard&) = delete; EventGuard(EventGuard &&other) : event_storage(std::move(other.event_storage)) {} template<class EvTag, class Fun> EventGuard(wxEvtHandler *emitter, const EvTag &tag, Fun fun) :event_storage(new EventStorageFun<EvTag, Fun>(emitter, tag, std::move(fun))) {} template<typename EvTag, typename Class, typename EvArg, typename EvHandler> EventGuard(wxEvtHandler *emitter, const EvTag &tag, void(Class::* method)(EvArg &), EvHandler *handler) :event_storage(new EventStorageMethod<EvTag, Class, EvArg, EvHandler>(emitter, tag, method, handler)) {} EventGuard& operator=(const EventGuard&) = delete; EventGuard& operator=(EventGuard &&other) { event_storage = std::move(other.event_storage); return *this; } void unbind() { event_storage.reset(nullptr); } explicit operator bool() const { return !!event_storage; } }; class CheckboxFileDialog : public wxFileDialog { public: CheckboxFileDialog(wxWindow *parent, const wxString &checkbox_label, bool checkbox_value, const wxString &message = wxFileSelectorPromptStr, const wxString &default_dir = wxEmptyString, const wxString &default_file = wxEmptyString, const wxString &wildcard = wxFileSelectorDefaultWildcardStr, long style = wxFD_DEFAULT_STYLE, const wxPoint &pos = wxDefaultPosition, const wxSize &size = wxDefaultSize, const wxString &name = wxFileDialogNameStr ); bool get_checkbox_value() const; private: struct ExtraPanel : public wxPanel { wxCheckBox *cbox; ExtraPanel(wxWindow *parent); static wxWindow* ctor(wxWindow *parent); }; wxString checkbox_label; }; class WindowMetrics { private: wxRect rect; bool maximized; WindowMetrics() : maximized(false) {} public: static WindowMetrics from_window(wxTopLevelWindow *window); static boost::optional<WindowMetrics> deserialize(const std::string &str); wxRect get_rect() const { return rect; } bool get_maximized() const { return maximized; } void sanitize_for_display(const wxRect &screen_rect); std::string serialize() const; }; std::ostream& operator<<(std::ostream &os, const WindowMetrics& metrics); }} #endif <|endoftext|>
<commit_before>#include <common/buffer.h> #include <ssh/ssh_algorithm_negotiation.h> #include <ssh/ssh_mac.h> #include <ssh/ssh_session.h> namespace { struct ssh_mac_algorithm { const char *rfc4250_name_; CryptoMAC::Algorithm crypto_algorithm_; unsigned size_; }; static const struct ssh_mac_algorithm ssh_mac_algorithms[] = { { "hmac-sha1", CryptoMAC::SHA1, 0 }, { "hmac-sha256", CryptoMAC::SHA256, 0 }, { "hmac-md5", CryptoMAC::MD5, 0 }, { "hmac-ripemd160", CryptoMAC::RIPEMD160, 0 }, { "hmac-sha1-96", CryptoMAC::SHA1, 12 }, { "hmac-md5-96", CryptoMAC::MD5, 12 }, { NULL, CryptoMAC::MD5, 0 } }; class CryptoSSHMAC : public SSH::MAC { LogHandle log_; CryptoMAC::Instance *instance_; public: CryptoSSHMAC(const std::string& xname, CryptoMAC::Instance *instance, unsigned xsize) : SSH::MAC(xname, xsize == 0 ? instance->size() : xsize, instance->size()), log_("/ssh/mac/crypto/" + xname), instance_(instance) { } ~CryptoSSHMAC() { } MAC *clone(void) const { return (new CryptoSSHMAC(name_, instance_->clone(), key_size_)); } bool initialize(const Buffer *key) { return (instance_->initialize(key)); } bool mac(Buffer *out, const Buffer *in) { return (instance_->mac(out, in)); } }; } void SSH::MAC::add_algorithms(Session *session) { const struct ssh_mac_algorithm *alg; for (alg = ssh_mac_algorithms; alg->rfc4250_name_ != NULL; alg++) { const CryptoMAC::Method *method = CryptoMAC::Method::method(alg->crypto_algorithm_); if (method == NULL) { DEBUG("/ssh/mac") << "Could not get method for algorithm: " << alg->crypto_algorithm_; continue; } CryptoMAC::Instance *instance = method->instance(alg->crypto_algorithm_); if (instance == NULL) { DEBUG("/ssh/mac") << "Could not get instance for algorithm: " << alg->crypto_algorithm_; continue; } session->algorithm_negotiation_->add_algorithm(new CryptoSSHMAC(alg->rfc4250_name_, instance, alg->size_)); } } SSH::MAC * SSH::MAC::algorithm(CryptoMAC::Algorithm xalgorithm) { const struct ssh_mac_algorithm *alg; for (alg = ssh_mac_algorithms; alg->rfc4250_name_ != NULL; alg++) { if (xalgorithm != alg->crypto_algorithm_) continue; const CryptoMAC::Method *method = CryptoMAC::Method::method(xalgorithm); if (method == NULL) { ERROR("/ssh/mac") << "Could not get method for algorithm: " << xalgorithm; return (NULL); } CryptoMAC::Instance *instance = method->instance(xalgorithm); if (instance == NULL) { ERROR("/ssh/mac") << "Could not get instance for algorithm: " << xalgorithm; return (NULL); } return (new CryptoSSHMAC(alg->rfc4250_name_, instance, alg->size_)); } ERROR("/ssh/mac") << "No SSH MAC support is available for algorithm: " << xalgorithm; return (NULL); } <commit_msg>Adjust algorithms.<commit_after>#include <common/buffer.h> #include <ssh/ssh_algorithm_negotiation.h> #include <ssh/ssh_mac.h> #include <ssh/ssh_session.h> namespace { struct ssh_mac_algorithm { const char *rfc4250_name_; CryptoMAC::Algorithm crypto_algorithm_; unsigned size_; }; static const struct ssh_mac_algorithm ssh_mac_algorithms[] = { { "hmac-sha1", CryptoMAC::SHA1, 0 }, { "hmac-sha2-256", CryptoMAC::SHA256, 0 }, { "hmac-sha2-512", CryptoMAC::SHA512, 0 }, { "hmac-ripemd160", CryptoMAC::RIPEMD160, 0 }, { "hmac-md5", CryptoMAC::MD5, 0 }, { "hmac-sha1-96", CryptoMAC::SHA1, 12 }, { "hmac-md5-96", CryptoMAC::MD5, 12 }, { NULL, CryptoMAC::MD5, 0 } }; class CryptoSSHMAC : public SSH::MAC { LogHandle log_; CryptoMAC::Instance *instance_; public: CryptoSSHMAC(const std::string& xname, CryptoMAC::Instance *instance, unsigned xsize) : SSH::MAC(xname, xsize == 0 ? instance->size() : xsize, instance->size()), log_("/ssh/mac/crypto/" + xname), instance_(instance) { } ~CryptoSSHMAC() { } MAC *clone(void) const { return (new CryptoSSHMAC(name_, instance_->clone(), key_size_)); } bool initialize(const Buffer *key) { return (instance_->initialize(key)); } bool mac(Buffer *out, const Buffer *in) { return (instance_->mac(out, in)); } }; } void SSH::MAC::add_algorithms(Session *session) { const struct ssh_mac_algorithm *alg; for (alg = ssh_mac_algorithms; alg->rfc4250_name_ != NULL; alg++) { const CryptoMAC::Method *method = CryptoMAC::Method::method(alg->crypto_algorithm_); if (method == NULL) { DEBUG("/ssh/mac") << "Could not get method for algorithm: " << alg->crypto_algorithm_; continue; } CryptoMAC::Instance *instance = method->instance(alg->crypto_algorithm_); if (instance == NULL) { DEBUG("/ssh/mac") << "Could not get instance for algorithm: " << alg->crypto_algorithm_; continue; } session->algorithm_negotiation_->add_algorithm(new CryptoSSHMAC(alg->rfc4250_name_, instance, alg->size_)); } } SSH::MAC * SSH::MAC::algorithm(CryptoMAC::Algorithm xalgorithm) { const struct ssh_mac_algorithm *alg; for (alg = ssh_mac_algorithms; alg->rfc4250_name_ != NULL; alg++) { if (xalgorithm != alg->crypto_algorithm_) continue; const CryptoMAC::Method *method = CryptoMAC::Method::method(xalgorithm); if (method == NULL) { ERROR("/ssh/mac") << "Could not get method for algorithm: " << xalgorithm; return (NULL); } CryptoMAC::Instance *instance = method->instance(xalgorithm); if (instance == NULL) { ERROR("/ssh/mac") << "Could not get instance for algorithm: " << xalgorithm; return (NULL); } return (new CryptoSSHMAC(alg->rfc4250_name_, instance, alg->size_)); } ERROR("/ssh/mac") << "No SSH MAC support is available for algorithm: " << xalgorithm; return (NULL); } <|endoftext|>
<commit_before>/** * Copyright (c) 2011-2014 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin-explorer. * * libbitcoin-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 <bitcoin/explorer/obelisk_client.hpp> #include <boost/filesystem.hpp> #include <czmq++/czmqpp.hpp> #include <bitcoin/bitcoin.hpp> #include <bitcoin/explorer/async_client.hpp> #include <bitcoin/explorer/primitives/cert_key.hpp> #include <bitcoin/explorer/primitives/uri.hpp> using namespace bc; using namespace bc::client; using namespace bc::explorer::primitives; using namespace czmqpp; using boost::filesystem::path; namespace libbitcoin { namespace explorer { constexpr int zmq_no_linger = 0; constexpr int zmq_curve_enabled = 1; obelisk_client::obelisk_client(const period_ms& timeout, uint8_t retries) : socket_(context_, ZMQ_DEALER) { stream_ = std::make_shared<socket_stream>(socket_); auto base_stream = std::static_pointer_cast<message_stream>(stream_); codec_ = std::make_shared<obelisk_codec>(base_stream); codec_->set_timeout(timeout); codec_->set_retries(retries); } obelisk_client::obelisk_client(const connection_type& channel) : obelisk_client(channel.wait, channel.retries) { } bool obelisk_client::connect(const uri& address) { // ZMQ *only* returns 0 or -1 for this call, so make boolean. bool success = socket_.connect(address.to_string()) == zmq_success; if (success) socket_.set_linger(zmq_no_linger); return success; } bool obelisk_client::connect(const uri& address, const cert_key& server_public_cert) { if (!zsys_has_curve()) return false; const auto server_key = server_public_cert.get_base85(); if (!server_key.empty()) socket_.set_curve_serverkey(server_key); return connect(address); } bool obelisk_client::connect(const uri& address, const cert_key& server_public_cert, const path& client_private_cert_path) { if (!zsys_has_curve()) return false; const auto& cert_path = client_private_cert_path.string(); if (!cert_path.empty()) { certificate cert(cert_path); cert.apply(socket_); socket_.set_curve_server(zmq_curve_enabled); } return connect(address, server_public_cert); } bool obelisk_client::connect(const connection_type& channel) { return connect(channel.server, channel.key, channel.cert_path); } std::shared_ptr<obelisk_codec> obelisk_client::get_codec() { return codec_; } bool obelisk_client::resolve_callbacks() { auto delay = static_cast<int>(codec_->wakeup().count()); czmqpp::poller poller; poller.add(stream_->get_socket()); while (delay > 0) { poller.wait(delay); if (poller.terminated()) return false; if (poller.expired()) { // recompute the delay and signal the appropriate error callbacks. delay = static_cast<int>(codec_->wakeup().count()); continue; } stream_->signal_response(codec_); if (codec_->outstanding_call_count() == 0) break; } return true; } void obelisk_client::poll_until_termination(const client::period_ms& timeout) { czmqpp::poller poller; poller.add(stream_->get_socket()); while (true) { poller.wait(static_cast<int>(timeout.count())); if (poller.terminated()) break; if (!poller.expired()) stream_->signal_response(codec_); } } void obelisk_client::poll_until_timeout_cumulative(const period_ms& timeout) { czmqpp::poller poller; poller.add(stream_->get_socket()); // calculate expected expiration time auto expiry = std::chrono::steady_clock::now() + timeout; while (std::chrono::steady_clock::now() < expiry) { // calculate maximum interval from now to expiration auto max_wait_interval = std::chrono::duration_cast<period_ms>( expiry - std::chrono::steady_clock::now()); poller.wait(static_cast<int>(max_wait_interval.count())); if (poller.terminated()) { break; } if (!poller.expired()) { stream_->signal_response(codec_); } } } } // namespace explorer } // namespace libbitcoin <commit_msg>Handle cert load failure error condition.<commit_after>/** * Copyright (c) 2011-2014 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin-explorer. * * libbitcoin-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 <bitcoin/explorer/obelisk_client.hpp> #include <boost/filesystem.hpp> #include <czmq++/czmqpp.hpp> #include <bitcoin/bitcoin.hpp> #include <bitcoin/explorer/async_client.hpp> #include <bitcoin/explorer/primitives/cert_key.hpp> #include <bitcoin/explorer/primitives/uri.hpp> using namespace bc; using namespace bc::client; using namespace bc::explorer::primitives; using namespace czmqpp; using boost::filesystem::path; namespace libbitcoin { namespace explorer { constexpr int zmq_no_linger = 0; constexpr int zmq_curve_enabled = 1; obelisk_client::obelisk_client(const period_ms& timeout, uint8_t retries) : socket_(context_, ZMQ_DEALER) { stream_ = std::make_shared<socket_stream>(socket_); auto base_stream = std::static_pointer_cast<message_stream>(stream_); codec_ = std::make_shared<obelisk_codec>(base_stream); codec_->set_timeout(timeout); codec_->set_retries(retries); } obelisk_client::obelisk_client(const connection_type& channel) : obelisk_client(channel.wait, channel.retries) { } bool obelisk_client::connect(const uri& address) { // ZMQ *only* returns 0 or -1 for this call, so make boolean. bool success = socket_.connect(address.to_string()) == zmq_success; if (success) socket_.set_linger(zmq_no_linger); return success; } bool obelisk_client::connect(const uri& address, const cert_key& server_public_cert) { if (!zsys_has_curve()) return false; const auto server_key = server_public_cert.get_base85(); if (!server_key.empty()) socket_.set_curve_serverkey(server_key); return connect(address); } bool obelisk_client::connect(const uri& address, const cert_key& server_public_cert, const path& client_private_cert_path) { if (!zsys_has_curve()) return false; const auto& cert_path = client_private_cert_path.string(); if (!cert_path.empty()) { certificate cert(cert_path); if (!cert.valid()) return false; cert.apply(socket_); socket_.set_curve_server(zmq_curve_enabled); } return connect(address, server_public_cert); } bool obelisk_client::connect(const connection_type& channel) { return connect(channel.server, channel.key, channel.cert_path); } std::shared_ptr<obelisk_codec> obelisk_client::get_codec() { return codec_; } bool obelisk_client::resolve_callbacks() { auto delay = static_cast<int>(codec_->wakeup().count()); czmqpp::poller poller; poller.add(stream_->get_socket()); while (delay > 0) { poller.wait(delay); if (poller.terminated()) return false; if (poller.expired()) { // recompute the delay and signal the appropriate error callbacks. delay = static_cast<int>(codec_->wakeup().count()); continue; } stream_->signal_response(codec_); if (codec_->outstanding_call_count() == 0) break; } return true; } void obelisk_client::poll_until_termination(const client::period_ms& timeout) { czmqpp::poller poller; poller.add(stream_->get_socket()); while (true) { poller.wait(static_cast<int>(timeout.count())); if (poller.terminated()) break; if (!poller.expired()) stream_->signal_response(codec_); } } void obelisk_client::poll_until_timeout_cumulative(const period_ms& timeout) { czmqpp::poller poller; poller.add(stream_->get_socket()); // calculate expected expiration time auto expiry = std::chrono::steady_clock::now() + timeout; while (std::chrono::steady_clock::now() < expiry) { // calculate maximum interval from now to expiration auto max_wait_interval = std::chrono::duration_cast<period_ms>( expiry - std::chrono::steady_clock::now()); poller.wait(static_cast<int>(max_wait_interval.count())); if (poller.terminated()) { break; } if (!poller.expired()) { stream_->signal_response(codec_); } } } } // namespace explorer } // namespace libbitcoin <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2014 Conrado Miranda Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Each batch has a header with the following format: // 1) Number of entries; // 2) For each entry, the following values: // 2.1) The hash of the task which provided the result; // 2.2) The position of the result inside the file; // 2.3) The size of the result. // // Each entry is of type size_t and the header isn't taken into account for the // maximum file size or entry position. #include "object_archive.hpp" #include <algorithm> #include <boost/filesystem.hpp> ObjectArchive::ObjectArchive(std::string const& filename, size_t max_buffer_size): must_rebuild_file_(false), max_buffer_size_(max_buffer_size), buffer_size_(0) { init(filename); if (max_buffer_size_ < 1) max_buffer_size_ = 1; } ObjectArchive::ObjectArchive(std::string const& filename, std::string const& max_buffer_size): ObjectArchive(filename, 0) { size_t length = max_buffer_size.size(); double buffer_size = atof(max_buffer_size.c_str()); bool changed = false; for (size_t i = 0; i< length && !changed; i++) { switch (max_buffer_size[i]) { case 'k': case 'K': buffer_size *= 1e3; changed = true; break; case 'm': case 'M': buffer_size *= 1e6; changed = true; break; case 'g': case 'G': buffer_size *= 1e9; changed = true; break; } } max_buffer_size_ = buffer_size; if (max_buffer_size_ < 1) max_buffer_size_ = 1; } ObjectArchive::~ObjectArchive() { flush(); } void ObjectArchive::init(std::string const& filename) { flush(); filename_ = filename; buffer_size_ = 0; objects_.clear(); LRU_.clear(); stream_.open(filename, std::ios_base::in | std::ios_base::out | std::ios_base::binary); stream_.seekg(0, std::ios_base::end); // If the file seems ok and has entries, use it. Otherwise, overwrite. if (stream_.good() && stream_.tellg() > 0) { stream_.seekg(0); size_t n_entries; stream_.read((char*)&n_entries, sizeof(size_t)); for (size_t i = 0; i < n_entries; i++) { size_t id, pos, size; stream_.read((char*)&id, sizeof(size_t)); stream_.read((char*)&pos, sizeof(size_t)); stream_.read((char*)&size, sizeof(size_t)); ObjectEntry entry; entry.index_in_file = pos; entry.size = size; entry.modified = false; objects_[id] = entry; } header_offset_ = stream_.tellg(); } else { stream_.open(filename, std::ios_base::in | std::ios_base::out | std::ios_base::binary | std::ios_base::trunc); header_offset_ = 0; } } void ObjectArchive::remove(size_t id) { auto it = objects_.find(id); if (it == objects_.end()) return; ObjectEntry& entry = it->second; if (entry.data.size()) buffer_size_ -= entry.size; objects_.erase(id); LRU_.remove(id); must_rebuild_file_ = true; } size_t ObjectArchive::insert_raw(size_t id, std::string&& data, bool keep_in_buffer) { size_t size = data.size(); if (size > max_buffer_size_) keep_in_buffer = false; remove(id); if (size + buffer_size_ > max_buffer_size_ && keep_in_buffer) unload(max_buffer_size_ - size); buffer_size_ += size; ObjectEntry& entry = objects_[id]; entry.data.swap(data); entry.size = size; entry.modified = true; touch_LRU(id); must_rebuild_file_ = true; if (!keep_in_buffer) write_back(id); return size; } size_t ObjectArchive::load_raw(size_t id, std::string& data, bool keep_in_buffer) { auto it = objects_.find(id); if (it == objects_.end()) return 0; ObjectEntry& entry = it->second; size_t size = entry.size; if (size > max_buffer_size_) keep_in_buffer = false; // If the result isn't in the buffer, we must read it. if (entry.data.size() == 0) { // Only check for size if we have to load. if (size + buffer_size_ > max_buffer_size_) unload(max_buffer_size_ - size); stream_.seekg(entry.index_in_file + header_offset_); std::string& buf = entry.data; buf.resize(size); stream_.read(&buf[0], size); buffer_size_ += size; entry.modified = false; touch_LRU(id); } if (!keep_in_buffer) { data.swap(entry.data); entry.data.clear(); } else data = entry.data; return size; } void ObjectArchive::unload(size_t desired_size) { while (buffer_size_ > desired_size) write_back(LRU_.back()); } std::list<size_t> ObjectArchive::available_objects() const { std::list<size_t> list; for (auto& it : objects_) list.push_front(it.first); return list; } void ObjectArchive::flush() { unload(); if (!must_rebuild_file_) return; must_rebuild_file_ = false; boost::filesystem::path temp_filename; temp_filename = boost::filesystem::temp_directory_path(); temp_filename += '/'; temp_filename += boost::filesystem::unique_path(); std::fstream temp_stream(temp_filename.string(), std::ios_base::in | std::ios_base::out | std::ios_base::binary | std::ios_base::trunc); size_t n_entries = objects_.size(); temp_stream.write((char*)&n_entries, sizeof(size_t)); size_t pos = 0; for (auto& it : objects_) { size_t id, size; ObjectEntry& entry = it.second; id = it.first; size = entry.size; temp_stream.write((char*)&id, sizeof(size_t)); temp_stream.write((char*)&pos, sizeof(size_t)); temp_stream.write((char*)&size, sizeof(size_t)); pos += size; } char* temp_buffer = new char[max_buffer_size_]; for (auto& it : objects_) { ObjectEntry& entry = it.second; stream_.seekg(entry.index_in_file + header_offset_); size_t size = entry.size; // Only uses the allowed buffer memory. for (; size > max_buffer_size_; size -= max_buffer_size_) { stream_.read(temp_buffer, max_buffer_size_); temp_stream.write(temp_buffer, max_buffer_size_); } stream_.read(temp_buffer, size); temp_stream.write(temp_buffer, size); } delete[] temp_buffer; stream_.close(); temp_stream.close(); boost::filesystem::remove(filename_); boost::filesystem::rename(temp_filename, filename_); init(filename_); } bool ObjectArchive::write_back(size_t id) { auto it = objects_.find(id); if (it == objects_.end()) return false; ObjectEntry& entry = it->second; if (entry.modified) { entry.index_in_file = stream_.tellp(); entry.index_in_file -= header_offset_; stream_.write((char*)&entry.data[0], entry.size); entry.modified = false; } entry.data.clear(); buffer_size_ -= entry.size; LRU_.remove(id); must_rebuild_file_ = true; return true; } void ObjectArchive::touch_LRU(size_t id) { LRU_.remove(id); LRU_.push_front(id); } <commit_msg>Removed unnecessary file rebuilding in write back.<commit_after>/* The MIT License (MIT) Copyright (c) 2014 Conrado Miranda Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Each batch has a header with the following format: // 1) Number of entries; // 2) For each entry, the following values: // 2.1) The hash of the task which provided the result; // 2.2) The position of the result inside the file; // 2.3) The size of the result. // // Each entry is of type size_t and the header isn't taken into account for the // maximum file size or entry position. #include "object_archive.hpp" #include <algorithm> #include <boost/filesystem.hpp> ObjectArchive::ObjectArchive(std::string const& filename, size_t max_buffer_size): must_rebuild_file_(false), max_buffer_size_(max_buffer_size), buffer_size_(0) { init(filename); if (max_buffer_size_ < 1) max_buffer_size_ = 1; } ObjectArchive::ObjectArchive(std::string const& filename, std::string const& max_buffer_size): ObjectArchive(filename, 0) { size_t length = max_buffer_size.size(); double buffer_size = atof(max_buffer_size.c_str()); bool changed = false; for (size_t i = 0; i< length && !changed; i++) { switch (max_buffer_size[i]) { case 'k': case 'K': buffer_size *= 1e3; changed = true; break; case 'm': case 'M': buffer_size *= 1e6; changed = true; break; case 'g': case 'G': buffer_size *= 1e9; changed = true; break; } } max_buffer_size_ = buffer_size; if (max_buffer_size_ < 1) max_buffer_size_ = 1; } ObjectArchive::~ObjectArchive() { flush(); } void ObjectArchive::init(std::string const& filename) { flush(); filename_ = filename; buffer_size_ = 0; objects_.clear(); LRU_.clear(); stream_.open(filename, std::ios_base::in | std::ios_base::out | std::ios_base::binary); stream_.seekg(0, std::ios_base::end); // If the file seems ok and has entries, use it. Otherwise, overwrite. if (stream_.good() && stream_.tellg() > 0) { stream_.seekg(0); size_t n_entries; stream_.read((char*)&n_entries, sizeof(size_t)); for (size_t i = 0; i < n_entries; i++) { size_t id, pos, size; stream_.read((char*)&id, sizeof(size_t)); stream_.read((char*)&pos, sizeof(size_t)); stream_.read((char*)&size, sizeof(size_t)); ObjectEntry entry; entry.index_in_file = pos; entry.size = size; entry.modified = false; objects_[id] = entry; } header_offset_ = stream_.tellg(); } else { stream_.open(filename, std::ios_base::in | std::ios_base::out | std::ios_base::binary | std::ios_base::trunc); header_offset_ = 0; } } void ObjectArchive::remove(size_t id) { auto it = objects_.find(id); if (it == objects_.end()) return; ObjectEntry& entry = it->second; if (entry.data.size()) buffer_size_ -= entry.size; objects_.erase(id); LRU_.remove(id); must_rebuild_file_ = true; } size_t ObjectArchive::insert_raw(size_t id, std::string&& data, bool keep_in_buffer) { size_t size = data.size(); if (size > max_buffer_size_) keep_in_buffer = false; remove(id); if (size + buffer_size_ > max_buffer_size_ && keep_in_buffer) unload(max_buffer_size_ - size); buffer_size_ += size; ObjectEntry& entry = objects_[id]; entry.data.swap(data); entry.size = size; entry.modified = true; touch_LRU(id); must_rebuild_file_ = true; if (!keep_in_buffer) write_back(id); return size; } size_t ObjectArchive::load_raw(size_t id, std::string& data, bool keep_in_buffer) { auto it = objects_.find(id); if (it == objects_.end()) return 0; ObjectEntry& entry = it->second; size_t size = entry.size; if (size > max_buffer_size_) keep_in_buffer = false; // If the result isn't in the buffer, we must read it. if (entry.data.size() == 0) { // Only check for size if we have to load. if (size + buffer_size_ > max_buffer_size_) unload(max_buffer_size_ - size); stream_.seekg(entry.index_in_file + header_offset_); std::string& buf = entry.data; buf.resize(size); stream_.read(&buf[0], size); buffer_size_ += size; entry.modified = false; touch_LRU(id); } if (!keep_in_buffer) { data.swap(entry.data); entry.data.clear(); } else data = entry.data; return size; } void ObjectArchive::unload(size_t desired_size) { while (buffer_size_ > desired_size) write_back(LRU_.back()); } std::list<size_t> ObjectArchive::available_objects() const { std::list<size_t> list; for (auto& it : objects_) list.push_front(it.first); return list; } void ObjectArchive::flush() { unload(); if (!must_rebuild_file_) return; must_rebuild_file_ = false; boost::filesystem::path temp_filename; temp_filename = boost::filesystem::temp_directory_path(); temp_filename += '/'; temp_filename += boost::filesystem::unique_path(); std::fstream temp_stream(temp_filename.string(), std::ios_base::in | std::ios_base::out | std::ios_base::binary | std::ios_base::trunc); size_t n_entries = objects_.size(); temp_stream.write((char*)&n_entries, sizeof(size_t)); size_t pos = 0; for (auto& it : objects_) { size_t id, size; ObjectEntry& entry = it.second; id = it.first; size = entry.size; temp_stream.write((char*)&id, sizeof(size_t)); temp_stream.write((char*)&pos, sizeof(size_t)); temp_stream.write((char*)&size, sizeof(size_t)); pos += size; } char* temp_buffer = new char[max_buffer_size_]; for (auto& it : objects_) { ObjectEntry& entry = it.second; stream_.seekg(entry.index_in_file + header_offset_); size_t size = entry.size; // Only uses the allowed buffer memory. for (; size > max_buffer_size_; size -= max_buffer_size_) { stream_.read(temp_buffer, max_buffer_size_); temp_stream.write(temp_buffer, max_buffer_size_); } stream_.read(temp_buffer, size); temp_stream.write(temp_buffer, size); } delete[] temp_buffer; stream_.close(); temp_stream.close(); boost::filesystem::remove(filename_); boost::filesystem::rename(temp_filename, filename_); init(filename_); } bool ObjectArchive::write_back(size_t id) { auto it = objects_.find(id); if (it == objects_.end()) return false; ObjectEntry& entry = it->second; if (entry.modified) { entry.index_in_file = stream_.tellp(); entry.index_in_file -= header_offset_; stream_.write((char*)&entry.data[0], entry.size); entry.modified = false; must_rebuild_file_ = true; } entry.data.clear(); buffer_size_ -= entry.size; LRU_.remove(id); return true; } void ObjectArchive::touch_LRU(size_t id) { LRU_.remove(id); LRU_.push_front(id); } <|endoftext|>
<commit_before>/** * ofxSoundObject.cpp * * Created by Marek Bereza on 10/08/2013. */ #include "ofxSoundObject.h" //---------------------------------------------------- // ofxSoundObject ofxSoundObject::ofxSoundObject() { inputObject = NULL; outputObjectRef = NULL; } ofxSoundObject &ofxSoundObject::connectTo(ofxSoundObject &soundObject) { if (outputObjectRef != NULL) { disconnect(); } outputObjectRef = &soundObject; soundObject.setInput(this); // if we find an infinite loop, we want to disconnect and provide an error if(!checkForInfiniteLoops()) { ofLogError("ofxSoundObject") << "There's an infinite loop in your chain of ofxSoundObjects"; disconnect(); } return soundObject; } void ofxSoundObject::disconnectInput(ofxSoundObject * input){ if (inputObject != NULL) { inputObject = NULL; } } void ofxSoundObject::disconnect(){ outputObjectRef->disconnectInput(this); outputObjectRef =NULL; } void ofxSoundObject::setInput(ofxSoundObject *obj) { inputObject = obj; } ofxSoundObject *ofxSoundObject::getInputObject() { return inputObject; } bool ofxSoundObject::checkForInfiniteLoops() { ofxSoundObject *prev = inputObject; // move up the dsp chain until we find ourselves or the beginning of the chain (input==NULL) while(prev!=this && prev!=NULL) { prev = prev->getInputObject(); } // if we found ourselves, return false (to indicate there's an infinite loop) return (prev==NULL); } // this pulls the audio through from earlier links in the chain void ofxSoundObject::audioOut(ofSoundBuffer &output) { if(inputObject!=NULL) { if(workingBuffer.size()!=output.size()) { ofLogVerbose("ofxSoundObject") << "working buffer size != output buffer size."; workingBuffer.resize(output.size()); workingBuffer.setNumChannels(output.getNumChannels()); workingBuffer.setSampleRate(output.getSampleRate()); } inputObject->audioOut(workingBuffer); } this->process(workingBuffer, output); } //---------------------------------------------------- // ofSoundInput ofxSoundInput::ofxSoundInput() { } // copy audio in to internal buffer void ofxSoundInput::audioIn(ofSoundBuffer &input) { if(inputBuffer.size()!=input.size()) { ofLogVerbose("ofSoundinput::audioIn") << "input buffer size != output buffer size."; inputBuffer.resize(input.size()); inputBuffer.setNumChannels(inputBuffer.getNumChannels()); inputBuffer.setSampleRate(inputBuffer.getSampleRate()); } input.copyTo(inputBuffer); } void ofxSoundInput::audioOut(ofSoundBuffer &output) { if(output.getNumFrames()==inputBuffer.getNumFrames()){ ofLogVerbose("ofSoundinput::audioOut") << "input buffer size != output buffer size."; inputBuffer.resize(output.size()); inputBuffer.setNumChannels(output.getNumChannels()); inputBuffer.setSampleRate(output.getSampleRate()); } inputBuffer.copyTo(output); } <commit_msg>Fixed wrong audio buffer passing values in ofxSoundInput<commit_after>/** * ofxSoundObject.cpp * * Created by Marek Bereza on 10/08/2013. */ #include "ofxSoundObject.h" //---------------------------------------------------- // ofxSoundObject ofxSoundObject::ofxSoundObject() { inputObject = NULL; outputObjectRef = NULL; } ofxSoundObject &ofxSoundObject::connectTo(ofxSoundObject &soundObject) { if (outputObjectRef != NULL) { disconnect(); } outputObjectRef = &soundObject; soundObject.setInput(this); // if we find an infinite loop, we want to disconnect and provide an error if(!checkForInfiniteLoops()) { ofLogError("ofxSoundObject") << "There's an infinite loop in your chain of ofxSoundObjects"; disconnect(); } return soundObject; } void ofxSoundObject::disconnectInput(ofxSoundObject * input){ if (inputObject != NULL) { inputObject = NULL; } } void ofxSoundObject::disconnect(){ outputObjectRef->disconnectInput(this); outputObjectRef =NULL; } void ofxSoundObject::setInput(ofxSoundObject *obj) { inputObject = obj; } ofxSoundObject *ofxSoundObject::getInputObject() { return inputObject; } bool ofxSoundObject::checkForInfiniteLoops() { ofxSoundObject *prev = inputObject; // move up the dsp chain until we find ourselves or the beginning of the chain (input==NULL) while(prev!=this && prev!=NULL) { prev = prev->getInputObject(); } // if we found ourselves, return false (to indicate there's an infinite loop) return (prev==NULL); } // this pulls the audio through from earlier links in the chain void ofxSoundObject::audioOut(ofSoundBuffer &output) { if(inputObject!=NULL) { if(workingBuffer.size()!=output.size()) { ofLogVerbose("ofxSoundObject") << "working buffer size != output buffer size."; workingBuffer.resize(output.size()); workingBuffer.setNumChannels(output.getNumChannels()); workingBuffer.setSampleRate(output.getSampleRate()); } inputObject->audioOut(workingBuffer); } this->process(workingBuffer, output); } //---------------------------------------------------- // ofSoundInput ofxSoundInput::ofxSoundInput() { } // copy audio in to internal buffer void ofxSoundInput::audioIn(ofSoundBuffer &input) { if(inputBuffer.size()!=input.size()) { ofLogVerbose("ofSoundinput::audioIn") << "input buffer size != output buffer size."; inputBuffer.resize(input.size()); inputBuffer.setNumChannels(input.getNumChannels()); inputBuffer.setSampleRate(input.getSampleRate()); } input.copyTo(inputBuffer); } void ofxSoundInput::audioOut(ofSoundBuffer &output) { if(output.getNumFrames()==inputBuffer.getNumFrames()){ ofLogVerbose("ofSoundinput::audioOut") << "input buffer size != output buffer size."; inputBuffer.resize(output.size()); inputBuffer.setNumChannels(output.getNumChannels()); inputBuffer.setSampleRate(output.getSampleRate()); } inputBuffer.copyTo(output); } <|endoftext|>
<commit_before>/******************************************************* SPIDAR-mouse-server for Linux, FreeBSD and Mac OS X Copyright (c) 2013 Naoto Hieda March 3, 2013 Licensed under MIT license. https://github.com/micuat/SPIDAR-mouse-UNIX ofxSpidarMouse.cpp ********************************************************/ #include "ofxSpidarMouse.h" #include "hidapi.h" ofxSpidarMouse::ofxSpidarMouse() { isInitialized = false; isOpened = false; } int ofxSpidarMouse::init() { isInitialized = false; int res; unsigned char buf[256]; #define MAX_STR 255 wchar_t wstr[MAX_STR]; devs = hid_enumerate(0x0, 0x0); cur_dev = devs; while (cur_dev) { printf("Device Found\n type: %04hx %04hx\n path: %s\n serial_number: %ls", cur_dev->vendor_id, cur_dev->product_id, cur_dev->path, cur_dev->serial_number); printf("\n"); printf(" Manufacturer: %ls\n", cur_dev->manufacturer_string); printf(" Product: %ls\n", cur_dev->product_string); printf(" Release: %hx\n", cur_dev->release_number); printf(" Interface: %d\n", cur_dev->interface_number); printf("\n"); cur_dev = cur_dev->next; } hid_free_enumeration(devs); // Set up the command buffer. memset(buf,0x00,sizeof(buf)); buf[0] = 0x01; buf[1] = 0x81; // Open the device using the VID, PID, // and optionally the Serial number. ////handle = hid_open(0x4d8, 0x3f, L"12345"); handle = hid_open(0x4d8, 0x3f, NULL); if (!handle) { printf("unable to open device\n"); return 1; } // Read the Manufacturer String wstr[0] = 0x0000; res = hid_get_manufacturer_string(handle, wstr, MAX_STR); if (res < 0) printf("Unable to read manufacturer string\n"); printf("Manufacturer String: %ls\n", wstr); // Read the Product String wstr[0] = 0x0000; res = hid_get_product_string(handle, wstr, MAX_STR); if (res < 0) printf("Unable to read product string\n"); printf("Product String: %ls\n", wstr); // Read the Serial Number String wstr[0] = 0x0000; res = hid_get_serial_number_string(handle, wstr, MAX_STR); if (res < 0) printf("Unable to read serial number string\n"); printf("Serial Number String: (%d) %ls", wstr[0], wstr); printf("\n"); // Read Indexed String 1 wstr[0] = 0x0000; res = hid_get_indexed_string(handle, 1, wstr, MAX_STR); if (res < 0) printf("Unable to read indexed string 1\n"); printf("Indexed String 1: %ls\n", wstr); // Set the hid_read() function to be non-blocking. hid_set_nonblocking(handle, 1); // Try to read from the device. There shoud be no // data here, but execution should not block. res = hid_read(handle, buf, 17); // Send a Feature Report to the device buf[0] = 0x2; buf[1] = 0xa0; buf[2] = 0x0a; buf[3] = 0x00; buf[4] = 0x00; res = hid_send_feature_report(handle, buf, 17); if (res < 0) { printf("Unable to send a feature report.\n"); } memset(buf,0,sizeof(buf)); // Read a Feature Report from the device buf[0] = 0x2; res = hid_get_feature_report(handle, buf, sizeof(buf)); if (res < 0) { printf("Unable to get a feature report.\n"); printf("%ls\n", hid_error(handle)); } else { // Print out the returned buffer. printf("Feature Report\n "); for (int i = 0; i < res; i++) printf("%02hhx ", buf[i]); printf("\n"); } isInitialized = true; return 0; } ofxSpidarMouse::~ofxSpidarMouse() { if( isOpened ) { close(); } if( isInitialized ) { hid_close(handle); /* Free static HIDAPI objects. */ hid_exit(); } } int ofxSpidarMouse::open() { isOpened = false; if( !isInitialized ) { return 1; } int res; unsigned char buf[256]; float conf_data[4]; // Initialize parameters interG_X=0.0; interG_Y=0.0; SetForce_Mag=0.0; SetForce_Dirunit_X=0.0; SetForce_Dirunit_Y=0.0; Max_Force=1.5; defaultDuration = 4; // 4ms duration = 0; forceStack.clear(); //////////////// Start SPIDAR-mouse memset(buf,0,sizeof(buf)); buf[0] = 0x00; buf[1] = 0x82; res = hid_write(handle, buf, 65); if (res < 0) { printf("Unable to write()\n"); printf("Error: %ls\n", hid_error(handle)); return 1; } // Read requested state. hid_read() has been set to be // non-blocking by the call to hid_set_nonblocking() above. // This loop demonstrates the non-blocking nature of hid_read(). res = 0; while (res == 0) { res = hid_read(handle, buf, sizeof(buf)); if (res == 0) printf("waiting...\n"); if (res < 0) printf("Unable to read()\n"); #ifdef WIN32 Sleep(500); #else usleep(500*1000); #endif } printf("Data read:\n "); // Print out the returned buffer. for (int i = 0; i < res; i++) printf("%02hhx ", buf[i]); printf("\n"); memset(buf,0,sizeof(buf)); conf_data[0] = 0.3; conf_data[1] = 1.5; conf_data[2] = 47.9867; conf_data[3] = 13.1215; MinForce_Bytes = (unsigned char *)&conf_data[0]; MaxForce_Bytes = (unsigned char *)&conf_data[1]; Fun_a_Bytes = (unsigned char *)&conf_data[2]; Fun_b_Bytes = (unsigned char *)&conf_data[3]; buf[0] = 0; buf[1] = 0x80; buf[2] = MinForce_Bytes[0]; buf[3] = MinForce_Bytes[1]; buf[4] = MinForce_Bytes[2]; buf[5] = MinForce_Bytes[3]; buf[6] = MaxForce_Bytes[0]; buf[7] = MaxForce_Bytes[1]; buf[8] = MaxForce_Bytes[2]; buf[9] = MaxForce_Bytes[3]; buf[10] = Fun_a_Bytes[0]; buf[11] = Fun_a_Bytes[1]; buf[12] = Fun_a_Bytes[2]; buf[13] = Fun_a_Bytes[3]; buf[14] = Fun_b_Bytes[0]; buf[15] = Fun_b_Bytes[1]; buf[16] = Fun_b_Bytes[2]; buf[17] = Fun_b_Bytes[3]; res = hid_write(handle, buf, 65); if (res < 0) { printf("Unable to start SPIDAR-mouse: %ls\n", hid_error(handle)); return 1; } setForce(0.0, 0.0); isOpened = true; return 0; } int ofxSpidarMouse::close() { if( !isOpened ) { return 1; } int res; unsigned char buf[256]; buf[0] = 0; buf[1] = 0x99; res = hid_write(handle, buf, 65); if (res < 0) { printf("Unable to close SPIDAR-mouse: %d %ls\n", res, hid_error(handle)); } return 0; } int ofxSpidarMouse::update() { unsigned long curTime = ofGetSystemTime(); if( duration != 0 && (curTime - startTime) > duration ) { setForce(0.0, 0.0); duration = 0; } forceStack.push_back(ofVec2f(Force_XScale, Force_YScale)); if( forceStack.size() > 30 ) { forceStack.erase(forceStack.begin()); } return 0; } int ofxSpidarMouse::setForce(float fx, float fy) { duration = 0; // infinite return sForce(fx, fy); } int ofxSpidarMouse::setForce(float fx, float fy, int d) { startTime = ofGetSystemTime(); if( d < defaultDuration ) { duration = defaultDuration; } else { duration = d; } return sForce(fx, fy); } int ofxSpidarMouse::sForce(float fx, float fy) { if( fabsf(fx) > 1.0 ) { Force_XScale = fx / fabsf(fx); } else { Force_XScale = fx; } if( fabsf(fy) > 1.0 ) { Force_YScale = fy / fabsf(fy); } else { Force_YScale = fy; } if( !isOpened ) { return 1; } Force_X = Force_XScale * Max_Force; Force_Y = Force_YScale * Max_Force; SetForce_Mag = sqrt(Force_X * Force_X + Force_Y * Force_Y); if ( SetForce_Mag > 0.0 ) { SetForce_Dirunit_X = Force_X / SetForce_Mag; SetForce_Dirunit_Y = Force_Y / SetForce_Mag; } int res; unsigned char buf[256]; memset(buf,0x00,sizeof(buf)); buf[0] = 0; buf[1] = 0x97; interG_X_Bytes = (unsigned char *)&interG_X; interG_Y_Bytes = (unsigned char *)&interG_Y; Force_Mag_Bytes = (unsigned char *)&SetForce_Mag; Force_Dirunit_X_Bytes = (unsigned char *)&SetForce_Dirunit_X; Force_Dirunit_Y_Bytes = (unsigned char *)&SetForce_Dirunit_Y; buf[2] = interG_X_Bytes[0]; buf[3] = interG_X_Bytes[1]; buf[4] = interG_X_Bytes[2]; buf[5] = interG_X_Bytes[3]; buf[6] = interG_Y_Bytes[0]; buf[7] = interG_Y_Bytes[1]; buf[8] = interG_Y_Bytes[2]; buf[9] = interG_Y_Bytes[3]; buf[10] = Force_Mag_Bytes[0] ; buf[11] = Force_Mag_Bytes[1] ; buf[12] = Force_Mag_Bytes[2] ; buf[13] = Force_Mag_Bytes[3] ; buf[14] = Force_Dirunit_X_Bytes[0] ; buf[15] = Force_Dirunit_X_Bytes[1] ; buf[16] = Force_Dirunit_X_Bytes[2] ; buf[17] = Force_Dirunit_X_Bytes[3] ; buf[18] = Force_Dirunit_Y_Bytes[0] ; buf[19] = Force_Dirunit_Y_Bytes[1] ; buf[20] = Force_Dirunit_Y_Bytes[2] ; buf[21] = Force_Dirunit_Y_Bytes[3] ; res = hid_write(handle, buf, 65); if (res < 0) { printf("Unable to make feedback: %ls\n", hid_error(handle)); return 1; } return 0; } void ofxSpidarMouse::draw(int col = 0x000000) { ofVec2f circleCenter(80, 100); int r = 30; string info = ""; info += "X Value: "+ofToString(Force_XScale, 3)+"\n"; info += "Y Value: "+ofToString(Force_YScale, 3)+"\n\n"; ofSetHexColor(col); ofDrawBitmapString(info, 30, 30); ofFill(); for( int i = 0 ; i < forceStack.size() ; i++ ) { ofSetColor(i * 6); if( fabsf(forceStack[i].x) > 0.01 || fabsf(forceStack[i].y) > 0.01 ) { ofCircle(circleCenter + forceStack[i] * r * i / 30, 3); } } ofNoFill(); ofSetHexColor(col); ofCircle(circleCenter, r * 1.41); ofCircle(circleCenter, r * 1.41 / 2); }<commit_msg>Improved debug window<commit_after>/******************************************************* SPIDAR-mouse-server for Linux, FreeBSD and Mac OS X Copyright (c) 2013 Naoto Hieda March 3, 2013 Licensed under MIT license. https://github.com/micuat/SPIDAR-mouse-UNIX ofxSpidarMouse.cpp ********************************************************/ #include "ofxSpidarMouse.h" #include "hidapi.h" ofxSpidarMouse::ofxSpidarMouse() { isInitialized = false; isOpened = false; } int ofxSpidarMouse::init() { isInitialized = false; int res; unsigned char buf[256]; #define MAX_STR 255 wchar_t wstr[MAX_STR]; devs = hid_enumerate(0x0, 0x0); cur_dev = devs; while (cur_dev) { printf("Device Found\n type: %04hx %04hx\n path: %s\n serial_number: %ls", cur_dev->vendor_id, cur_dev->product_id, cur_dev->path, cur_dev->serial_number); printf("\n"); printf(" Manufacturer: %ls\n", cur_dev->manufacturer_string); printf(" Product: %ls\n", cur_dev->product_string); printf(" Release: %hx\n", cur_dev->release_number); printf(" Interface: %d\n", cur_dev->interface_number); printf("\n"); cur_dev = cur_dev->next; } hid_free_enumeration(devs); // Set up the command buffer. memset(buf,0x00,sizeof(buf)); buf[0] = 0x01; buf[1] = 0x81; // Open the device using the VID, PID, // and optionally the Serial number. ////handle = hid_open(0x4d8, 0x3f, L"12345"); handle = hid_open(0x4d8, 0x3f, NULL); if (!handle) { printf("unable to open device\n"); return 1; } // Read the Manufacturer String wstr[0] = 0x0000; res = hid_get_manufacturer_string(handle, wstr, MAX_STR); if (res < 0) printf("Unable to read manufacturer string\n"); printf("Manufacturer String: %ls\n", wstr); // Read the Product String wstr[0] = 0x0000; res = hid_get_product_string(handle, wstr, MAX_STR); if (res < 0) printf("Unable to read product string\n"); printf("Product String: %ls\n", wstr); // Read the Serial Number String wstr[0] = 0x0000; res = hid_get_serial_number_string(handle, wstr, MAX_STR); if (res < 0) printf("Unable to read serial number string\n"); printf("Serial Number String: (%d) %ls", wstr[0], wstr); printf("\n"); // Read Indexed String 1 wstr[0] = 0x0000; res = hid_get_indexed_string(handle, 1, wstr, MAX_STR); if (res < 0) printf("Unable to read indexed string 1\n"); printf("Indexed String 1: %ls\n", wstr); // Set the hid_read() function to be non-blocking. hid_set_nonblocking(handle, 1); // Try to read from the device. There shoud be no // data here, but execution should not block. res = hid_read(handle, buf, 17); // Send a Feature Report to the device buf[0] = 0x2; buf[1] = 0xa0; buf[2] = 0x0a; buf[3] = 0x00; buf[4] = 0x00; res = hid_send_feature_report(handle, buf, 17); if (res < 0) { printf("Unable to send a feature report.\n"); } memset(buf,0,sizeof(buf)); // Read a Feature Report from the device buf[0] = 0x2; res = hid_get_feature_report(handle, buf, sizeof(buf)); if (res < 0) { printf("Unable to get a feature report.\n"); printf("%ls\n", hid_error(handle)); } else { // Print out the returned buffer. printf("Feature Report\n "); for (int i = 0; i < res; i++) printf("%02hhx ", buf[i]); printf("\n"); } isInitialized = true; return 0; } ofxSpidarMouse::~ofxSpidarMouse() { if( isOpened ) { close(); } if( isInitialized ) { hid_close(handle); /* Free static HIDAPI objects. */ hid_exit(); } } int ofxSpidarMouse::open() { isOpened = false; if( !isInitialized ) { return 1; } int res; unsigned char buf[256]; float conf_data[4]; // Initialize parameters interG_X=0.0; interG_Y=0.0; SetForce_Mag=0.0; SetForce_Dirunit_X=0.0; SetForce_Dirunit_Y=0.0; Max_Force=1.5; defaultDuration = 4; // 4ms duration = 0; forceStack.clear(); //////////////// Start SPIDAR-mouse memset(buf,0,sizeof(buf)); buf[0] = 0x00; buf[1] = 0x82; res = hid_write(handle, buf, 65); if (res < 0) { printf("Unable to write()\n"); printf("Error: %ls\n", hid_error(handle)); return 1; } // Read requested state. hid_read() has been set to be // non-blocking by the call to hid_set_nonblocking() above. // This loop demonstrates the non-blocking nature of hid_read(). res = 0; while (res == 0) { res = hid_read(handle, buf, sizeof(buf)); if (res == 0) printf("waiting...\n"); if (res < 0) printf("Unable to read()\n"); #ifdef WIN32 Sleep(500); #else usleep(500*1000); #endif } printf("Data read:\n "); // Print out the returned buffer. for (int i = 0; i < res; i++) printf("%02hhx ", buf[i]); printf("\n"); memset(buf,0,sizeof(buf)); conf_data[0] = 0.3; conf_data[1] = 1.5; conf_data[2] = 47.9867; conf_data[3] = 13.1215; MinForce_Bytes = (unsigned char *)&conf_data[0]; MaxForce_Bytes = (unsigned char *)&conf_data[1]; Fun_a_Bytes = (unsigned char *)&conf_data[2]; Fun_b_Bytes = (unsigned char *)&conf_data[3]; buf[0] = 0; buf[1] = 0x80; buf[2] = MinForce_Bytes[0]; buf[3] = MinForce_Bytes[1]; buf[4] = MinForce_Bytes[2]; buf[5] = MinForce_Bytes[3]; buf[6] = MaxForce_Bytes[0]; buf[7] = MaxForce_Bytes[1]; buf[8] = MaxForce_Bytes[2]; buf[9] = MaxForce_Bytes[3]; buf[10] = Fun_a_Bytes[0]; buf[11] = Fun_a_Bytes[1]; buf[12] = Fun_a_Bytes[2]; buf[13] = Fun_a_Bytes[3]; buf[14] = Fun_b_Bytes[0]; buf[15] = Fun_b_Bytes[1]; buf[16] = Fun_b_Bytes[2]; buf[17] = Fun_b_Bytes[3]; res = hid_write(handle, buf, 65); if (res < 0) { printf("Unable to start SPIDAR-mouse: %ls\n", hid_error(handle)); return 1; } setForce(0.0, 0.0); isOpened = true; return 0; } int ofxSpidarMouse::close() { if( !isOpened ) { return 1; } int res; unsigned char buf[256]; buf[0] = 0; buf[1] = 0x99; res = hid_write(handle, buf, 65); if (res < 0) { printf("Unable to close SPIDAR-mouse: %d %ls\n", res, hid_error(handle)); } return 0; } int ofxSpidarMouse::update() { unsigned long curTime = ofGetSystemTime(); if( duration != 0 && (curTime - startTime) > duration ) { setForce(0.0, 0.0); duration = 0; } forceStack.push_back(ofVec2f(Force_XScale, Force_YScale)); if( forceStack.size() > 30 ) { forceStack.erase(forceStack.begin()); } return 0; } int ofxSpidarMouse::setForce(float fx, float fy) { duration = 0; // infinite return sForce(fx, fy); } int ofxSpidarMouse::setForce(float fx, float fy, int d) { startTime = ofGetSystemTime(); if( d < defaultDuration ) { duration = defaultDuration; } else { duration = d; } return sForce(fx, fy); } int ofxSpidarMouse::sForce(float fx, float fy) { if( fabsf(fx) > 1.0 ) { Force_XScale = fx / fabsf(fx); } else { Force_XScale = fx; } if( fabsf(fy) > 1.0 ) { Force_YScale = fy / fabsf(fy); } else { Force_YScale = fy; } if( !isOpened ) { return 1; } Force_X = Force_XScale * Max_Force; Force_Y = Force_YScale * Max_Force; SetForce_Mag = sqrt(Force_X * Force_X + Force_Y * Force_Y); if ( SetForce_Mag > 0.0 ) { SetForce_Dirunit_X = Force_X / SetForce_Mag; SetForce_Dirunit_Y = Force_Y / SetForce_Mag; } int res; unsigned char buf[256]; memset(buf,0x00,sizeof(buf)); buf[0] = 0; buf[1] = 0x97; interG_X_Bytes = (unsigned char *)&interG_X; interG_Y_Bytes = (unsigned char *)&interG_Y; Force_Mag_Bytes = (unsigned char *)&SetForce_Mag; Force_Dirunit_X_Bytes = (unsigned char *)&SetForce_Dirunit_X; Force_Dirunit_Y_Bytes = (unsigned char *)&SetForce_Dirunit_Y; buf[2] = interG_X_Bytes[0]; buf[3] = interG_X_Bytes[1]; buf[4] = interG_X_Bytes[2]; buf[5] = interG_X_Bytes[3]; buf[6] = interG_Y_Bytes[0]; buf[7] = interG_Y_Bytes[1]; buf[8] = interG_Y_Bytes[2]; buf[9] = interG_Y_Bytes[3]; buf[10] = Force_Mag_Bytes[0] ; buf[11] = Force_Mag_Bytes[1] ; buf[12] = Force_Mag_Bytes[2] ; buf[13] = Force_Mag_Bytes[3] ; buf[14] = Force_Dirunit_X_Bytes[0] ; buf[15] = Force_Dirunit_X_Bytes[1] ; buf[16] = Force_Dirunit_X_Bytes[2] ; buf[17] = Force_Dirunit_X_Bytes[3] ; buf[18] = Force_Dirunit_Y_Bytes[0] ; buf[19] = Force_Dirunit_Y_Bytes[1] ; buf[20] = Force_Dirunit_Y_Bytes[2] ; buf[21] = Force_Dirunit_Y_Bytes[3] ; res = hid_write(handle, buf, 65); if (res < 0) { printf("Unable to make feedback: %ls\n", hid_error(handle)); return 1; } return 0; } void ofxSpidarMouse::draw(int col = 0x000000) { ofVec2f circleCenter(80, 100); int r = 30; string info = ""; info += "X Value: "+ofToString(Force_XScale, 3)+"\n"; info += "Y Value: "+ofToString(Force_YScale, 3)+"\n\n"; ofSetHexColor(col); ofDrawBitmapString(info, 30, 30); ofFill(); for( int i = 0 ; i < forceStack.size() ; i++ ) { ofSetColor(i * 6); if( fabsf(forceStack[i].x) > 0.01 || fabsf(forceStack[i].y) > 0.01 ) { ofPushMatrix(); ofTranslate(circleCenter + forceStack[i] * r * i / 30); ofRotateZ(atan2(forceStack[i].y, forceStack[i].x)/M_PI*180); ofRect(-2, -4, 4, 8); ofPopMatrix(); } } ofNoFill(); ofSetHexColor(col); ofCircle(circleCenter, r * 1.41); ofCircle(circleCenter, r * 1.41 / 2); }<|endoftext|>
<commit_before> // The files containing the tree of child classes of |DynamicFrame| must be // included in the order of inheritance to avoid circular dependencies. This // class will end up being reincluded as part of the implementation of its // parent. #ifndef PRINCIPIA_PHYSICS_DYNAMIC_FRAME_HPP_ #include "physics/dynamic_frame.hpp" #else #ifndef PRINCIPIA_PHYSICS_BODY_CENTRED_BODY_DIRECTION_DYNAMIC_FRAME_HPP_ #define PRINCIPIA_PHYSICS_BODY_CENTRED_BODY_DIRECTION_DYNAMIC_FRAME_HPP_ #include "base/not_null.hpp" #include "geometry/grassmann.hpp" #include "geometry/named_quantities.hpp" #include "geometry/rotation.hpp" #include "physics/continuous_trajectory.hpp" #include "physics/degrees_of_freedom.hpp" #include "physics/dynamic_frame.hpp" #include "physics/ephemeris.hpp" #include "physics/massive_body.hpp" #include "physics/rigid_motion.hpp" #include "quantities/named_quantities.hpp" namespace principia { namespace physics { namespace internal_body_centred_body_direction_dynamic_frame { using base::not_null; using geometry::AngularVelocity; using geometry::Instant; using geometry::Position; using geometry::Rotation; using geometry::Vector; using quantities::Acceleration; // The origin of the frame is the center of mass of the primary body. The X axis // points to the secondary. The Y axis is in the direction of the velocity of // the secondary with respect to the primary. The Z axis is in the direction of // the angular velocity of the system. The basis has the same orientation as // |InertialFrame|. template<typename InertialFrame, typename ThisFrame> class BodyCentredBodyDirectionDynamicFrame : public DynamicFrame<InertialFrame, ThisFrame> { public: BodyCentredBodyDirectionDynamicFrame( not_null<Ephemeris<InertialFrame> const*> const ephemeris, not_null<MassiveBody const*> const primary, not_null<MassiveBody const*> const secondary); RigidMotion<InertialFrame, ThisFrame> ToThisFrameAtTime( Instant const& t) const override; void WriteToMessage( not_null<serialization::DynamicFrame*> const message) const override; static not_null<std::unique_ptr<BodyCentredBodyDirectionDynamicFrame>> ReadFromMessage( not_null<Ephemeris<InertialFrame> const*> const ephemeris, serialization::BodyCentredBodyDirectionDynamicFrame const& message); private: Vector<Acceleration, InertialFrame> GravitationalAcceleration( Instant const& t, Position<InertialFrame> const& q) const override; AcceleratedRigidMotion<InertialFrame, ThisFrame> MotionOfThisFrame( Instant const& t) const override; // Fills |*rotation| with the rotation that maps the basis of |InertialFrame| // to the basis of |ThisFrame|. Fills |*angular_frequency| with the // corresponding angular velocity. static void ComputeAngularDegreesOfFreedom( DegreesOfFreedom<InertialFrame> const& primary_degrees_of_freedom, DegreesOfFreedom<InertialFrame> const& secondary_degrees_of_freedom, not_null<Rotation<InertialFrame, ThisFrame>*> const rotation, not_null<AngularVelocity<InertialFrame>*> const angular_velocity); not_null<Ephemeris<InertialFrame> const*> const ephemeris_; not_null<MassiveBody const*> const primary_; not_null<MassiveBody const*> const secondary_; not_null<ContinuousTrajectory<InertialFrame> const*> const primary_trajectory_; not_null<ContinuousTrajectory<InertialFrame> const*> const secondary_trajectory_; mutable typename ContinuousTrajectory<InertialFrame>::Hint primary_hint_; mutable typename ContinuousTrajectory<InertialFrame>::Hint secondary_hint_; }; } // namespace internal_body_centred_body_direction_dynamic_frame using internal_body_centred_body_direction_dynamic_frame:: BodyCentredBodyDirectionDynamicFrame; } // namespace physics } // namespace principia #include "physics/body_centred_body_direction_dynamic_frame_body.hpp" #endif // PRINCIPIA_PHYSICS_BODY_CENTRED_BODY_DIRECTION_DYNAMIC_FRAME_HPP_ #endif // PRINCIPIA_PHYSICS_DYNAMIC_FRAME_HPP_ <commit_msg>Lint.<commit_after> // The files containing the tree of child classes of |DynamicFrame| must be // included in the order of inheritance to avoid circular dependencies. This // class will end up being reincluded as part of the implementation of its // parent. #ifndef PRINCIPIA_PHYSICS_DYNAMIC_FRAME_HPP_ #include "physics/dynamic_frame.hpp" #else #ifndef PRINCIPIA_PHYSICS_BODY_CENTRED_BODY_DIRECTION_DYNAMIC_FRAME_HPP_ #define PRINCIPIA_PHYSICS_BODY_CENTRED_BODY_DIRECTION_DYNAMIC_FRAME_HPP_ #include "base/not_null.hpp" #include "geometry/grassmann.hpp" #include "geometry/named_quantities.hpp" #include "geometry/rotation.hpp" #include "physics/continuous_trajectory.hpp" #include "physics/degrees_of_freedom.hpp" #include "physics/dynamic_frame.hpp" #include "physics/ephemeris.hpp" #include "physics/massive_body.hpp" #include "physics/rigid_motion.hpp" #include "quantities/named_quantities.hpp" namespace principia { namespace physics { namespace internal_body_centred_body_direction_dynamic_frame { using base::not_null; using geometry::AngularVelocity; using geometry::Instant; using geometry::Position; using geometry::Rotation; using geometry::Vector; using quantities::Acceleration; // The origin of the frame is the center of mass of the primary body. The X // axis points to the secondary. The Y axis is in the direction of the velocity // of the secondary with respect to the primary. The Z axis is in the direction // of the angular velocity of the system. The basis has the same orientation as // |InertialFrame|. template<typename InertialFrame, typename ThisFrame> class BodyCentredBodyDirectionDynamicFrame : public DynamicFrame<InertialFrame, ThisFrame> { public: BodyCentredBodyDirectionDynamicFrame( not_null<Ephemeris<InertialFrame> const*> const ephemeris, not_null<MassiveBody const*> const primary, not_null<MassiveBody const*> const secondary); RigidMotion<InertialFrame, ThisFrame> ToThisFrameAtTime( Instant const& t) const override; void WriteToMessage( not_null<serialization::DynamicFrame*> const message) const override; static not_null<std::unique_ptr<BodyCentredBodyDirectionDynamicFrame>> ReadFromMessage( not_null<Ephemeris<InertialFrame> const*> const ephemeris, serialization::BodyCentredBodyDirectionDynamicFrame const& message); private: Vector<Acceleration, InertialFrame> GravitationalAcceleration( Instant const& t, Position<InertialFrame> const& q) const override; AcceleratedRigidMotion<InertialFrame, ThisFrame> MotionOfThisFrame( Instant const& t) const override; // Fills |*rotation| with the rotation that maps the basis of |InertialFrame| // to the basis of |ThisFrame|. Fills |*angular_frequency| with the // corresponding angular velocity. static void ComputeAngularDegreesOfFreedom( DegreesOfFreedom<InertialFrame> const& primary_degrees_of_freedom, DegreesOfFreedom<InertialFrame> const& secondary_degrees_of_freedom, not_null<Rotation<InertialFrame, ThisFrame>*> const rotation, not_null<AngularVelocity<InertialFrame>*> const angular_velocity); not_null<Ephemeris<InertialFrame> const*> const ephemeris_; not_null<MassiveBody const*> const primary_; not_null<MassiveBody const*> const secondary_; not_null<ContinuousTrajectory<InertialFrame> const*> const primary_trajectory_; not_null<ContinuousTrajectory<InertialFrame> const*> const secondary_trajectory_; mutable typename ContinuousTrajectory<InertialFrame>::Hint primary_hint_; mutable typename ContinuousTrajectory<InertialFrame>::Hint secondary_hint_; }; } // namespace internal_body_centred_body_direction_dynamic_frame using internal_body_centred_body_direction_dynamic_frame:: BodyCentredBodyDirectionDynamicFrame; } // namespace physics } // namespace principia #include "physics/body_centred_body_direction_dynamic_frame_body.hpp" #endif // PRINCIPIA_PHYSICS_BODY_CENTRED_BODY_DIRECTION_DYNAMIC_FRAME_HPP_ #endif // PRINCIPIA_PHYSICS_DYNAMIC_FRAME_HPP_ <|endoftext|>
<commit_before>/* * AscEmu Framework based on ArcEmu MMORPG Server * Copyright (c) 2014-2020 AscEmu Team <http://www.ascemu.org> * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/> * Copyright (C) 2005-2007 Ascent Team * * 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 * 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 "StdAfx.h" #include "Storage/MySQLDataStore.hpp" #include "Server/MainServerDefines.h" #include "CellHandler.h" #include "WorldCreator.h" // Class Map // Holder for all instances of each mapmgr, handles transferring players between, and template holding. Map::Map(uint32 mapid, MySQLStructure::MapInfo const* inf) { memset(spawns, 0, sizeof(CellSpawns*) * _sizeX); _mapInfo = inf; _mapId = mapid; //new stuff Load Spawns LoadSpawns(false); // get our name if (_mapInfo) name = _mapInfo->name; else name = "Unknown"; } Map::~Map() { LogNotice("Map : ~Map %u", this->_mapId); for (uint32 x = 0; x < _sizeX; x++) { if (spawns[x]) { for (uint32 y = 0; y < _sizeY; y++) { if (spawns[x][y]) { CellSpawns* sp = spawns[x][y]; for (CreatureSpawnList::iterator i = sp->CreatureSpawns.begin(); i != sp->CreatureSpawns.end(); ++i) delete(*i); for (GameobjectSpawnList::iterator it = sp->GameobjectSpawns.begin(); it != sp->GameobjectSpawns.end(); ++it) delete(*it); delete sp; spawns[x][y] = NULL; } } delete[] spawns[x]; } } for (CreatureSpawnList::iterator i = staticSpawns.CreatureSpawns.begin(); i != staticSpawns.CreatureSpawns.end(); ++i) delete *i; for (GameobjectSpawnList::iterator i = staticSpawns.GameobjectSpawns.begin(); i != staticSpawns.GameobjectSpawns.end(); ++i) delete *i; } std::string Map::GetMapName() { return name; } CellSpawns* Map::GetSpawnsList(uint32 cellx, uint32 celly) { ARCEMU_ASSERT(cellx < _sizeX); ARCEMU_ASSERT(celly < _sizeY); if (spawns[cellx] == NULL) return NULL; return spawns[cellx][celly]; } CellSpawns* Map::GetSpawnsListAndCreate(uint32 cellx, uint32 celly) { ARCEMU_ASSERT(cellx < _sizeX); ARCEMU_ASSERT(celly < _sizeY); if (spawns[cellx] == NULL) { spawns[cellx] = new CellSpawns*[_sizeY]; memset(spawns[cellx], 0, sizeof(CellSpawns*)*_sizeY); } if (spawns[cellx][celly] == 0) spawns[cellx][celly] = new CellSpawns; return spawns[cellx][celly]; } #define CREATURESPAWNSFIELDCOUNT 27 #define GOSPAWNSFIELDCOUNT 18 void Map::LoadSpawns(bool reload) { if (reload) //perform cleanup { for (uint32 x = 0; x < _sizeX; x++) { for (uint32 y = 0; y < _sizeY; y++) { if (spawns[x][y]) { CellSpawns* sp = spawns[x][y]; for (CreatureSpawnList::iterator i = sp->CreatureSpawns.begin(); i != sp->CreatureSpawns.end(); ++i) delete(*i); for (GameobjectSpawnList::iterator it = sp->GameobjectSpawns.begin(); it != sp->GameobjectSpawns.end(); ++it) delete(*it); delete sp; spawns[x][y] = NULL; } } } } CreatureSpawnCount = 0; for (auto cspawn : sMySQLStore._creatureSpawnsStore[this->_mapId]) { uint32 cellx = CellHandler<MapMgr>::GetPosX(cspawn->x); uint32 celly = CellHandler<MapMgr>::GetPosY(cspawn->y); if (!spawns[cellx]) { spawns[cellx] = new CellSpawns * [_sizeY]; memset(spawns[cellx], 0, sizeof(CellSpawns*) * _sizeY); } if (!spawns[cellx][celly]) spawns[cellx][celly] = new CellSpawns; spawns[cellx][celly]->CreatureSpawns.push_back(cspawn); ++CreatureSpawnCount; } GameObjectSpawnCount = 0; for (auto go_spawn : sMySQLStore._gameobjectSpawnsStore[this->_mapId]) { if (go_spawn->overrides & GAMEOBJECT_MAPWIDE) { staticSpawns.GameobjectSpawns.push_back(go_spawn); //We already have a staticSpawns in the Map class, and it does just the right thing ++GameObjectSpawnCount; } else { // Zyres: transporter stuff if (sMySQLStore.getGameObjectProperties(go_spawn->entry)->type == 11 || sMySQLStore.getGameObjectProperties(go_spawn->entry)->type == 15) { staticSpawns.GameobjectSpawns.push_back(go_spawn); } else { uint32 cellx = CellHandler<MapMgr>::GetPosX(go_spawn->position_x); uint32 celly = CellHandler<MapMgr>::GetPosY(go_spawn->position_y); if (spawns[cellx] == NULL) { spawns[cellx] = new CellSpawns * [_sizeY]; memset(spawns[cellx], 0, sizeof(CellSpawns*) * _sizeY); } if (!spawns[cellx][celly]) spawns[cellx][celly] = new CellSpawns; } ++GameObjectSpawnCount; } } LogDetail("MapMgr : %u creatures / %u gobjects on map %u cached.", CreatureSpawnCount, GameObjectSpawnCount, _mapId); } <commit_msg>Fix "no normal spawns on Map" @aaron02<commit_after>/* * AscEmu Framework based on ArcEmu MMORPG Server * Copyright (c) 2014-2020 AscEmu Team <http://www.ascemu.org> * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/> * Copyright (C) 2005-2007 Ascent Team * * 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 * 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 "StdAfx.h" #include "Storage/MySQLDataStore.hpp" #include "Server/MainServerDefines.h" #include "CellHandler.h" #include "WorldCreator.h" // Class Map // Holder for all instances of each mapmgr, handles transferring players between, and template holding. Map::Map(uint32 mapid, MySQLStructure::MapInfo const* inf) { memset(spawns, 0, sizeof(CellSpawns*) * _sizeX); _mapInfo = inf; _mapId = mapid; //new stuff Load Spawns LoadSpawns(false); // get our name if (_mapInfo) name = _mapInfo->name; else name = "Unknown"; } Map::~Map() { LogNotice("Map : ~Map %u", this->_mapId); for (uint32 x = 0; x < _sizeX; x++) { if (spawns[x]) { for (uint32 y = 0; y < _sizeY; y++) { if (spawns[x][y]) { CellSpawns* sp = spawns[x][y]; for (CreatureSpawnList::iterator i = sp->CreatureSpawns.begin(); i != sp->CreatureSpawns.end(); ++i) delete(*i); for (GameobjectSpawnList::iterator it = sp->GameobjectSpawns.begin(); it != sp->GameobjectSpawns.end(); ++it) delete(*it); delete sp; spawns[x][y] = NULL; } } delete[] spawns[x]; } } for (CreatureSpawnList::iterator i = staticSpawns.CreatureSpawns.begin(); i != staticSpawns.CreatureSpawns.end(); ++i) delete *i; for (GameobjectSpawnList::iterator i = staticSpawns.GameobjectSpawns.begin(); i != staticSpawns.GameobjectSpawns.end(); ++i) delete *i; } std::string Map::GetMapName() { return name; } CellSpawns* Map::GetSpawnsList(uint32 cellx, uint32 celly) { ARCEMU_ASSERT(cellx < _sizeX); ARCEMU_ASSERT(celly < _sizeY); if (spawns[cellx] == NULL) return NULL; return spawns[cellx][celly]; } CellSpawns* Map::GetSpawnsListAndCreate(uint32 cellx, uint32 celly) { ARCEMU_ASSERT(cellx < _sizeX); ARCEMU_ASSERT(celly < _sizeY); if (spawns[cellx] == NULL) { spawns[cellx] = new CellSpawns*[_sizeY]; memset(spawns[cellx], 0, sizeof(CellSpawns*)*_sizeY); } if (spawns[cellx][celly] == 0) spawns[cellx][celly] = new CellSpawns; return spawns[cellx][celly]; } #define CREATURESPAWNSFIELDCOUNT 27 #define GOSPAWNSFIELDCOUNT 18 void Map::LoadSpawns(bool reload) { if (reload) //perform cleanup { for (uint32 x = 0; x < _sizeX; x++) { for (uint32 y = 0; y < _sizeY; y++) { if (spawns[x][y]) { CellSpawns* sp = spawns[x][y]; for (CreatureSpawnList::iterator i = sp->CreatureSpawns.begin(); i != sp->CreatureSpawns.end(); ++i) delete(*i); for (GameobjectSpawnList::iterator it = sp->GameobjectSpawns.begin(); it != sp->GameobjectSpawns.end(); ++it) delete(*it); delete sp; spawns[x][y] = NULL; } } } } CreatureSpawnCount = 0; for (auto cspawn : sMySQLStore._creatureSpawnsStore[this->_mapId]) { uint32 cellx = CellHandler<MapMgr>::GetPosX(cspawn->x); uint32 celly = CellHandler<MapMgr>::GetPosY(cspawn->y); if (!spawns[cellx]) { spawns[cellx] = new CellSpawns * [_sizeY]; memset(spawns[cellx], 0, sizeof(CellSpawns*) * _sizeY); } if (!spawns[cellx][celly]) spawns[cellx][celly] = new CellSpawns; spawns[cellx][celly]->CreatureSpawns.push_back(cspawn); ++CreatureSpawnCount; } GameObjectSpawnCount = 0; for (auto go_spawn : sMySQLStore._gameobjectSpawnsStore[this->_mapId]) { if (go_spawn->overrides & GAMEOBJECT_MAPWIDE) { staticSpawns.GameobjectSpawns.push_back(go_spawn); //We already have a staticSpawns in the Map class, and it does just the right thing ++GameObjectSpawnCount; } else { // Zyres: transporter stuff if (sMySQLStore.getGameObjectProperties(go_spawn->entry)->type == 11 || sMySQLStore.getGameObjectProperties(go_spawn->entry)->type == 15) { staticSpawns.GameobjectSpawns.push_back(go_spawn); } else { uint32 cellx = CellHandler<MapMgr>::GetPosX(go_spawn->position_x); uint32 celly = CellHandler<MapMgr>::GetPosY(go_spawn->position_y); if (spawns[cellx] == NULL) { spawns[cellx] = new CellSpawns * [_sizeY]; memset(spawns[cellx], 0, sizeof(CellSpawns*) * _sizeY); } if (!spawns[cellx][celly]) spawns[cellx][celly] = new CellSpawns; spawns[cellx][celly]->GameobjectSpawns.push_back(go_spawn); } ++GameObjectSpawnCount; } } LogDetail("MapMgr : %u creatures / %u gobjects on map %u cached.", CreatureSpawnCount, GameObjectSpawnCount, _mapId); } <|endoftext|>
<commit_before>/** * @file statistics.hpp * @brief An implemenation of statistics operations * @author [email protected] * @date 2013-07-01 * @version 1.0 * * @section LICENSE * * Copyright (c) 2007-2013, Seonho Oh * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <ORGANIZATION> nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <armadillo> namespace arma_ext { using namespace arma; /** * @brief 2-D correlation coefficient * @param A * @param B * @return the correlation coefficient between @c A and @c B, where @c A and @c B are matrices or vectors of the same size. * @c corr2 computes the correlation coefficient using * \f[ * r = \frac{ \sum_{m}\sum_{n}(A_{mn}-\bar{A}) (B_{mn}-\bar{B}) }{\sqrt{ \left( \sum_{m}\sum_{n}(A_{mn}-\bar{A})^2 \right) \left( \sum_{m}\sum_{n}(B_{mn}-\bar{B})^2 \right)}} * \f] * where * \f$ \bar{A}\f$=mean2(A), and \f$\bar{B}\f$=mean2(B). * @see http://www.mathworks.co.kr/kr/help/images/ref/corr2.html */ template <typename mat_type, typename prec_type> inline prec_type corr2(const mat_type& A, const mat_type& B) { typedef Mat<prec_type> tmat; tmat A1, B1; A1 = conv_to<tmat>::from(A); B1 = conv_to<tmat>::from(B); A1 -= mean2(A1); B1 -= mean2(B1); return accu(A1 % B1) / sqrt(accu(square(A1)) * accu(square(B1))); } /** * @brief Distance metric */ enum distance_type : uword { euclidean, ///< Euclidean distance. seuclidean, ///< Standarized Eucliean distance. cityblock, ///< City block metric. minkowski, ///< Minkowski distance. The default exponent is 2. chebychev, ///< Chebychev distance (maximum coordinate difference). mahalanobis, ///< Mahalanobis distance, using the sample covariance of X. cosine, ///< One minus the cosine of the included angle between points(treated as vectors). correlation, ///< One minus the sample correlation between points (treatedas sequences of values). spearman, ///< One minus the sample Spearman's rank correlation betweenobservations (treated as sequences of values). hamming, ///< Hamming distance, which is the percentage of coordinatesthat differ. jaccard, ///< One minus the Jaccard coefficient, which is the percentageof nonzero coordinates that differ. custom }; typedef double (*pdist_func)(const arma::subview_row<double>&, const arma::subview_row<double>&); /// Euclidean distance for pdist double pdist_euclidean(const arma::subview_row<double>& a, const arma::subview_row<double>& b) { return sqrt(sum(square(b - a))); } /** * @brief Pairwise distance between pairs of objects.<br> * Computes the distance between pairs of objects in \f$m\f$-by-\f$n\f$ data matrix \f$X\f$. * Rows of \f$X\f$ correspond to observations, and columns correspond to variables. * Output is the row vector of length \f$frac{m(m - 1)}{2}\f$, corresponding to pairs of observations in \f$X\f$. * The distances are arranged in the order \f$(2, 1), (3, 1), \cdots, (m, 1), (3, 2), \cdots, (m, 2), \cdots, (m, m - 1)\f$. * Output is commonly used as a dissimilarity matrix in clustering or multidimensional scailing. * @return Pairwise distance. */ vec pdist(const mat& X, distance_type type = euclidean, pdist_func func_ptr = nullptr) { const uword m = X.n_rows; vec Y(m * (m - 1) / 2); double* ptr = Y.memptr(); switch (type) { case euclidean: func_ptr = pdist_euclidean; break; case custom: // stub break; default: func_ptr = &pdist_euclidean; } uword k = 0; for (uword i = 0 ; i < m ; i++) for (uword j = i + 1 ; j < m ; j++) ptr[k++] = func_ptr(X.row(i), X.row(j)); //sqrt(sum(square(X.row(j) - X.row(i)))); return Y; } }<commit_msg>Update documentation<commit_after>/** * @file statistics.hpp * @brief An implemenation of statistics operations * @author [email protected] * @date 2013-07-01 * @version 1.0 * * @section LICENSE * * Copyright (c) 2007-2013, Seonho Oh * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <ORGANIZATION> nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <armadillo> namespace arma_ext { using namespace arma; /** * @brief 2-D correlation coefficient * @param A * @param B * @return the correlation coefficient between @c A and @c B, where @c A and @c B are matrices or vectors of the same size. * @c corr2 computes the correlation coefficient using * \f[ * r = \frac{ \sum_{m}\sum_{n}(A_{mn}-\bar{A}) (B_{mn}-\bar{B}) }{\sqrt{ \left( \sum_{m}\sum_{n}(A_{mn}-\bar{A})^2 \right) \left( \sum_{m}\sum_{n}(B_{mn}-\bar{B})^2 \right)}} * \f] * where * \f$ \bar{A}\f$=mean2(A), and \f$\bar{B}\f$=mean2(B). * @see http://www.mathworks.co.kr/kr/help/images/ref/corr2.html */ template <typename mat_type, typename prec_type> inline prec_type corr2(const mat_type& A, const mat_type& B) { typedef Mat<prec_type> tmat; tmat A1, B1; A1 = conv_to<tmat>::from(A); B1 = conv_to<tmat>::from(B); A1 -= mean2(A1); B1 -= mean2(B1); return accu(A1 % B1) / sqrt(accu(square(A1)) * accu(square(B1))); } /** * @brief Distance metric */ enum distance_type : uword { euclidean, ///< Euclidean distance. seuclidean, ///< Standarized Eucliean distance. cityblock, ///< City block metric. minkowski, ///< Minkowski distance. The default exponent is 2. chebychev, ///< Chebychev distance (maximum coordinate difference). mahalanobis, ///< Mahalanobis distance, using the sample covariance of X. cosine, ///< One minus the cosine of the included angle between points(treated as vectors). correlation, ///< One minus the sample correlation between points (treatedas sequences of values). spearman, ///< One minus the sample Spearman's rank correlation betweenobservations (treated as sequences of values). hamming, ///< Hamming distance, which is the percentage of coordinatesthat differ. jaccard, ///< One minus the Jaccard coefficient, which is the percentageof nonzero coordinates that differ. custom }; typedef double (*pdist_func)(const arma::subview_row<double>&, const arma::subview_row<double>&); /// Euclidean distance for pdist double pdist_euclidean(const arma::subview_row<double>& a, const arma::subview_row<double>& b) { return sqrt(sum(square(b - a))); } /** * @brief Pairwise distance between pairs of objects.<br> * Computes the distance between pairs of objects in \f$m\f$-by-\f$n\f$ data matrix \f$X\f$. * Rows of \f$X\f$ correspond to observations, and columns correspond to variables. * Output is the row vector of length \f$ \frac{m(m - 1)}{2} \f$, corresponding to pairs of observations in \f$X\f$. * The distances are arranged in the order \f$(2, 1), (3, 1), \cdots, (m, 1), (3, 2), \cdots, (m, 2), \cdots, (m, m - 1)\f$. * Output is commonly used as a dissimilarity matrix in clustering or multidimensional scailing. * @return Pairwise distance. */ vec pdist(const mat& X, distance_type type = euclidean, pdist_func func_ptr = nullptr) { const uword m = X.n_rows; vec Y(m * (m - 1) / 2); double* ptr = Y.memptr(); switch (type) { case euclidean: func_ptr = pdist_euclidean; break; case custom: // stub break; default: func_ptr = &pdist_euclidean; } uword k = 0; for (uword i = 0 ; i < m ; i++) for (uword j = i + 1 ; j < m ; j++) ptr[k++] = func_ptr(X.row(i), X.row(j)); //sqrt(sum(square(X.row(j) - X.row(i)))); return Y; } }<|endoftext|>
<commit_before>#include "openmc/tallies/tally_filter.h" #include <string> #include "openmc/constants.h" // for MAX_LINE_LEN; #include "openmc/tallies/tally_filter_azimuthal.h" #include "openmc/tallies/tally_filter_cell.h" #include "openmc/tallies/tally_filter_cellborn.h" #include "openmc/tallies/tally_filter_cellfrom.h" #include "openmc/tallies/tally_filter_distribcell.h" #include "openmc/tallies/tally_filter_legendre.h" #include "openmc/tallies/tally_filter_material.h" #include "openmc/tallies/tally_filter_mesh.h" #include "openmc/tallies/tally_filter_meshsurface.h" #include "openmc/tallies/tally_filter_mu.h" #include "openmc/tallies/tally_filter_polar.h" #include "openmc/tallies/tally_filter_sph_harm.h" #include "openmc/tallies/tally_filter_surface.h" #include "openmc/tallies/tally_filter_universe.h" namespace openmc { //============================================================================== // Global variables //============================================================================== std::vector<TallyFilterMatch> filter_matches; std::vector<TallyFilter*> tally_filters; //============================================================================== // Non-member functions //============================================================================== void free_memory_tally_c() { #pragma omp parallel { filter_matches.clear(); } for (TallyFilter* filt : tally_filters) {delete filt;} tally_filters.clear(); } //============================================================================== // Fortran compatibility functions //============================================================================== extern "C" { TallyFilterMatch* filter_match_pointer(int indx) {return &filter_matches[indx];} void filter_match_bins_push_back(TallyFilterMatch* match, int val) {match->bins.push_back(val);} void filter_match_weights_push_back(TallyFilterMatch* match, double val) {match->weights.push_back(val);} void filter_match_bins_clear(TallyFilterMatch* match) {match->bins.clear();} void filter_match_weights_clear(TallyFilterMatch* match) {match->weights.clear();} int filter_match_bins_size(TallyFilterMatch* match) {return match->bins.size();} int filter_match_bins_data(TallyFilterMatch* match, int indx) {return match->bins.at(indx-1);} double filter_match_weights_data(TallyFilterMatch* match, int indx) {return match->weights.at(indx-1);} void filter_match_bins_set_data(TallyFilterMatch* match, int indx, int val) {match->bins.at(indx-1) = val;} TallyFilter* allocate_filter(const char* type) { std::string type_ {type}; if (type_ == "azimuthal") { tally_filters.push_back(new AzimuthalFilter()); } else if (type_ == "cell") { tally_filters.push_back(new CellFilter()); } else if (type_ == "cellborn") { tally_filters.push_back(new CellbornFilter()); } else if (type_ == "cellfrom") { tally_filters.push_back(new CellFromFilter()); } else if (type_ == "distribcell") { tally_filters.push_back(new DistribcellFilter()); } else if (type_ == "legendre") { tally_filters.push_back(new LegendreFilter()); } else if (type_ == "material") { tally_filters.push_back(new MaterialFilter()); } else if (type_ == "mesh") { tally_filters.push_back(new MeshFilter()); } else if (type_ == "meshsurface") { tally_filters.push_back(new MeshSurfaceFilter()); } else if (type_ == "mu") { tally_filters.push_back(new MuFilter()); } else if (type_ == "polar") { tally_filters.push_back(new PolarFilter()); } else if (type_ == "surface") { tally_filters.push_back(new SurfaceFilter()); } else if (type_ == "sphericalharmonics") { tally_filters.push_back(new SphericalHarmonicsFilter()); } else if (type_ == "universe") { tally_filters.push_back(new UniverseFilter()); } else { return nullptr; } return tally_filters.back(); } void filter_from_xml(TallyFilter* filt, pugi::xml_node* node) {filt->from_xml(*node);} void filter_get_all_bins(TallyFilter* filt, Particle* p, int estimator, TallyFilterMatch* match) { filt->get_all_bins(p, estimator, *match); } void filter_to_statepoint(TallyFilter* filt, hid_t group) {filt->to_statepoint(group);} void filter_text_label(TallyFilter* filt, int bin, char* label) { std::string label_str = filt->text_label(bin); int i = 0; for (; i < label_str.size() && i < MAX_LINE_LEN; i++) label[i] = label_str[i]; label[i] = '\0'; } void filter_initialize(TallyFilter* filt) {filt->initialize();} int filter_n_bins(TallyFilter* filt) {return filt->n_bins_;} void cell_filter_get_bins(CellFilter* filt, int32_t** cells, int32_t* n) { *cells = filt->cells_.data(); *n = filt->cells_.size(); } int legendre_filter_get_order(LegendreFilter* filt) {return filt->order_;} void legendre_filter_set_order(LegendreFilter* filt, int order) {filt->order_ = order;} void material_filter_get_bins(MaterialFilter* filt, int32_t** bins, int32_t* n) { *bins = filt->materials_.data(); *n = filt->materials_.size(); } void material_filter_set_bins(MaterialFilter* filt, int32_t n, int32_t* bins) { filt->materials_.clear(); filt->materials_.resize(n); for (int i = 0; i < n; i++) filt->materials_[i] = bins[i]; filt->n_bins_ = filt->materials_.size(); filt->map_.clear(); for (int i = 0; i < n; i++) filt->map_[filt->materials_[i]] = i; } int mesh_filter_get_mesh(MeshFilter* filt) {return filt->mesh_;} void mesh_filter_set_mesh(MeshFilter* filt, int mesh) { filt->mesh_ = mesh; filt->n_bins_ = 1; for (auto dim : meshes[mesh]->shape_) filt->n_bins_ *= dim; } int meshsurface_filter_get_mesh(MeshSurfaceFilter* filt) {return filt->mesh_;} void meshsurface_filter_set_mesh(MeshSurfaceFilter* filt, int mesh) { filt->mesh_ = mesh; filt->n_bins_ = 4 * meshes[mesh]->n_dimension_; for (auto dim : meshes[mesh]->shape_) filt->n_bins_ *= dim; } int sphharm_filter_get_order(SphericalHarmonicsFilter* filt) {return filt->order_;} int sphharm_filter_get_cosine(SphericalHarmonicsFilter* filt) {return static_cast<int>(filt->cosine_);} void sphharm_filter_set_order(SphericalHarmonicsFilter* filt, int order) { filt->order_ = order; filt->n_bins_ = (order + 1) * (order + 1); } void sphharm_filter_set_cosine(SphericalHarmonicsFilter* filt, int cosine) {filt->cosine_ = static_cast<SphericalHarmonicsCosine>(cosine);} } } // namespace openmc <commit_msg>Fix legendre_filter_set_order<commit_after>#include "openmc/tallies/tally_filter.h" #include <string> #include "openmc/constants.h" // for MAX_LINE_LEN; #include "openmc/tallies/tally_filter_azimuthal.h" #include "openmc/tallies/tally_filter_cell.h" #include "openmc/tallies/tally_filter_cellborn.h" #include "openmc/tallies/tally_filter_cellfrom.h" #include "openmc/tallies/tally_filter_distribcell.h" #include "openmc/tallies/tally_filter_legendre.h" #include "openmc/tallies/tally_filter_material.h" #include "openmc/tallies/tally_filter_mesh.h" #include "openmc/tallies/tally_filter_meshsurface.h" #include "openmc/tallies/tally_filter_mu.h" #include "openmc/tallies/tally_filter_polar.h" #include "openmc/tallies/tally_filter_sph_harm.h" #include "openmc/tallies/tally_filter_surface.h" #include "openmc/tallies/tally_filter_universe.h" namespace openmc { //============================================================================== // Global variables //============================================================================== std::vector<TallyFilterMatch> filter_matches; std::vector<TallyFilter*> tally_filters; //============================================================================== // Non-member functions //============================================================================== void free_memory_tally_c() { #pragma omp parallel { filter_matches.clear(); } for (TallyFilter* filt : tally_filters) {delete filt;} tally_filters.clear(); } //============================================================================== // Fortran compatibility functions //============================================================================== extern "C" { TallyFilterMatch* filter_match_pointer(int indx) {return &filter_matches[indx];} void filter_match_bins_push_back(TallyFilterMatch* match, int val) {match->bins.push_back(val);} void filter_match_weights_push_back(TallyFilterMatch* match, double val) {match->weights.push_back(val);} void filter_match_bins_clear(TallyFilterMatch* match) {match->bins.clear();} void filter_match_weights_clear(TallyFilterMatch* match) {match->weights.clear();} int filter_match_bins_size(TallyFilterMatch* match) {return match->bins.size();} int filter_match_bins_data(TallyFilterMatch* match, int indx) {return match->bins.at(indx-1);} double filter_match_weights_data(TallyFilterMatch* match, int indx) {return match->weights.at(indx-1);} void filter_match_bins_set_data(TallyFilterMatch* match, int indx, int val) {match->bins.at(indx-1) = val;} TallyFilter* allocate_filter(const char* type) { std::string type_ {type}; if (type_ == "azimuthal") { tally_filters.push_back(new AzimuthalFilter()); } else if (type_ == "cell") { tally_filters.push_back(new CellFilter()); } else if (type_ == "cellborn") { tally_filters.push_back(new CellbornFilter()); } else if (type_ == "cellfrom") { tally_filters.push_back(new CellFromFilter()); } else if (type_ == "distribcell") { tally_filters.push_back(new DistribcellFilter()); } else if (type_ == "legendre") { tally_filters.push_back(new LegendreFilter()); } else if (type_ == "material") { tally_filters.push_back(new MaterialFilter()); } else if (type_ == "mesh") { tally_filters.push_back(new MeshFilter()); } else if (type_ == "meshsurface") { tally_filters.push_back(new MeshSurfaceFilter()); } else if (type_ == "mu") { tally_filters.push_back(new MuFilter()); } else if (type_ == "polar") { tally_filters.push_back(new PolarFilter()); } else if (type_ == "surface") { tally_filters.push_back(new SurfaceFilter()); } else if (type_ == "sphericalharmonics") { tally_filters.push_back(new SphericalHarmonicsFilter()); } else if (type_ == "universe") { tally_filters.push_back(new UniverseFilter()); } else { return nullptr; } return tally_filters.back(); } void filter_from_xml(TallyFilter* filt, pugi::xml_node* node) {filt->from_xml(*node);} void filter_get_all_bins(TallyFilter* filt, Particle* p, int estimator, TallyFilterMatch* match) { filt->get_all_bins(p, estimator, *match); } void filter_to_statepoint(TallyFilter* filt, hid_t group) {filt->to_statepoint(group);} void filter_text_label(TallyFilter* filt, int bin, char* label) { std::string label_str = filt->text_label(bin); int i = 0; for (; i < label_str.size() && i < MAX_LINE_LEN; i++) label[i] = label_str[i]; label[i] = '\0'; } void filter_initialize(TallyFilter* filt) {filt->initialize();} int filter_n_bins(TallyFilter* filt) {return filt->n_bins_;} void cell_filter_get_bins(CellFilter* filt, int32_t** cells, int32_t* n) { *cells = filt->cells_.data(); *n = filt->cells_.size(); } int legendre_filter_get_order(LegendreFilter* filt) {return filt->order_;} void legendre_filter_set_order(LegendreFilter* filt, int order) { filt->order_ = order; filt->n_bins_ = order + 1; } void material_filter_get_bins(MaterialFilter* filt, int32_t** bins, int32_t* n) { *bins = filt->materials_.data(); *n = filt->materials_.size(); } void material_filter_set_bins(MaterialFilter* filt, int32_t n, int32_t* bins) { filt->materials_.clear(); filt->materials_.resize(n); for (int i = 0; i < n; i++) filt->materials_[i] = bins[i]; filt->n_bins_ = filt->materials_.size(); filt->map_.clear(); for (int i = 0; i < n; i++) filt->map_[filt->materials_[i]] = i; } int mesh_filter_get_mesh(MeshFilter* filt) {return filt->mesh_;} void mesh_filter_set_mesh(MeshFilter* filt, int mesh) { filt->mesh_ = mesh; filt->n_bins_ = 1; for (auto dim : meshes[mesh]->shape_) filt->n_bins_ *= dim; } int meshsurface_filter_get_mesh(MeshSurfaceFilter* filt) {return filt->mesh_;} void meshsurface_filter_set_mesh(MeshSurfaceFilter* filt, int mesh) { filt->mesh_ = mesh; filt->n_bins_ = 4 * meshes[mesh]->n_dimension_; for (auto dim : meshes[mesh]->shape_) filt->n_bins_ *= dim; } int sphharm_filter_get_order(SphericalHarmonicsFilter* filt) {return filt->order_;} int sphharm_filter_get_cosine(SphericalHarmonicsFilter* filt) {return static_cast<int>(filt->cosine_);} void sphharm_filter_set_order(SphericalHarmonicsFilter* filt, int order) { filt->order_ = order; filt->n_bins_ = (order + 1) * (order + 1); } void sphharm_filter_set_cosine(SphericalHarmonicsFilter* filt, int cosine) {filt->cosine_ = static_cast<SphericalHarmonicsCosine>(cosine);} } } // namespace openmc <|endoftext|>
<commit_before>#include <cassert> #include <ctime> #include <iostream> #include <cstdlib> #include <vector> #include "../slitherlink/SlitherlinkDatabase.h" #include "../slitherlink/SlitherlinkDatabaseMethod.hpp" #include "../slitherlink/SlitherlinkField.h" #include "../slitherlink/SlitherlinkProblem.h" #include "Test.h" namespace Penciloid { void PenciloidTest::SlitherlinkClueTest(int height, int width, std::vector<const char*> board, int expected_status, int test_id = -1) { SlitherlinkField field; field.Init(height, width); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { char clue = board[y * 2 + 1][x * 2 + 1]; if ('0' <= clue && clue <= '3') field.SetClue(y, x, clue - '0'); } } field.CheckAll(); bool is_status_ok = true; if (expected_status == SolverStatus::NORMAL && field.GetStatus() != expected_status) is_status_ok = false; if (expected_status == SolverStatus::SUCCESS && field.GetStatus() != expected_status) is_status_ok = false; if (expected_status == SolverStatus::INCONSISTENT && (field.GetStatus() & SolverStatus::INCONSISTENT) == 0) is_status_ok = false; if (!is_status_ok) { std::cerr << "SlitherlinkClueTest failed in test #" << test_id << std::endl; std::cerr << "expected: " << expected_status << ", actual: " << field.GetStatus() << " (field status)" << std::endl; } if (expected_status == SolverStatus::INCONSISTENT) return; for (int y = 0; y <= height * 2; ++y) { for (int x = 0; x <= width * 2; ++x) { if (y % 2 == x % 2) continue; // this is not a segment int expected = board[y][x] == ' ' ? SlitherlinkField::LOOP_UNDECIDED : board[y][x] == 'x' ? SlitherlinkField::LOOP_BLANK : SlitherlinkField::LOOP_LINE; if (field.GetSegmentStyle(y, x) != expected) { std::cerr << "SlitherlinkClueTest failed in test #" << test_id << std::endl; std::cerr << "expected: " << expected << ", actual: " << field.GetSegmentStyle(y, x) << " at (" << y << "," << x << ")" << std::endl; exit(1); } } } } bool PenciloidTest::SlitherlinkCheckGrid(SlitherlinkField &field, const int *expected) { int height = field.GetHeight() * 2 + 1, width = field.GetWidth() * 2 + 1; for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { if (i % 2 != j % 2) { int expected_style = (expected[i * width + j] == 1) ? SlitherlinkField::LOOP_LINE : SlitherlinkField::LOOP_BLANK; if (field.GetSegmentStyle(i, j) != expected_style) return false; } } } return true; } void PenciloidTest::SlitherlinkFieldTestByProblems() { for (int t = 0; t < 2; ++t) { // t: enable database or not // t is specified in test_id by adding t * 1000 if (t == 0) { if (SlitherlinkDatabase::IsCreated()) SlitherlinkDatabase::ReleaseDatabase(); } else if (t == 1) { if (!SlitherlinkDatabase::IsCreated()) SlitherlinkDatabase::CreateDatabase(); } SlitherlinkClueTest(3, 3, { "+x+x+-+", "x0x2| |", "+x+-+x+", "x | x |", "+-+x+x+", "|3x1x |", "+-+-+-+", }, SolverStatus::SUCCESS, t * 1000 + 0); SlitherlinkClueTest(3, 3, { "+-+-+-+", "| x x |", "+x+-+x+", "|3|3| |", "+-+x+x+", "x x |3|", "+x+x+-+", }, SolverStatus::SUCCESS, t * 1000 + 1); // 2: closed loop test SlitherlinkClueTest(5, 3, { "+-+x+-+", "|3|3|3|", "+x+-+x+", "|2x2x2|", "+-+-+-+", "x x1x x", "+x+x+x+", "x x x x", "+x+x+x+", "x x x x", "+x+x+x+", }, SolverStatus::SUCCESS, t * 1000 + 2); // 3: closed loop (inconsistent) test SlitherlinkClueTest(5, 3, { "+ + + +", " 3 3 3 ", "+ + + +", " 2 2 2 ", "+ + + +", " ", "+ + + +", " 2 ", "+ + + +", " ", "+ + + +", }, SolverStatus::INCONSISTENT, t * 1000 + 3); // 1xx: diagonal chain test SlitherlinkClueTest(4, 4, { "+x+x+ + +", "x0x ", "+x+ + + +", "x 2 ", "+ + +x+ +", " x1 ", "+ + + + +", " ", "+ + + + +", }, SolverStatus::NORMAL, t * 1000 + 100); SlitherlinkClueTest(4, 4, { "+x+x+ + +", "x0x ", "+x+-+ + +", "x |2x ", "+ +x+-+ +", " |3 ", "+ + + + +", " ", "+ + + + +", }, SolverStatus::NORMAL, t * 1000 + 101); if (t == 1) SlitherlinkDatabase::ReleaseDatabase(); } } void PenciloidTest::SlitherlinkReducedDatabaseTest() { if (SlitherlinkDatabase::IsCreated()) SlitherlinkDatabase::ReleaseDatabase(); SlitherlinkDatabase::CreateReducedDatabase(SlitherlinkDatabaseMethod()); SlitherlinkClueTest(4, 4, { "+x+ + + +", "x1 ", "+ + + + +", " ", "+ + + + +", " ", "+ + + + +", " ", "+ + + + +", }, SolverStatus::NORMAL, 2000); SlitherlinkClueTest(4, 4, { "+ +-+ + +", " 2 ", "+ + + + +", "| ", "+ + + + +", " ", "+ + + + +", " ", "+ + + + +", }, SolverStatus::NORMAL, 2001); SlitherlinkClueTest(4, 4, { "+-+ + + +", "|3 ", "+ + + + +", " ", "+ + + + +", " ", "+ + + + +", " ", "+ + + + +", }, SolverStatus::NORMAL, 2002); SlitherlinkDatabase::ReleaseDatabase(); } }<commit_msg>Add a test for line to 3<commit_after>#include <cassert> #include <ctime> #include <iostream> #include <cstdlib> #include <vector> #include "../slitherlink/SlitherlinkDatabase.h" #include "../slitherlink/SlitherlinkDatabaseMethod.hpp" #include "../slitherlink/SlitherlinkField.h" #include "../slitherlink/SlitherlinkProblem.h" #include "Test.h" namespace Penciloid { void PenciloidTest::SlitherlinkClueTest(int height, int width, std::vector<const char*> board, int expected_status, int test_id = -1) { SlitherlinkField field; field.Init(height, width); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { char clue = board[y * 2 + 1][x * 2 + 1]; if ('0' <= clue && clue <= '3') field.SetClue(y, x, clue - '0'); } } field.CheckAll(); bool is_status_ok = true; if (expected_status == SolverStatus::NORMAL && field.GetStatus() != expected_status) is_status_ok = false; if (expected_status == SolverStatus::SUCCESS && field.GetStatus() != expected_status) is_status_ok = false; if (expected_status == SolverStatus::INCONSISTENT && (field.GetStatus() & SolverStatus::INCONSISTENT) == 0) is_status_ok = false; if (!is_status_ok) { std::cerr << "SlitherlinkClueTest failed in test #" << test_id << std::endl; std::cerr << "expected: " << expected_status << ", actual: " << field.GetStatus() << " (field status)" << std::endl; } if (expected_status == SolverStatus::INCONSISTENT) return; for (int y = 0; y <= height * 2; ++y) { for (int x = 0; x <= width * 2; ++x) { if (y % 2 == x % 2) continue; // this is not a segment int expected = board[y][x] == ' ' ? SlitherlinkField::LOOP_UNDECIDED : board[y][x] == 'x' ? SlitherlinkField::LOOP_BLANK : SlitherlinkField::LOOP_LINE; if (field.GetSegmentStyle(y, x) != expected) { std::cerr << "SlitherlinkClueTest failed in test #" << test_id << std::endl; std::cerr << "expected: " << expected << ", actual: " << field.GetSegmentStyle(y, x) << " at (" << y << "," << x << ")" << std::endl; exit(1); } } } } bool PenciloidTest::SlitherlinkCheckGrid(SlitherlinkField &field, const int *expected) { int height = field.GetHeight() * 2 + 1, width = field.GetWidth() * 2 + 1; for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { if (i % 2 != j % 2) { int expected_style = (expected[i * width + j] == 1) ? SlitherlinkField::LOOP_LINE : SlitherlinkField::LOOP_BLANK; if (field.GetSegmentStyle(i, j) != expected_style) return false; } } } return true; } void PenciloidTest::SlitherlinkFieldTestByProblems() { for (int t = 0; t < 2; ++t) { // t: enable database or not // t is specified in test_id by adding t * 1000 if (t == 0) { if (SlitherlinkDatabase::IsCreated()) SlitherlinkDatabase::ReleaseDatabase(); } else if (t == 1) { if (!SlitherlinkDatabase::IsCreated()) SlitherlinkDatabase::CreateDatabase(); } SlitherlinkClueTest(3, 3, { "+x+x+-+", "x0x2| |", "+x+-+x+", "x | x |", "+-+x+x+", "|3x1x |", "+-+-+-+", }, SolverStatus::SUCCESS, t * 1000 + 0); SlitherlinkClueTest(3, 3, { "+-+-+-+", "| x x |", "+x+-+x+", "|3|3| |", "+-+x+x+", "x x |3|", "+x+x+-+", }, SolverStatus::SUCCESS, t * 1000 + 1); // 2: closed loop test SlitherlinkClueTest(5, 3, { "+-+x+-+", "|3|3|3|", "+x+-+x+", "|2x2x2|", "+-+-+-+", "x x1x x", "+x+x+x+", "x x x x", "+x+x+x+", "x x x x", "+x+x+x+", }, SolverStatus::SUCCESS, t * 1000 + 2); // 3: closed loop (inconsistent) test SlitherlinkClueTest(5, 3, { "+ + + +", " 3 3 3 ", "+ + + +", " 2 2 2 ", "+ + + +", " ", "+ + + +", " 2 ", "+ + + +", " ", "+ + + +", }, SolverStatus::INCONSISTENT, t * 1000 + 3); // 1xx: diagonal chain test SlitherlinkClueTest(4, 4, { "+x+x+ + +", "x0x ", "+x+ + + +", "x 2 ", "+ + +x+ +", " x1 ", "+ + + + +", " ", "+ + + + +", }, SolverStatus::NORMAL, t * 1000 + 100); SlitherlinkClueTest(4, 4, { "+x+x+ + +", "x0x ", "+x+-+ + +", "x |2x ", "+ +x+-+ +", " |3 ", "+ + + + +", " ", "+ + + + +", }, SolverStatus::NORMAL, t * 1000 + 101); if (t == 1) SlitherlinkDatabase::ReleaseDatabase(); } } void PenciloidTest::SlitherlinkReducedDatabaseTest() { if (SlitherlinkDatabase::IsCreated()) SlitherlinkDatabase::ReleaseDatabase(); SlitherlinkDatabase::CreateReducedDatabase(SlitherlinkDatabaseMethod()); SlitherlinkClueTest(4, 4, { "+x+ + + +", "x1 ", "+ + + + +", " ", "+ + + + +", " ", "+ + + + +", " ", "+ + + + +", }, SolverStatus::NORMAL, 2000); SlitherlinkClueTest(4, 4, { "+ +-+ + +", " 2 ", "+ + + + +", "| ", "+ + + + +", " ", "+ + + + +", " ", "+ + + + +", }, SolverStatus::NORMAL, 2001); SlitherlinkClueTest(4, 4, { "+-+ + + +", "|3 ", "+ + + + +", " ", "+ + + + +", " ", "+ + + + +", " ", "+ + + + +", }, SolverStatus::NORMAL, 2002); SlitherlinkClueTest(4, 4, { "+x+x+-+ +", "x0x2| ", "+x+-+x+ +", "x | x ", "+x+ + + +", "x 3| ", "+ +-+x+ +", " x ", "+ + + + +", }, SolverStatus::NORMAL, 2002); SlitherlinkDatabase::ReleaseDatabase(); } }<|endoftext|>
<commit_before>#if !FEATURE_IPV4 #error [NOT_SUPPORTED] IPV4 not supported for this target #endif #include <algorithm> #include "mbed.h" #include "EthernetInterface.h" #include "TCPSocket.h" #include "greentea-client/test_env.h" #include "unity/unity.h" namespace { // Test connection information const char *HTTP_SERVER_NAME = "developer.mbed.org"; const char *HTTP_SERVER_FILE_PATH = "/media/uploads/mbed_official/hello.txt"; const int HTTP_SERVER_PORT = 80; #if defined(TARGET_VK_RZ_A1H) const int RECV_BUFFER_SIZE = 300; #else const int RECV_BUFFER_SIZE = 512; #endif // Test related data const char *HTTP_OK_STR = "200 OK"; const char *HTTP_HELLO_STR = "Hello world!"; // Test buffers char buffer[RECV_BUFFER_SIZE] = {0}; } bool find_substring(const char *first, const char *last, const char *s_first, const char *s_last) { const char *f = std::search(first, last, s_first, s_last); return (f != last); } int main() { GREENTEA_SETUP(20, "default_auto"); bool result = false; EthernetInterface eth; //eth.init(); //Use DHCP eth.connect(); printf("TCP client IP Address is %s\r\n", eth.get_ip_address()); TCPSocket sock(&eth); printf("HTTP: Connection to %s:%d\r\n", HTTP_SERVER_NAME, HTTP_SERVER_PORT); if (sock.connect(HTTP_SERVER_NAME, HTTP_SERVER_PORT) == 0) { printf("HTTP: OK\r\n"); // We are constructing GET command like this: // GET http://developer.mbed.org/media/uploads/mbed_official/hello.txt HTTP/1.0\n\n strcpy(buffer, "GET http://"); strcat(buffer, HTTP_SERVER_NAME); strcat(buffer, HTTP_SERVER_FILE_PATH); strcat(buffer, " HTTP/1.0\n\n"); // Send GET command sock.send(buffer, strlen(buffer)); // Server will respond with HTTP GET's success code const int ret = sock.recv(buffer, sizeof(buffer) - 1); buffer[ret] = '\0'; // Find 200 OK HTTP status in reply bool found_200_ok = find_substring(buffer, buffer + ret, HTTP_OK_STR, HTTP_OK_STR + strlen(HTTP_OK_STR)); // Find "Hello World!" string in reply bool found_hello = find_substring(buffer, buffer + ret, HTTP_HELLO_STR, HTTP_HELLO_STR + strlen(HTTP_HELLO_STR)); TEST_ASSERT_TRUE(found_200_ok); TEST_ASSERT_TRUE(found_hello); result = true; if (!found_200_ok) result = false; if (!found_hello) result = false; printf("HTTP: Received %d chars from server\r\n", ret); printf("HTTP: Received 200 OK status ... %s\r\n", found_200_ok ? "[OK]" : "[FAIL]"); printf("HTTP: Received '%s' status ... %s\r\n", HTTP_HELLO_STR, found_hello ? "[OK]" : "[FAIL]"); printf("HTTP: Received message:\r\n"); printf("%s", buffer); sock.close(); } else { printf("HTTP: ERROR\r\n"); } eth.disconnect(); GREENTEA_TESTSUITE_RESULT(result); } <commit_msg>tcp_client_hello_worldminor update<commit_after>#if !FEATURE_IPV4 #error [NOT_SUPPORTED] IPV4 not supported for this target #endif #include <algorithm> #include "mbed.h" #include "EthernetInterface.h" #include "TCPSocket.h" #include "greentea-client/test_env.h" #include "unity/unity.h" namespace { // Test connection information const char *HTTP_SERVER_NAME = "developer.mbed.org"; const char *HTTP_SERVER_FILE_PATH = "/media/uploads/mbed_official/hello.txt"; const int HTTP_SERVER_PORT = 80; #if defined(TARGET_VK_RZ_A1H) const int RECV_BUFFER_SIZE = 300; #else const int RECV_BUFFER_SIZE = 512; #endif // Test related data const char *HTTP_OK_STR = "200 OK"; const char *HTTP_HELLO_STR = "Hello world!"; // Test buffers char buffer[RECV_BUFFER_SIZE] = {0}; } bool find_substring(const char *first, const char *last, const char *s_first, const char *s_last) { const char *f = std::search(first, last, s_first, s_last); return (f != last); } int main() { GREENTEA_SETUP(20, "default_auto"); bool result = false; EthernetInterface eth; //eth.init(); //Use DHCP eth.connect(); printf("TCP client IP Address is %s\r\n", eth.get_ip_address()); TCPSocket sock(&eth); printf("HTTP: Connection to %s:%d\r\n", HTTP_SERVER_NAME, HTTP_SERVER_PORT); if (sock.connect(HTTP_SERVER_NAME, HTTP_SERVER_PORT) == 0) { printf("HTTP: OK\r\n"); // We are constructing GET command like this: // GET http://developer.mbed.org/media/uploads/mbed_official/hello.txt HTTP/1.0\n\n strcpy(buffer, "GET http://"); strcat(buffer, HTTP_SERVER_NAME); strcat(buffer, HTTP_SERVER_FILE_PATH); strcat(buffer, " HTTP/1.0\n\n"); // Send GET command sock.send(buffer, strlen(buffer)); // Server will respond with HTTP GET's success code const int ret = sock.recv(buffer, sizeof(buffer) - 1); buffer[ret] = '\0'; // Find 200 OK HTTP status in reply bool found_200_ok = find_substring(buffer, buffer + ret, HTTP_OK_STR, HTTP_OK_STR + strlen(HTTP_OK_STR)); // Find "Hello World!" string in reply bool found_hello = find_substring(buffer, buffer + ret, HTTP_HELLO_STR, HTTP_HELLO_STR + strlen(HTTP_HELLO_STR)); TEST_ASSERT_TRUE(found_200_ok); TEST_ASSERT_TRUE(found_hello); if (found_200_ok && found_hello) result = true; printf("HTTP: Received %d chars from server\r\n", ret); printf("HTTP: Received 200 OK status ... %s\r\n", found_200_ok ? "[OK]" : "[FAIL]"); printf("HTTP: Received '%s' status ... %s\r\n", HTTP_HELLO_STR, found_hello ? "[OK]" : "[FAIL]"); printf("HTTP: Received message:\r\n"); printf("%s", buffer); sock.close(); } else { printf("HTTP: ERROR\r\n"); } eth.disconnect(); GREENTEA_TESTSUITE_RESULT(result); } <|endoftext|>
<commit_before>/* *The MIT License (MIT) * * Copyright (c) <2016> <Stephan Gatzka> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE websocket_tests #include <boost/test/unit_test.hpp> #include <errno.h> #include "jet_string.h" #include "socket.h" #include "websocket.h" #define CRLF "\r\n" #ifndef ARRAY_SIZE #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #endif static const int FD_CORRECT_UPGRADE = 1; static bool ws_error = false; static const char *readbuffer; static const char *readbuffer_ptr; static http_parser response_parser; static http_parser_settings response_parser_settings; static bool got_complete_response_header = false; static bool response_parse_error = false; extern "C" { ssize_t socket_writev(socket_type sock, struct buffered_socket_io_vector *io_vec, unsigned int count) { switch (sock) { case FD_CORRECT_UPGRADE: { size_t complete_length = 0; for (unsigned int i = 0; i < count; i++) { if (!got_complete_response_header) { size_t nparsed = http_parser_execute(&response_parser, &response_parser_settings, (const char *)io_vec[i].iov_base, io_vec[i].iov_len); if (nparsed != io_vec[i].iov_len) { response_parse_error = true; errno = EFAULT; return -1; } } else { } complete_length += io_vec[i].iov_len; } return complete_length; } default: errno = EWOULDBLOCK; return -1; } } ssize_t socket_send(socket_type sock, const void *buf, size_t len) { (void)buf; (void)len; switch (sock) { default: errno = EWOULDBLOCK; return -1; } } ssize_t socket_read(socket_type sock, void *buf, size_t count) { (void)buf; (void)count; switch (sock) { default: errno = EWOULDBLOCK; return -1; } } int socket_close(socket_type sock) { (void)sock; return 0; } } static enum callback_return eventloop_fake_add(const void *this_ptr, const struct io_event *ev) { (void)this_ptr; (void)ev; return CONTINUE_LOOP; } static void eventloop_fake_remove(const void *this_ptr, const struct io_event *ev) { (void)this_ptr; (void)ev; } static void ws_on_error(struct websocket *ws) { (void)ws; ws_error = true; } static int on_headers_complete(http_parser *parser) { (void)parser; got_complete_response_header = true; return 0; } struct F { enum response_on_header_field { HEADER_UNKNOWN, HEADER_UPGRADE, HEADER_CONNECTION, HEADER_ACCEPT, }; F() { loop.init = NULL; loop.destroy = NULL; loop.run = NULL; loop.add = eventloop_fake_add; loop.remove = eventloop_fake_remove; readbuffer_ptr = readbuffer; got_complete_response_header = false; response_parse_error = false; http_parser_settings_init(&parser_settings); http_parser_init(&parser, HTTP_REQUEST); http_parser_settings_init(&response_parser_settings); http_parser_init(&response_parser, HTTP_RESPONSE); response_parser.data = this; response_parser_settings.on_header_field = response_on_header_field; response_parser_settings.on_header_value = response_on_header_value; response_parser_settings.on_headers_complete = on_headers_complete; handler[0].request_target = "/"; handler[0].create = NULL; handler[0].on_header_field = websocket_upgrade_on_header_field, handler[0].on_header_value = websocket_upgrade_on_header_value, handler[0].on_headers_complete = websocket_upgrade_on_headers_complete, handler[0].on_body = NULL; handler[0].on_message_complete = NULL; http_server.handler = handler; http_server.num_handlers = ARRAY_SIZE(handler); ::memset(websocket_accept_key, 0, sizeof(websocket_accept_key)); ws_error = false; got_upgrade_response = false; got_connection_upgrade = false; current_header_field = HEADER_UNKNOWN; } ~F() { } static int response_on_header_field(http_parser *p, const char *at, size_t length) { struct F *f = (struct F *)p->data; static const char upgrade_key[] = "Upgrade"; if ((sizeof(upgrade_key) - 1 == length) && (jet_strncasecmp(at, upgrade_key, length) == 0)) { f->current_header_field = HEADER_UPGRADE; return 0; } static const char connection_key[] = "Connection"; if ((sizeof(connection_key) - 1 == length) && (jet_strncasecmp(at, connection_key, length) == 0)) { f->current_header_field = HEADER_CONNECTION; return 0; } static const char accept_key[] = "Sec-WebSocket-Accept"; if ((sizeof(accept_key) - 1 == length) && (jet_strncasecmp(at, accept_key, length) == 0)) { f->current_header_field = HEADER_ACCEPT; return 0; } return 0; } static int response_on_header_value(http_parser *p, const char *at, size_t length) { int ret = 0; struct F *f = (struct F *)p->data; switch(f->current_header_field) { case HEADER_UPGRADE: f->got_upgrade_response = true; break; case HEADER_CONNECTION: if (jet_strncasecmp(at, "Upgrade", length) == 0) { f->got_connection_upgrade = true; } break; case HEADER_ACCEPT: { size_t len = std::min(length, sizeof(websocket_accept_key)); memcpy(f->websocket_accept_key, at, len); break; } case HEADER_UNKNOWN: default: break; } f->current_header_field = HEADER_UNKNOWN; return ret; } struct eventloop loop; http_parser parser; http_parser_settings parser_settings; struct url_handler handler[1]; struct http_server http_server; bool got_upgrade_response; bool got_connection_upgrade; enum response_on_header_field current_header_field; uint8_t websocket_accept_key[28]; }; BOOST_AUTO_TEST_CASE(test_websocket_init) { struct websocket ws; websocket_init(&ws, NULL, true, NULL); websocket_free(&ws); } BOOST_FIXTURE_TEST_CASE(test_http_upgrade, F) { char request[] = "GET / HTTP/1.1" CRLF "Connection: Upgrade" CRLF \ "Upgrade: websocket" CRLF \ "Sec-WebSocket-Version: 13" CRLF\ "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" CRLF CRLF; struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_CORRECT_UPGRADE); BOOST_REQUIRE_MESSAGE(connection != NULL, "Failed to allocate http connection"); struct websocket ws; websocket_init(&ws, connection, true, ws_on_error); connection->parser.data = &ws; bs_read_callback_return ret = websocket_read_header_line(&ws, request, ::strlen(request)); BOOST_CHECK_MESSAGE(ret == BS_OK, "websocket_read_header_line did not return BS_OK"); BOOST_CHECK_MESSAGE(ws_error == false, "Error while parsing the http upgrade request"); websocket_free(&ws); BOOST_CHECK_MESSAGE(response_parser.status_code == 101, "Expected 101 status code"); BOOST_CHECK_MESSAGE(response_parser.http_major == 1, "Expected http major 1"); BOOST_CHECK_MESSAGE(response_parser.http_minor == 1, "Expected http minor 1"); BOOST_CHECK_MESSAGE(response_parse_error == false, "Invalid upgrade response!"); BOOST_CHECK_MESSAGE(got_upgrade_response == true, "Upgrade header field missing!"); BOOST_CHECK_MESSAGE(got_connection_upgrade == true, "Connection header field missing!"); BOOST_CHECK_MESSAGE(::memcmp(websocket_accept_key, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", sizeof(websocket_accept_key)) == 0, "Got illegal websocket accept key!"); // TODO: Check that close frame was sent } <commit_msg>Check that a close frame was sent when calling websocket_free().<commit_after>/* *The MIT License (MIT) * * Copyright (c) <2016> <Stephan Gatzka> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE websocket_tests #include <boost/test/unit_test.hpp> #include <errno.h> #include "jet_endian.h" #include "jet_string.h" #include "socket.h" #include "websocket.h" #define CRLF "\r\n" #ifndef ARRAY_SIZE #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #endif static const int FD_CORRECT_UPGRADE = 1; static bool ws_error = false; static const char *readbuffer; static const char *readbuffer_ptr; static char write_buffer[5000]; static char *write_buffer_ptr; static http_parser response_parser; static http_parser_settings response_parser_settings; static bool got_complete_response_header = false; static bool response_parse_error = false; extern "C" { ssize_t socket_writev(socket_type sock, struct buffered_socket_io_vector *io_vec, unsigned int count) { switch (sock) { case FD_CORRECT_UPGRADE: { size_t complete_length = 0; for (unsigned int i = 0; i < count; i++) { if (!got_complete_response_header) { size_t nparsed = http_parser_execute(&response_parser, &response_parser_settings, (const char *)io_vec[i].iov_base, io_vec[i].iov_len); if (nparsed != io_vec[i].iov_len) { response_parse_error = true; errno = EFAULT; return -1; } } else { memcpy(write_buffer_ptr, io_vec[i].iov_base, io_vec[i].iov_len); write_buffer_ptr += io_vec[i].iov_len; } complete_length += io_vec[i].iov_len; } return complete_length; } default: errno = EWOULDBLOCK; return -1; } } ssize_t socket_send(socket_type sock, const void *buf, size_t len) { (void)buf; (void)len; switch (sock) { default: errno = EWOULDBLOCK; return -1; } } ssize_t socket_read(socket_type sock, void *buf, size_t count) { (void)buf; (void)count; switch (sock) { default: errno = EWOULDBLOCK; return -1; } } int socket_close(socket_type sock) { (void)sock; return 0; } } static enum callback_return eventloop_fake_add(const void *this_ptr, const struct io_event *ev) { (void)this_ptr; (void)ev; return CONTINUE_LOOP; } static void eventloop_fake_remove(const void *this_ptr, const struct io_event *ev) { (void)this_ptr; (void)ev; } static void ws_on_error(struct websocket *ws) { (void)ws; ws_error = true; } static int on_headers_complete(http_parser *parser) { (void)parser; got_complete_response_header = true; return 0; } struct F { enum response_on_header_field { HEADER_UNKNOWN, HEADER_UPGRADE, HEADER_CONNECTION, HEADER_ACCEPT, }; F() { loop.init = NULL; loop.destroy = NULL; loop.run = NULL; loop.add = eventloop_fake_add; loop.remove = eventloop_fake_remove; readbuffer_ptr = readbuffer; got_complete_response_header = false; response_parse_error = false; http_parser_settings_init(&parser_settings); http_parser_init(&parser, HTTP_REQUEST); http_parser_settings_init(&response_parser_settings); http_parser_init(&response_parser, HTTP_RESPONSE); response_parser.data = this; response_parser_settings.on_header_field = response_on_header_field; response_parser_settings.on_header_value = response_on_header_value; response_parser_settings.on_headers_complete = on_headers_complete; handler[0].request_target = "/"; handler[0].create = NULL; handler[0].on_header_field = websocket_upgrade_on_header_field, handler[0].on_header_value = websocket_upgrade_on_header_value, handler[0].on_headers_complete = websocket_upgrade_on_headers_complete, handler[0].on_body = NULL; handler[0].on_message_complete = NULL; http_server.handler = handler; http_server.num_handlers = ARRAY_SIZE(handler); ::memset(websocket_accept_key, 0, sizeof(websocket_accept_key)); write_buffer_ptr = write_buffer; ws_error = false; got_upgrade_response = false; got_connection_upgrade = false; current_header_field = HEADER_UNKNOWN; } ~F() { } static int response_on_header_field(http_parser *p, const char *at, size_t length) { struct F *f = (struct F *)p->data; static const char upgrade_key[] = "Upgrade"; if ((sizeof(upgrade_key) - 1 == length) && (jet_strncasecmp(at, upgrade_key, length) == 0)) { f->current_header_field = HEADER_UPGRADE; return 0; } static const char connection_key[] = "Connection"; if ((sizeof(connection_key) - 1 == length) && (jet_strncasecmp(at, connection_key, length) == 0)) { f->current_header_field = HEADER_CONNECTION; return 0; } static const char accept_key[] = "Sec-WebSocket-Accept"; if ((sizeof(accept_key) - 1 == length) && (jet_strncasecmp(at, accept_key, length) == 0)) { f->current_header_field = HEADER_ACCEPT; return 0; } return 0; } static int response_on_header_value(http_parser *p, const char *at, size_t length) { int ret = 0; struct F *f = (struct F *)p->data; switch(f->current_header_field) { case HEADER_UPGRADE: f->got_upgrade_response = true; break; case HEADER_CONNECTION: if (jet_strncasecmp(at, "Upgrade", length) == 0) { f->got_connection_upgrade = true; } break; case HEADER_ACCEPT: { size_t len = std::min(length, sizeof(websocket_accept_key)); memcpy(f->websocket_accept_key, at, len); break; } case HEADER_UNKNOWN: default: break; } f->current_header_field = HEADER_UNKNOWN; return ret; } struct eventloop loop; http_parser parser; http_parser_settings parser_settings; struct url_handler handler[1]; struct http_server http_server; bool got_upgrade_response; bool got_connection_upgrade; enum response_on_header_field current_header_field; uint8_t websocket_accept_key[28]; }; static const uint8_t WS_HEADER_FIN = 0x80; static const uint8_t WS_CLOSE_FRAME = 0x08; static const uint8_t WS_MASK_BIT = 0x80; static const uint8_t WS_PAYLOAD_LENGTH = 0x7f; static bool is_close_frame() { if ((write_buffer[0] & WS_HEADER_FIN) == 0) { return false; } if ((write_buffer[0] & WS_CLOSE_FRAME) == 0) { return false; } if ((write_buffer[1] & WS_MASK_BIT) != 0) { return false; } size_t len = write_buffer[1] & WS_PAYLOAD_LENGTH; if (len < 2) { return false; } uint16_t status_code; ::memcpy(&status_code, &write_buffer[2], sizeof(status_code)); status_code = jet_be16toh(status_code); if (status_code != 1001) { return false; } return true; } BOOST_AUTO_TEST_CASE(test_websocket_init) { struct websocket ws; websocket_init(&ws, NULL, true, NULL); websocket_free(&ws); } BOOST_FIXTURE_TEST_CASE(test_http_upgrade, F) { char request[] = "GET / HTTP/1.1" CRLF "Connection: Upgrade" CRLF \ "Upgrade: websocket" CRLF \ "Sec-WebSocket-Version: 13" CRLF\ "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" CRLF CRLF; struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_CORRECT_UPGRADE); BOOST_REQUIRE_MESSAGE(connection != NULL, "Failed to allocate http connection"); struct websocket ws; websocket_init(&ws, connection, true, ws_on_error); connection->parser.data = &ws; bs_read_callback_return ret = websocket_read_header_line(&ws, request, ::strlen(request)); BOOST_CHECK_MESSAGE(ret == BS_OK, "websocket_read_header_line did not return BS_OK"); BOOST_CHECK_MESSAGE(ws_error == false, "Error while parsing the http upgrade request"); websocket_free(&ws); BOOST_CHECK_MESSAGE(response_parser.status_code == 101, "Expected 101 status code"); BOOST_CHECK_MESSAGE(response_parser.http_major == 1, "Expected http major 1"); BOOST_CHECK_MESSAGE(response_parser.http_minor == 1, "Expected http minor 1"); BOOST_CHECK_MESSAGE(response_parse_error == false, "Invalid upgrade response!"); BOOST_CHECK_MESSAGE(got_upgrade_response == true, "Upgrade header field missing!"); BOOST_CHECK_MESSAGE(got_connection_upgrade == true, "Connection header field missing!"); BOOST_CHECK_MESSAGE(::memcmp(websocket_accept_key, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", sizeof(websocket_accept_key)) == 0, "Got illegal websocket accept key!"); BOOST_CHECK_MESSAGE(is_close_frame(), "No close frame sent!"); } <|endoftext|>
<commit_before>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <signal.h> #include <gtest/gtest.h> #include <queue> #include <tr1/functional> #include <stout/lambda.hpp> #include "common/lock.hpp" #include "logging/logging.hpp" #include "jvm/jvm.hpp" #include "tests/utils.hpp" #include "tests/zookeeper_test.hpp" #include "tests/zookeeper_test_server.hpp" namespace mesos { namespace internal { namespace tests { const Milliseconds ZooKeeperTest::NO_TIMEOUT(5000); // Note that we NEVER delete the Jvm instance because you can only // create one JVM since destructing a JVM has issues (see: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4712793). Jvm* ZooKeeperTest::jvm = NULL; static void silenceServerLogs(Jvm* jvm) { Jvm::Attach attach(jvm); Jvm::JClass loggerClass = Jvm::JClass::forName("org/apache/log4j/Logger"); jobject rootLogger =jvm->invokeStatic<jobject>( jvm->findStaticMethod(loggerClass .method("getRootLogger") .returns(loggerClass))); Jvm::JClass levelClass = Jvm::JClass::forName("org/apache/log4j/Level"); jvm->invoke<void>( rootLogger, jvm->findMethod(loggerClass .method("setLevel") .parameter(levelClass) .returns(jvm->voidClass)), jvm->getStaticField<jobject>(jvm->findStaticField(levelClass, "OFF"))); } static void silenceClientLogs() { // TODO(jsirois): Put this in the C++ API. zoo_set_debug_level(ZOO_LOG_LEVEL_ERROR); } void ZooKeeperTest::SetUpTestCase() { if (jvm == NULL) { std::string zkHome = flags.build_dir + "/third_party/zookeeper-" ZOOKEEPER_VERSION; std::string classpath = "-Djava.class.path=" + zkHome + "/zookeeper-" ZOOKEEPER_VERSION ".jar:" + zkHome + "/lib/log4j-1.2.15.jar"; LOG(INFO) << "Using classpath setup: " << classpath << std::endl; std::vector<std::string> opts; opts.push_back(classpath); jvm = new Jvm(opts); silenceServerLogs(jvm); silenceClientLogs(); } } void ZooKeeperTest::SetUp() { server = new ZooKeeperTestServer(jvm); server->startNetwork(); }; void ZooKeeperTest::TearDown() { delete server; server = NULL; }; ZooKeeperTest::TestWatcher::TestWatcher() { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); pthread_mutex_init(&mutex, &attr); pthread_mutexattr_destroy(&attr); pthread_cond_init(&cond, 0); } ZooKeeperTest::TestWatcher::~TestWatcher() { pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); } void ZooKeeperTest::TestWatcher::process( ZooKeeper* zk, int type, int state, const std::string& path) { Lock lock(&mutex); events.push(Event(type, state, path)); pthread_cond_signal(&cond); } static bool isSessionState( const ZooKeeperTest::TestWatcher::Event& event, int state) { return event.type == ZOO_SESSION_EVENT && event.state == state; } void ZooKeeperTest::TestWatcher::awaitSessionEvent(int state) { awaitEvent(lambda::bind(&isSessionState, lambda::_1, state)); } static bool isCreated( const ZooKeeperTest::TestWatcher::Event& event, const std::string& path) { return event.type == ZOO_CHILD_EVENT && event.path == path; } void ZooKeeperTest::TestWatcher::awaitCreated(const std::string& path) { awaitEvent(lambda::bind(&isCreated, lambda::_1, path)); } ZooKeeperTest::TestWatcher::Event ZooKeeperTest::TestWatcher::awaitEvent() { Lock lock(&mutex); while (true) { while (events.empty()) { pthread_cond_wait(&cond, &mutex); } Event event = events.front(); events.pop(); return event; } } ZooKeeperTest::TestWatcher::Event ZooKeeperTest::TestWatcher::awaitEvent( const std::tr1::function<bool(Event)>& matches) { while (true) { Event event = awaitEvent(); if (matches(event)) { return event; } } } } // namespace tests { } // namespace internal { } // namespace mesos { <commit_msg>Don't silence ZooKeeper tests when the 'verbose' option is specified.<commit_after>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <signal.h> #include <gtest/gtest.h> #include <queue> #include <tr1/functional> #include <stout/lambda.hpp> #include "common/lock.hpp" #include "logging/logging.hpp" #include "jvm/jvm.hpp" #include "tests/utils.hpp" #include "tests/zookeeper_test.hpp" #include "tests/zookeeper_test_server.hpp" namespace mesos { namespace internal { namespace tests { const Milliseconds ZooKeeperTest::NO_TIMEOUT(5000); // Note that we NEVER delete the Jvm instance because you can only // create one JVM since destructing a JVM has issues (see: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4712793). Jvm* ZooKeeperTest::jvm = NULL; static void silenceServerLogs(Jvm* jvm) { Jvm::Attach attach(jvm); Jvm::JClass loggerClass = Jvm::JClass::forName("org/apache/log4j/Logger"); jobject rootLogger =jvm->invokeStatic<jobject>( jvm->findStaticMethod(loggerClass .method("getRootLogger") .returns(loggerClass))); Jvm::JClass levelClass = Jvm::JClass::forName("org/apache/log4j/Level"); jvm->invoke<void>( rootLogger, jvm->findMethod(loggerClass .method("setLevel") .parameter(levelClass) .returns(jvm->voidClass)), jvm->getStaticField<jobject>(jvm->findStaticField(levelClass, "OFF"))); } static void silenceClientLogs() { // TODO(jsirois): Put this in the C++ API. zoo_set_debug_level(ZOO_LOG_LEVEL_ERROR); } void ZooKeeperTest::SetUpTestCase() { if (jvm == NULL) { std::string zkHome = flags.build_dir + "/third_party/zookeeper-" ZOOKEEPER_VERSION; std::string classpath = "-Djava.class.path=" + zkHome + "/zookeeper-" ZOOKEEPER_VERSION ".jar:" + zkHome + "/lib/log4j-1.2.15.jar"; LOG(INFO) << "Using classpath setup: " << classpath << std::endl; std::vector<std::string> opts; opts.push_back(classpath); jvm = new Jvm(opts); if (!flags.verbose) { silenceServerLogs(jvm); silenceClientLogs(); } } } void ZooKeeperTest::SetUp() { server = new ZooKeeperTestServer(jvm); server->startNetwork(); }; void ZooKeeperTest::TearDown() { delete server; server = NULL; }; ZooKeeperTest::TestWatcher::TestWatcher() { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); pthread_mutex_init(&mutex, &attr); pthread_mutexattr_destroy(&attr); pthread_cond_init(&cond, 0); } ZooKeeperTest::TestWatcher::~TestWatcher() { pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); } void ZooKeeperTest::TestWatcher::process( ZooKeeper* zk, int type, int state, const std::string& path) { Lock lock(&mutex); events.push(Event(type, state, path)); pthread_cond_signal(&cond); } static bool isSessionState( const ZooKeeperTest::TestWatcher::Event& event, int state) { return event.type == ZOO_SESSION_EVENT && event.state == state; } void ZooKeeperTest::TestWatcher::awaitSessionEvent(int state) { awaitEvent(lambda::bind(&isSessionState, lambda::_1, state)); } static bool isCreated( const ZooKeeperTest::TestWatcher::Event& event, const std::string& path) { return event.type == ZOO_CHILD_EVENT && event.path == path; } void ZooKeeperTest::TestWatcher::awaitCreated(const std::string& path) { awaitEvent(lambda::bind(&isCreated, lambda::_1, path)); } ZooKeeperTest::TestWatcher::Event ZooKeeperTest::TestWatcher::awaitEvent() { Lock lock(&mutex); while (true) { while (events.empty()) { pthread_cond_wait(&cond, &mutex); } Event event = events.front(); events.pop(); return event; } } ZooKeeperTest::TestWatcher::Event ZooKeeperTest::TestWatcher::awaitEvent( const std::tr1::function<bool(Event)>& matches) { while (true) { Event event = awaitEvent(); if (matches(event)) { return event; } } } } // namespace tests { } // namespace internal { } // namespace mesos { <|endoftext|>
<commit_before>/* ***************************************************************************** * ___ _ _ _ _ * / _ \ __ _| |_| |__(_) |_ ___ * | (_) / _` | / / '_ \ | _(_-< * \___/\__,_|_\_\_.__/_|\__/__/ * Copyright (c) 2012 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *****************************************************************************/ /** * @author R. Picard * @date 2011/05/01 * *****************************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <dlfcn.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <cxxabi.h> #include "CallStack.h" #ifdef HAVE_LIBUNWIND #define UNW_LOCAL_ONLY #include "libunwind.h" #endif /** * @date 2012/03/22 * * Constructor. ******************************************************************************/ CallStack::CallStack(void): Depth(CALLSTACK_MAX_DEPTH), SkipFrameCount(0), StackIndex(0), NamesAreResolved(false) { memset(Stack, 0, CALLSTACK_MAX_DEPTH*sizeof(void*)); memset(StackNames, 0, CALLSTACK_MAX_DEPTH*ALLOCER_NAME_SIZE*sizeof(char)); return; } /** * @date 2012/02/09 * * Copy Constructor. * @param Callers (in): Callstack.to copy. * @param Level (in): Optionnal max level to copy. If Level is strictly positive * and less that the depth of Callers, then only this level of callers is * assigned. ******************************************************************************/ CallStack::CallStack(const CallStack& Callers, uint32_t Level): Depth(Callers.GetDepth()), SkipFrameCount(0), StackIndex(0), NamesAreResolved(false) { memset(Stack, 0, CALLSTACK_MAX_DEPTH*sizeof(void*)); memset(StackNames, 0, CALLSTACK_MAX_DEPTH*ALLOCER_NAME_SIZE*sizeof(char)); if( (Level > 0) &&(Level < Depth) ) Depth = Level; SetTo(Callers); return; } /** * @date 2012/03/22 * * Destructor. * ******************************************************************************/ CallStack::~CallStack(void) { return; } /** * @date 2013/02/22 * * Equality operator. Two callstacks are considered equal if their Stack arrays * are identical. * ******************************************************************************/ bool CallStack::operator==(const CallStack &Rhs) const { if(Depth == Rhs.GetDepth()) { if(memcmp(Stack, Rhs.Get(), Depth*sizeof(void*)) == 0) return(true); } return(false); } /** * @date 2013/02/22 * * Inequality operator. * ******************************************************************************/ bool CallStack::operator!=(const CallStack &Rhs) const { return(!operator==(Rhs)); } /** * @date 2013/03/25 * * Equality operator for only a specified depth. ******************************************************************************/ bool CallStack::CallerIs(const CallStack &Rhs, uint32_t Level) const { if((Depth >= Level) && (Rhs.GetDepth() >= Level)) { if(memcmp(Stack, Rhs.Get(), Level*sizeof(void*)) == 0) return(true); } return(false); } #ifdef HAVE_LIBUNWIND void CallStack::Unwind(void) { Depth = CALLSTACK_MAX_DEPTH; SkipFrameCount = 1; StackIndex = 0; unw_cursor_t cursor; unw_context_t context; // Initialize cursor to current frame for local unwinding. unw_getcontext(&context); unw_init_local(&cursor, &context); // Unwind frames one by one, going up the frame stack. while (unw_step(&cursor) > 0) { unw_word_t pc; unw_get_reg(&cursor, UNW_REG_IP, &pc); if (pc == 0) { break; } if( (--SkipFrameCount < 0) && (StackIndex < CALLSTACK_MAX_DEPTH) ) { Stack[StackIndex] = reinterpret_cast<void *>(pc); StackIndex++; } } return; } #else /** * @date 2012/03/22 * * Unwind the callers. * ******************************************************************************/ void CallStack::Unwind(void) { Depth = CALLSTACK_MAX_DEPTH; SkipFrameCount = 2; StackIndex = 0; _Unwind_Backtrace(UnwindCallback, this); return; } /** * @date 2012/03/22 * * Unwind callback. * ******************************************************************************/ _Unwind_Reason_Code CallStack::UnwindCallback(struct _Unwind_Context *Context, void *Closure) { CallStack *This = static_cast<CallStack*>(Closure); if(This != NULL) return(This->UnwindCallback(Context)); return _URC_FOREIGN_EXCEPTION_CAUGHT; } /** * @date 2012/03/22 * * Unwind callback. * ******************************************************************************/ _Unwind_Reason_Code CallStack::UnwindCallback(struct _Unwind_Context *Context) { if( (--SkipFrameCount < 0) && (StackIndex < CALLSTACK_MAX_DEPTH) ) { Stack[StackIndex] = reinterpret_cast<void *>(_Unwind_GetIP(Context)); StackIndex++; } return _URC_NO_REASON; } #endif /** * @date 2013/02/25 * * Initializes the callstack from another callstack but for only one level (the * caller). * ******************************************************************************/ void CallStack::SetCaller(const CallStack& Callers) { Depth = 1; Stack[0] = Callers.Get()[0]; return; } /** * @date 2012/03/22 * * Sets the CallStack to the state of another one. * ******************************************************************************/ void CallStack::SetTo(const CallStack &Target, uint32_t Level) { memcpy(Stack, Target.Get(), sizeof(Stack)); return; } /** * @date 2013/02/11 * * Resolves the symbols names in the callstack. * ******************************************************************************/ void CallStack::ResolveNames(void) { if(NamesAreResolved == true) return; uint32_t Level; for(Level=0; Level<Depth; Level++) { if(Stack[Level] != NULL) { Dl_info s_info; if( (dladdr(Stack[Level], &s_info) != 0) && (s_info.dli_sname != NULL) ) { int Status; char* UnmangledName = abi::__cxa_demangle(s_info.dli_sname, NULL, 0, &Status); if(UnmangledName != NULL) { snprintf(StackNames[Level], ALLOCER_NAME_SIZE, "%p:%s", Stack[Level], UnmangledName); free(UnmangledName); } else { snprintf(StackNames[Level], ALLOCER_NAME_SIZE, "%p:%s", Stack[Level], s_info.dli_sname); } if(s_info.dli_fname != NULL) { strncpy(SoNames[Level], s_info.dli_fname, ALLOCER_NAME_SIZE); } else { strncpy(SoNames[Level], "", ALLOCER_NAME_SIZE); } } else { snprintf(StackNames[Level], ALLOCER_NAME_SIZE, "%p", Stack[Level]); } StackNames[Level][ALLOCER_NAME_SIZE-1] = '\0'; SoNames[Level][ALLOCER_NAME_SIZE-1] = '\0'; } } NamesAreResolved = true; } /** * @date 2013/02/09 * * Returns the symbol name of the callstack at the specified level. * ******************************************************************************/ const char* CallStack::GetName(uint32_t Level) { if(Level >= Depth) return(NULL); ResolveNames(); if(StackNames[Level][0] == '\0') return(NULL); return(StackNames[Level]); } /** * Returns the shared object name of the callstack at the specified level. */ const char* CallStack::GetSoName(uint32_t Level) { if(Level >= Depth) return(NULL); ResolveNames(); if(SoNames[Level][0] == '\0') return(NULL); return(SoNames[Level]); } <commit_msg>Fixed soname initialization<commit_after>/* ***************************************************************************** * ___ _ _ _ _ * / _ \ __ _| |_| |__(_) |_ ___ * | (_) / _` | / / '_ \ | _(_-< * \___/\__,_|_\_\_.__/_|\__/__/ * Copyright (c) 2012 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *****************************************************************************/ /** * @author R. Picard * @date 2011/05/01 * *****************************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <dlfcn.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <cxxabi.h> #include "CallStack.h" #ifdef HAVE_LIBUNWIND #define UNW_LOCAL_ONLY #include "libunwind.h" #endif /** * @date 2012/03/22 * * Constructor. ******************************************************************************/ CallStack::CallStack(void): Depth(CALLSTACK_MAX_DEPTH), SkipFrameCount(0), StackIndex(0), NamesAreResolved(false) { memset(Stack, 0, CALLSTACK_MAX_DEPTH*sizeof(void*)); memset(StackNames, 0, CALLSTACK_MAX_DEPTH*ALLOCER_NAME_SIZE*sizeof(char)); memset(SoNames, 0, CALLSTACK_MAX_DEPTH*ALLOCER_NAME_SIZE*sizeof(char)); return; } /** * @date 2012/02/09 * * Copy Constructor. * @param Callers (in): Callstack.to copy. * @param Level (in): Optionnal max level to copy. If Level is strictly positive * and less that the depth of Callers, then only this level of callers is * assigned. ******************************************************************************/ CallStack::CallStack(const CallStack& Callers, uint32_t Level): Depth(Callers.GetDepth()), SkipFrameCount(0), StackIndex(0), NamesAreResolved(false) { memset(Stack, 0, CALLSTACK_MAX_DEPTH*sizeof(void*)); memset(StackNames, 0, CALLSTACK_MAX_DEPTH*ALLOCER_NAME_SIZE*sizeof(char)); memset(SoNames, 0, CALLSTACK_MAX_DEPTH*ALLOCER_NAME_SIZE*sizeof(char)); if( (Level > 0) &&(Level < Depth) ) Depth = Level; SetTo(Callers); return; } /** * @date 2012/03/22 * * Destructor. * ******************************************************************************/ CallStack::~CallStack(void) { return; } /** * @date 2013/02/22 * * Equality operator. Two callstacks are considered equal if their Stack arrays * are identical. * ******************************************************************************/ bool CallStack::operator==(const CallStack &Rhs) const { if(Depth == Rhs.GetDepth()) { if(memcmp(Stack, Rhs.Get(), Depth*sizeof(void*)) == 0) return(true); } return(false); } /** * @date 2013/02/22 * * Inequality operator. * ******************************************************************************/ bool CallStack::operator!=(const CallStack &Rhs) const { return(!operator==(Rhs)); } /** * @date 2013/03/25 * * Equality operator for only a specified depth. ******************************************************************************/ bool CallStack::CallerIs(const CallStack &Rhs, uint32_t Level) const { if((Depth >= Level) && (Rhs.GetDepth() >= Level)) { if(memcmp(Stack, Rhs.Get(), Level*sizeof(void*)) == 0) return(true); } return(false); } #ifdef HAVE_LIBUNWIND void CallStack::Unwind(void) { Depth = CALLSTACK_MAX_DEPTH; SkipFrameCount = 1; StackIndex = 0; unw_cursor_t cursor; unw_context_t context; // Initialize cursor to current frame for local unwinding. unw_getcontext(&context); unw_init_local(&cursor, &context); // Unwind frames one by one, going up the frame stack. while (unw_step(&cursor) > 0) { unw_word_t pc; unw_get_reg(&cursor, UNW_REG_IP, &pc); if (pc == 0) { break; } if( (--SkipFrameCount < 0) && (StackIndex < CALLSTACK_MAX_DEPTH) ) { Stack[StackIndex] = reinterpret_cast<void *>(pc); StackIndex++; } } return; } #else /** * @date 2012/03/22 * * Unwind the callers. * ******************************************************************************/ void CallStack::Unwind(void) { Depth = CALLSTACK_MAX_DEPTH; SkipFrameCount = 2; StackIndex = 0; _Unwind_Backtrace(UnwindCallback, this); return; } /** * @date 2012/03/22 * * Unwind callback. * ******************************************************************************/ _Unwind_Reason_Code CallStack::UnwindCallback(struct _Unwind_Context *Context, void *Closure) { CallStack *This = static_cast<CallStack*>(Closure); if(This != NULL) return(This->UnwindCallback(Context)); return _URC_FOREIGN_EXCEPTION_CAUGHT; } /** * @date 2012/03/22 * * Unwind callback. * ******************************************************************************/ _Unwind_Reason_Code CallStack::UnwindCallback(struct _Unwind_Context *Context) { if( (--SkipFrameCount < 0) && (StackIndex < CALLSTACK_MAX_DEPTH) ) { Stack[StackIndex] = reinterpret_cast<void *>(_Unwind_GetIP(Context)); StackIndex++; } return _URC_NO_REASON; } #endif /** * @date 2013/02/25 * * Initializes the callstack from another callstack but for only one level (the * caller). * ******************************************************************************/ void CallStack::SetCaller(const CallStack& Callers) { Depth = 1; Stack[0] = Callers.Get()[0]; return; } /** * @date 2012/03/22 * * Sets the CallStack to the state of another one. * ******************************************************************************/ void CallStack::SetTo(const CallStack &Target, uint32_t Level) { memcpy(Stack, Target.Get(), sizeof(Stack)); return; } /** * @date 2013/02/11 * * Resolves the symbols names in the callstack. * ******************************************************************************/ void CallStack::ResolveNames(void) { if(NamesAreResolved == true) return; uint32_t Level; for(Level=0; Level<Depth; Level++) { if(Stack[Level] != NULL) { Dl_info s_info; if( (dladdr(Stack[Level], &s_info) != 0) && (s_info.dli_sname != NULL) ) { int Status; char* UnmangledName = abi::__cxa_demangle(s_info.dli_sname, NULL, 0, &Status); if(UnmangledName != NULL) { snprintf(StackNames[Level], ALLOCER_NAME_SIZE, "%p:%s", Stack[Level], UnmangledName); free(UnmangledName); } else { snprintf(StackNames[Level], ALLOCER_NAME_SIZE, "%p:%s", Stack[Level], s_info.dli_sname); } if(s_info.dli_fname != NULL) { strncpy(SoNames[Level], s_info.dli_fname, ALLOCER_NAME_SIZE); } else { strncpy(SoNames[Level], "", ALLOCER_NAME_SIZE); } } else { snprintf(StackNames[Level], ALLOCER_NAME_SIZE, "%p", Stack[Level]); } StackNames[Level][ALLOCER_NAME_SIZE-1] = '\0'; SoNames[Level][ALLOCER_NAME_SIZE-1] = '\0'; } } NamesAreResolved = true; } /** * @date 2013/02/09 * * Returns the symbol name of the callstack at the specified level. * ******************************************************************************/ const char* CallStack::GetName(uint32_t Level) { if(Level >= Depth) return(NULL); ResolveNames(); if(StackNames[Level][0] == '\0') return(NULL); return(StackNames[Level]); } /** * Returns the shared object name of the callstack at the specified level. */ const char* CallStack::GetSoName(uint32_t Level) { if(Level >= Depth) return(NULL); ResolveNames(); if(SoNames[Level][0] == '\0') return(NULL); return(SoNames[Level]); } <|endoftext|>
<commit_before>// Copyright (c) 2007, 2008, 2009 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include <algorithm> #include <string> #include "libmv/base/vector.h" #include "libmv/correspondence/klt.h" #include "libmv/image/image.h" #include "libmv/image/image_io.h" #include "libmv/image/image_drawing.h" #include "libmv/image/surf.h" #include "libmv/image/surf_descriptor.h" #include "libmv/tools/tool.h" using namespace libmv; using namespace std; void usage() { LOG(ERROR) << " interest_points ImageNameIn.pgm ImageNameOut.pgm " <<std::endl << " ImageNameIn.pgm : the input image on which surf features will be extrated, " << std::endl << " ImageNameOut.pgm : the surf keypoints will be displayed on it. " << std::endl << " INFO : work with pgm image only." << std::endl; } void DrawSurfFeatures( Array3Df & im, const libmv::vector<libmv::SurfFeature> & feat); int main(int argc, char **argv) { libmv::Init("Extract surf feature from an image", &argc, &argv); if (argc != 3 || !(GetFormat(argv[1])==Pnm && GetFormat(argv[2])==Pnm)) { usage(); LOG(ERROR) << "Missing parameters or errors in the command line."; return 1; } // Parse input parameter const string sImageIn = argv[1]; const string sImageOut = argv[2]; Array3Du imageIn; if (!ReadPnm(sImageIn.c_str(), &imageIn)) { LOG(FATAL) << "Failed loading image: " << sImageIn; return 0; } Array3Df image; ByteArrayToScaledFloatArray(imageIn, &image); // TODO(pmoulon) Assert that the image value is within [0.f;255.f] for(int j=0; j < image.Height(); ++j) for(int i=0; i < image.Width(); ++i) image(j,i) *=255; libmv::vector<libmv::SurfFeature> features; libmv::SurfFeatures(image, 4, 4, &features); DrawSurfFeatures(image, features); if (!WritePnm(image, sImageOut.c_str())) { LOG(FATAL) << "Failed saving output image: " << sImageOut; } return 0; } void DrawSurfFeatures( Array3Df & im, const libmv::vector<libmv::SurfFeature> & feat) { std::cout << feat.size() << " Detected points " <<std::endl; for (int i = 0; i < feat.size(); ++i) { const libmv::SurfFeature & feature = feat[i]; const int x = feature.x(); const int y = feature.y(); const float scale = 2*feature.scale; //std::cout << i << " " << x << " " << y << " " << feature.getScale() <<std::endl; DrawCircle(x, y, scale, (unsigned char)255, &im); const float angle = feature.orientation; DrawLine(x, y, x + scale * cos(angle), y + scale*sin(angle), (unsigned char) 255, &im); } } <commit_msg>Add unused flag to interest points tool.<commit_after>// Copyright (c) 2007, 2008, 2009 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include <algorithm> #include <string> #include "libmv/base/vector.h" #include "libmv/correspondence/klt.h" #include "libmv/image/image.h" #include "libmv/image/image_io.h" #include "libmv/image/image_drawing.h" #include "libmv/image/surf.h" #include "libmv/image/surf_descriptor.h" #include "libmv/tools/tool.h" DEFINE_string(detector, "fast", "Detector type."); using namespace libmv; using namespace std; void usage() { LOG(ERROR) << " interest_points ImageNameIn.pgm ImageNameOut.pgm " <<std::endl << " ImageNameIn.pgm : the input image on which surf features will be extrated, " << std::endl << " ImageNameOut.pgm : the surf keypoints will be displayed on it. " << std::endl << " INFO : work with pgm image only." << std::endl; } void DrawSurfFeatures( Array3Df & im, const libmv::vector<libmv::SurfFeature> & feat); int main(int argc, char **argv) { libmv::Init("Extract surf feature from an image", &argc, &argv); if (argc != 3 || !(GetFormat(argv[1])==Pnm && GetFormat(argv[2])==Pnm)) { usage(); LOG(ERROR) << "Missing parameters or errors in the command line."; return 1; } // Parse input parameter const string sImageIn = argv[1]; const string sImageOut = argv[2]; Array3Du imageIn; if (!ReadPnm(sImageIn.c_str(), &imageIn)) { LOG(FATAL) << "Failed loading image: " << sImageIn; return 0; } Array3Df image; ByteArrayToScaledFloatArray(imageIn, &image); // TODO(pmoulon) Assert that the image value is within [0.f;255.f] for(int j=0; j < image.Height(); ++j) for(int i=0; i < image.Width(); ++i) image(j,i) *=255; libmv::vector<libmv::SurfFeature> features; libmv::SurfFeatures(image, 4, 4, &features); DrawSurfFeatures(image, features); if (!WritePnm(image, sImageOut.c_str())) { LOG(FATAL) << "Failed saving output image: " << sImageOut; } return 0; } void DrawSurfFeatures( Array3Df & im, const libmv::vector<libmv::SurfFeature> & feat) { std::cout << feat.size() << " Detected points " <<std::endl; for (int i = 0; i < feat.size(); ++i) { const libmv::SurfFeature & feature = feat[i]; const int x = feature.x(); const int y = feature.y(); const float scale = 2*feature.scale; //std::cout << i << " " << x << " " << y << " " << feature.getScale() <<std::endl; DrawCircle(x, y, scale, (unsigned char)255, &im); const float angle = feature.orientation; DrawLine(x, y, x + scale * cos(angle), y + scale*sin(angle), (unsigned char) 255, &im); } } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_GLM_LPMF_HPP #define STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_GLM_LPMF_HPP #include <stan/math/prim/scal/meta/is_constant_struct.hpp> #include <stan/math/prim/scal/meta/partials_return_type.hpp> #include <stan/math/prim/scal/meta/operands_and_partials.hpp> #include <stan/math/prim/scal/err/check_consistent_sizes.hpp> #include <stan/math/prim/scal/err/check_bounded.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/mat/fun/value_of_rec.hpp> #include <stan/math/prim/arr/fun/value_of_rec.hpp> #include <stan/math/prim/mat/meta/as_column_vector_or_scalar.hpp> #include <stan/math/prim/scal/meta/as_column_vector_or_scalar.hpp> #include <stan/math/prim/scal/meta/include_summand.hpp> #include <stan/math/prim/scal/fun/size_zero.hpp> #include <stan/math/prim/mat/err/check_ordered.hpp> #include <stan/math/prim/arr/err/check_ordered.hpp> #include <stan/math/prim/mat/fun/log1m_exp.hpp> #include <stan/math/prim/scal/meta/is_vector.hpp> #include <stan/math/prim/scal/meta/scalar_seq_view.hpp> #include <cmath> namespace stan { namespace math { /** * Returns the log PMF of the ordinal regression Generalized Linear Model (GLM). * This is equivalent to and faster than ordered_logistic_lpmf(y, x * beta, * cuts). * * @tparam T_y type of integer vector of classes. It can be either `std::vector<int>` or `int`. * @tparam T_x_scalar type of elements in the matrix of independent variables * (features) * @tparam T_x_rows compile-time number of rows of `x`. It can be either * `Eigen::Dynamic` or 1. * @tparam T_beta_scalar type of a scalar in the vector of weights * @tparam T_cuts_scalar type of a scalar in the vector of cutpoints * @param y a scalar or vector of classes. If it is a scalar it will be * broadcast - used for all instances. Values should be between 1 and number of * classes, including endpoints. * @param x design matrix or row vector. If it is a row vector it will be * broadcast - used for all instances. * @param beta weight vector * @param cuts cutpoints vector * @return log probability * @throw std::domain_error If any class is not between 1 and * the number of cutpoints plus 2 or if the cutpoint vector is not sorted in * ascending order or any input is not finite * @throw std::invalid_argument if container sizes mismatch. */ template <bool propto, typename T_y, typename T_x_scalar, int T_x_rows, typename T_beta_scalar, typename T_cuts_scalar> typename stan::return_type<T_x_scalar, T_beta_scalar, T_cuts_scalar>::type ordered_logistic_glm_lpmf( const T_y& y, const Eigen::Matrix<T_x_scalar, T_x_rows, Eigen::Dynamic>& x, const Eigen::Matrix<T_beta_scalar, Eigen::Dynamic, 1>& beta, const Eigen::Matrix<T_cuts_scalar, Eigen::Dynamic,1>& cuts) { using Eigen::Array; using Eigen::Dynamic; using Eigen::Matrix; using Eigen::VectorXd; using std::exp; using std::isfinite; typedef typename partials_return_type<T_y, T_x_scalar, T_beta_scalar, T_cuts_scalar>::type T_partials_return; typedef typename std::conditional<T_x_rows == 1, double, Array<double, Dynamic, 1>>::type T_location; static const char* function = "ordered_logistic_glm_lpmf"; const size_t N_instances = T_x_rows == 1 ? length(y) : x.rows(); const size_t N_attributes = x.cols(); const size_t N_classes = length(cuts) + 1; if(is_vector<T_y>::value && T_x_rows!=1) { check_consistent_size(function, "Vector of dependent variables", y, N_instances); } check_consistent_size(function, "Weight vector", beta, N_attributes); check_bounded(function, "Vector of dependent variables", y, 1, N_classes); check_ordered(function, "Cut-points", cuts); check_finite(function, "Final cut-point", cuts[N_classes - 2]); check_finite(function, "First cut-point", cuts[0]); if (size_zero(y, cuts)) return 0; if (!include_summand<propto, T_x_scalar, T_beta_scalar, T_cuts_scalar>::value) return 0; T_partials_return logp(0); const auto& x_val = value_of_rec(x); const auto& beta_val = value_of_rec(beta); const auto& cuts_val = value_of_rec(cuts); const auto& beta_val_vec = as_column_vector_or_scalar(beta_val); const auto& cuts_val_vec = as_column_vector_or_scalar(cuts_val); scalar_seq_view<T_y> y_seq(y); Array<double, Dynamic, 1> cuts_y1(N_instances), cuts_y2(N_instances); for (int i = 0; i < N_instances; i++) { int c = y_seq[i]; if (c != N_classes) { cuts_y1[i] = cuts_val_vec[c - 1]; } else { cuts_y1[i] = INFINITY; } if (c != 1) { cuts_y2[i] = cuts_val_vec[c - 2]; } else { cuts_y2[i] = -INFINITY; } } T_location location = x_val * beta_val_vec; if (!isfinite(sum(location))) { check_finite(function, "Weight vector", beta); check_finite(function, "Matrix of independent variables", x); } Array<double, Dynamic, 1> cut2 = location - cuts_y2; Array<double, Dynamic, 1> cut1 = location - cuts_y1; // Not immediately evaluating next two expressions benefits performance auto m_log_1p_exp_cut1 = -cut1 * (cut1 > 0.0).cast<double>() - (-cut1.abs()).exp().log1p(); auto m_log_1p_exp_m_cut2 = cut2 * (cut2 <= 0.0).cast<double>() - (-cut2.abs()).exp().log1p(); if (is_vector<T_y>::value) { Eigen::Map<const Eigen::Matrix<int, Eigen::Dynamic, 1>> y_vec(&y_seq[0], y_seq.size()); logp = y_vec.cwiseEqual(1) .select(m_log_1p_exp_cut1, y_vec.cwiseEqual(N_classes).select( m_log_1p_exp_m_cut2, m_log_1p_exp_m_cut2 + log1m_exp(cut1 - cut2).array() + m_log_1p_exp_cut1)) .sum(); } else { if (y_seq[0] == 1) { logp = m_log_1p_exp_cut1.sum(); } else if (y_seq[0] == N_classes) { logp = m_log_1p_exp_m_cut2.sum(); } else { logp = (m_log_1p_exp_m_cut2 + log1m_exp(cut1 - cut2).array() + m_log_1p_exp_cut1).sum(); } } operands_and_partials<Matrix<T_x_scalar, T_x_rows, Dynamic>, Eigen::Matrix<T_beta_scalar, Eigen::Dynamic, 1>, Eigen::Matrix<T_cuts_scalar, Eigen::Dynamic,1>> ops_partials(x, beta, cuts); if (!is_constant_struct<T_x_scalar>::value || !is_constant_struct<T_beta_scalar>::value || !is_constant_struct<T_cuts_scalar>::value) { Array<double, Dynamic, 1> d1 = 1 / (1 + exp(cut2)) - 1 / (1 - exp(cuts_y1 - cuts_y2)); Array<double, Dynamic, 1> d2 = 1 / (1 - exp(cuts_y2 - cuts_y1)) - 1 / (1 + exp(cut1)); if (!is_constant_struct<T_x_scalar>::value || !is_constant_struct<T_beta_scalar>::value) { Matrix<double, 1, Dynamic> location_derivative = d1 - d2; if (!is_constant_struct<T_x_scalar>::value) { if(T_x_rows==1){ ops_partials.edge1_.partials_ = beta_val_vec * location_derivative.sum(); } else { ops_partials.edge1_.partials_ = (beta_val_vec * location_derivative).transpose(); } } if (!is_constant_struct<T_beta_scalar>::value) { if(T_x_rows==1){ ops_partials.edge2_.partials_ = (location_derivative * x_val.replicate(N_instances,1)).transpose(); } else { ops_partials.edge2_.partials_ = (location_derivative * x_val).transpose(); } } } if (!is_constant_struct<T_cuts_scalar>::value) { for (int i = 0; i < N_instances; i++) { int c = y_seq[i]; if (c != N_classes) { ops_partials.edge3_.partials_[c - 1] += d2[i]; } if (c != 1) { ops_partials.edge3_.partials_[c - 2] -= d1[i]; } } } } return ops_partials.build(logp); } template <typename T_y, typename T_x_scalar, int T_x_rows, typename T_beta_scalar, typename T_cuts_scalar> typename stan::return_type<T_x_scalar, T_beta_scalar, T_cuts_scalar>::type ordered_logistic_glm_lpmf( const T_y& y, const Eigen::Matrix<T_x_scalar, T_x_rows, Eigen::Dynamic>& x, const Eigen::Matrix<T_beta_scalar, Eigen::Dynamic, 1>& beta, const Eigen::Matrix<T_cuts_scalar, Eigen::Dynamic,1>& cuts) { return ordered_logistic_glm_lpmf<false>(y, x, beta, cuts); } } // namespace math } // namespace stan #endif <commit_msg>optimized log1p_exp calculations<commit_after>#ifndef STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_GLM_LPMF_HPP #define STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_GLM_LPMF_HPP #include <stan/math/prim/scal/meta/is_constant_struct.hpp> #include <stan/math/prim/scal/meta/partials_return_type.hpp> #include <stan/math/prim/scal/meta/operands_and_partials.hpp> #include <stan/math/prim/scal/err/check_consistent_sizes.hpp> #include <stan/math/prim/scal/err/check_bounded.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/mat/fun/value_of_rec.hpp> #include <stan/math/prim/arr/fun/value_of_rec.hpp> #include <stan/math/prim/mat/meta/as_column_vector_or_scalar.hpp> #include <stan/math/prim/scal/meta/as_column_vector_or_scalar.hpp> #include <stan/math/prim/scal/meta/include_summand.hpp> #include <stan/math/prim/scal/fun/size_zero.hpp> #include <stan/math/prim/mat/err/check_ordered.hpp> #include <stan/math/prim/arr/err/check_ordered.hpp> #include <stan/math/prim/mat/fun/log1m_exp.hpp> #include <stan/math/prim/scal/meta/is_vector.hpp> #include <stan/math/prim/scal/meta/scalar_seq_view.hpp> #include <cmath> namespace stan { namespace math { /** * Returns the log PMF of the ordinal regression Generalized Linear Model (GLM). * This is equivalent to and faster than ordered_logistic_lpmf(y, x * beta, * cuts). * * @tparam T_y type of integer vector of classes. It can be either `std::vector<int>` or `int`. * @tparam T_x_scalar type of elements in the matrix of independent variables * (features) * @tparam T_x_rows compile-time number of rows of `x`. It can be either * `Eigen::Dynamic` or 1. * @tparam T_beta_scalar type of a scalar in the vector of weights * @tparam T_cuts_scalar type of a scalar in the vector of cutpoints * @param y a scalar or vector of classes. If it is a scalar it will be * broadcast - used for all instances. Values should be between 1 and number of * classes, including endpoints. * @param x design matrix or row vector. If it is a row vector it will be * broadcast - used for all instances. * @param beta weight vector * @param cuts cutpoints vector * @return log probability * @throw std::domain_error If any class is not between 1 and * the number of cutpoints plus 2 or if the cutpoint vector is not sorted in * ascending order or any input is not finite * @throw std::invalid_argument if container sizes mismatch. */ template <bool propto, typename T_y, typename T_x_scalar, int T_x_rows, typename T_beta_scalar, typename T_cuts_scalar> typename stan::return_type<T_x_scalar, T_beta_scalar, T_cuts_scalar>::type ordered_logistic_glm_lpmf( const T_y& y, const Eigen::Matrix<T_x_scalar, T_x_rows, Eigen::Dynamic>& x, const Eigen::Matrix<T_beta_scalar, Eigen::Dynamic, 1>& beta, const Eigen::Matrix<T_cuts_scalar, Eigen::Dynamic,1>& cuts) { using Eigen::Array; using Eigen::Dynamic; using Eigen::Matrix; using Eigen::VectorXd; using std::exp; using std::isfinite; typedef typename partials_return_type<T_y, T_x_scalar, T_beta_scalar, T_cuts_scalar>::type T_partials_return; typedef typename std::conditional<T_x_rows == 1, double, Array<double, Dynamic, 1>>::type T_location; static const char* function = "ordered_logistic_glm_lpmf"; const size_t N_instances = T_x_rows == 1 ? length(y) : x.rows(); const size_t N_attributes = x.cols(); const size_t N_classes = length(cuts) + 1; if(is_vector<T_y>::value && T_x_rows!=1) { check_consistent_size(function, "Vector of dependent variables", y, N_instances); } check_consistent_size(function, "Weight vector", beta, N_attributes); check_bounded(function, "Vector of dependent variables", y, 1, N_classes); check_ordered(function, "Cut-points", cuts); check_finite(function, "Final cut-point", cuts[N_classes - 2]); check_finite(function, "First cut-point", cuts[0]); if (size_zero(y, cuts)) return 0; if (!include_summand<propto, T_x_scalar, T_beta_scalar, T_cuts_scalar>::value) return 0; T_partials_return logp(0); const auto& x_val = value_of_rec(x); const auto& beta_val = value_of_rec(beta); const auto& cuts_val = value_of_rec(cuts); const auto& beta_val_vec = as_column_vector_or_scalar(beta_val); const auto& cuts_val_vec = as_column_vector_or_scalar(cuts_val); scalar_seq_view<T_y> y_seq(y); Array<double, Dynamic, 1> cuts_y1(N_instances), cuts_y2(N_instances); for (int i = 0; i < N_instances; i++) { int c = y_seq[i]; if (c != N_classes) { cuts_y1[i] = cuts_val_vec[c - 1]; } else { cuts_y1[i] = INFINITY; } if (c != 1) { cuts_y2[i] = cuts_val_vec[c - 2]; } else { cuts_y2[i] = -INFINITY; } } T_location location = x_val * beta_val_vec; if (!isfinite(sum(location))) { check_finite(function, "Weight vector", beta); check_finite(function, "Matrix of independent variables", x); } Array<double, Dynamic, 1> cut2 = location - cuts_y2; Array<double, Dynamic, 1> cut1 = location - cuts_y1; // Not immediately evaluating next two expressions benefits performance auto m_log_1p_exp_cut1 = (cut1 > 0.0).select(-cut1,0) - (-cut1.abs()).exp().log1p(); auto m_log_1p_exp_m_cut2 = (cut2 <= 0.0).select(cut2,0) - (-cut2.abs()).exp().log1p(); if (is_vector<T_y>::value) { Eigen::Map<const Eigen::Matrix<int, Eigen::Dynamic, 1>> y_vec(&y_seq[0], y_seq.size()); logp = y_vec.cwiseEqual(1) .select(m_log_1p_exp_cut1, y_vec.cwiseEqual(N_classes).select( m_log_1p_exp_m_cut2, m_log_1p_exp_m_cut2 + log1m_exp(cut1 - cut2).array() + m_log_1p_exp_cut1)) .sum(); } else { if (y_seq[0] == 1) { logp = m_log_1p_exp_cut1.sum(); } else if (y_seq[0] == N_classes) { logp = m_log_1p_exp_m_cut2.sum(); } else { logp = (m_log_1p_exp_m_cut2 + log1m_exp(cut1 - cut2).array() + m_log_1p_exp_cut1).sum(); } } operands_and_partials<Matrix<T_x_scalar, T_x_rows, Dynamic>, Eigen::Matrix<T_beta_scalar, Eigen::Dynamic, 1>, Eigen::Matrix<T_cuts_scalar, Eigen::Dynamic,1>> ops_partials(x, beta, cuts); if (!is_constant_struct<T_x_scalar>::value || !is_constant_struct<T_beta_scalar>::value || !is_constant_struct<T_cuts_scalar>::value) { Array<double, Dynamic, 1> d1 = 1 / (1 + exp(cut2)) - 1 / (1 - exp(cuts_y1 - cuts_y2)); Array<double, Dynamic, 1> d2 = 1 / (1 - exp(cuts_y2 - cuts_y1)) - 1 / (1 + exp(cut1)); if (!is_constant_struct<T_x_scalar>::value || !is_constant_struct<T_beta_scalar>::value) { Matrix<double, 1, Dynamic> location_derivative = d1 - d2; if (!is_constant_struct<T_x_scalar>::value) { if(T_x_rows==1){ ops_partials.edge1_.partials_ = beta_val_vec * location_derivative.sum(); } else { ops_partials.edge1_.partials_ = (beta_val_vec * location_derivative).transpose(); } } if (!is_constant_struct<T_beta_scalar>::value) { if(T_x_rows==1){ ops_partials.edge2_.partials_ = (location_derivative * x_val.replicate(N_instances,1)).transpose(); } else { ops_partials.edge2_.partials_ = (location_derivative * x_val).transpose(); } } } if (!is_constant_struct<T_cuts_scalar>::value) { for (int i = 0; i < N_instances; i++) { int c = y_seq[i]; if (c != N_classes) { ops_partials.edge3_.partials_[c - 1] += d2[i]; } if (c != 1) { ops_partials.edge3_.partials_[c - 2] -= d1[i]; } } } } return ops_partials.build(logp); } template <typename T_y, typename T_x_scalar, int T_x_rows, typename T_beta_scalar, typename T_cuts_scalar> typename stan::return_type<T_x_scalar, T_beta_scalar, T_cuts_scalar>::type ordered_logistic_glm_lpmf( const T_y& y, const Eigen::Matrix<T_x_scalar, T_x_rows, Eigen::Dynamic>& x, const Eigen::Matrix<T_beta_scalar, Eigen::Dynamic, 1>& beta, const Eigen::Matrix<T_cuts_scalar, Eigen::Dynamic,1>& cuts) { return ordered_logistic_glm_lpmf<false>(y, x, beta, cuts); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>#include "util/bitmap.h" #include "util/trans-bitmap.h" #include "context-box.h" #include "util/font.h" #include <math.h> #include "util/token.h" static const double FONT_SPACER = 1.3; static const int GradientMax = 50; static Graphics::Color selectedGradientStart(){ static Graphics::Color color = Graphics::makeColor(19, 167, 168); return color; } static Graphics::Color selectedGradientEnd(){ static Graphics::Color color = Graphics::makeColor(27, 237, 239); return color; } using namespace std; namespace Gui{ Effects::Gradient standardGradient(){ Effects::Gradient standard(GradientMax, selectedGradientStart(), selectedGradientEnd()); return standard; } Effects::Gradient modifiedGradient(Graphics::Color low, Graphics::Color high){ Effects::Gradient modified(GradientMax, low, high); return modified; } ListValues::ListValues(): interpolate(true), lowColor(selectedGradientStart()), highColor(selectedGradientEnd()), selectedColor(selectedGradientStart()), selectedAlpha(255), otherColor(Graphics::makeColor(255, 255, 255)), otherAlpha(255), fade(true){ } ListValues::ListValues(const ListValues & copy): interpolate(copy.interpolate), lowColor(copy.lowColor), highColor(copy.highColor), selectedColor(copy.selectedColor), selectedAlpha(copy.selectedAlpha), otherColor(copy.otherColor), otherAlpha(copy.otherAlpha), fade(copy.fade){ } ListValues::~ListValues(){ } const ListValues & ListValues::operator=(const ListValues & copy){ interpolate = copy.interpolate; lowColor = copy.lowColor; highColor = copy.highColor; selectedColor = copy.selectedColor; selectedAlpha = copy.selectedAlpha; otherColor = copy.otherColor; otherAlpha = copy.otherAlpha; fade = copy.fade; return *this; } void ListValues::getValues(const Token * token){ TokenView view = token->view(); while (view.hasMore()){ const Token * token; view >> token; try{ int red = 0, green = 0, blue = 0, alpha = 0; if (token->match("interpolate-selected", interpolate)){ } else if (token->match("color-low", red, green, blue)){ lowColor = Graphics::makeColor(red, green, blue); } else if (token->match("color-high", red, green, blue)){ highColor = Graphics::makeColor(red, green, blue); } else if (token->match("selected-color", red, green, blue)){ selectedColor = Graphics::makeColor(red, green, blue); } else if (token->match("selected-color-alpha", alpha)){ selectedAlpha = alpha; } else if (token->match("other-color", red, green, blue)){ otherColor = Graphics::makeColor(red, green, blue); } else if (token->match("other-color-alpha", alpha)){ otherAlpha = alpha; } else if (token->match("distance-fade", fade)){ } } catch (const TokenException & ex){ // Output something } } } ContextItem::ContextItem(const std::string & name, const ContextBox & parent): text(name), parent(parent){ } ContextItem::~ContextItem(){ } void ContextItem::draw(int x, int y, const Graphics::Bitmap & where, const Font & font, int distance) const { if (distance == 0){ if (parent.getListValues().getInterpolate()){ Graphics::Bitmap::transBlender(0, 0, 0, parent.getFadeAlpha()); font.printf(x, y, parent.getSelectedColor(), where.translucent(), getText(), 0); } else { Graphics::Bitmap::transBlender(0, 0, 0, parent.getListValues().getSelectedAlpha()); font.printf(x, y, parent.getListValues().getSelectedColor(), where.translucent(), getText(), 0); } } else { if (parent.getListValues().getDistanceFade()){ int alpha = parent.getFadeAlpha() - fabs((double) distance) * 35; if (alpha < 0){ alpha = 0; } Graphics::Bitmap::transBlender(0, 0, 0, alpha); font.printf(x, y, parent.getListValues().getOtherColor(), where.translucent(), getText(), 0); } else { Graphics::Bitmap::transBlender(0, 0, 0, parent.getListValues().getOtherAlpha()); font.printf(x, y, parent.getListValues().getOtherColor(), where.translucent(), getText(), 0); } } } void ContextItem::setText(const LanguageString & t){ text = t; } int ContextItem::size(const Font & font) const { return font.textLength(getText().c_str()); } ContextBox::ContextBox(): fadeState(NotActive), list(new ScrollList()), /* fontWidth(0), fontHeight(0), */ fadeSpeed(12), fadeAlpha(0), cursorCenter(0), cursorLocation(0), scrollWait(4), selectedGradient(standardGradient()), useGradient(true), renderOnlyText(false){ } ContextBox::ContextBox( const ContextBox & copy ): fadeState(NotActive), list(new ScrollList()), selectedGradient(standardGradient()), renderOnlyText(false){ this->list = copy.list; // this->context = copy.context; /* this->font = copy.font; this->fontWidth = copy.fontWidth; this->fontHeight = copy.fontHeight; */ this->fadeSpeed = copy.fadeSpeed; this->fadeAlpha = copy.fadeAlpha; this->cursorCenter = copy.cursorCenter; this->cursorLocation = copy.cursorLocation; this->scrollWait = copy.scrollWait; this->useGradient = copy.useGradient; this->renderOnlyText = copy.renderOnlyText; } ContextBox::~ContextBox(){ } ContextBox & ContextBox::operator=( const ContextBox & copy){ this->fadeState = NotActive; this->list = copy.list; // this->context = copy.context; /* this->font = copy.font; this->fontWidth = copy.fontWidth; this->fontHeight = copy.fontHeight; */ this->fadeSpeed = copy.fadeSpeed; this->fadeAlpha = copy.fadeAlpha; this->cursorCenter = copy.cursorCenter; this->cursorLocation = copy.cursorLocation; this->scrollWait = copy.scrollWait; this->useGradient = copy.useGradient; this->renderOnlyText = copy.renderOnlyText; return *this; } void ContextBox::act(const Font & font){ // update board board.act(font); // Calculate text info // calculateText(font); list->act(); // do fade doFade(); // Update gradient selectedGradient.update(); } void ContextBox::render(const Graphics::Bitmap & work){ } void ContextBox::render(const Graphics::Bitmap & work, const Font & font){ if (!renderOnlyText){ board.render(work); } drawText(work, font); } bool ContextBox::next(const Font & font){ if (fadeState == FadeOut){ return false; } list->next(); /* cursorLocation += (int)(font.getHeight()/FONT_SPACER); if (current < context.size()-1){ current++; } else { current = 0; } */ return true; } bool ContextBox::previous(const Font & font){ if (fadeState == FadeOut){ return false; } list->previous(); /* cursorLocation -= (int)(font.getHeight()/FONT_SPACER); if (current > 0){ current--; } else { current = context.size()-1; } */ return true; } Graphics::Color ContextBox::getSelectedColor() const { return useGradient ? selectedGradient.current() : selectedGradientStart(); } void ContextBox::setListValues(const Gui::ListValues & values){ this->values = values; if (useGradient){ selectedGradient = modifiedGradient(values.getLowColor(), values.getHighColor()); } } void ContextBox::adjustLeft(){ } void ContextBox::adjustRight(){ } void ContextBox::open(){ // Set the fade stuff fadeState = FadeIn; //board.position = position; board.location = location; board.transforms = transforms; board.colors = colors; board.open(); fadeAlpha = 0; cursorLocation = 0; } void ContextBox::close(){ fadeState = FadeOut; board.close(); fadeAlpha = 255; cursorLocation = 480; } void ContextBox::doFade(){ switch (fadeState){ case FadeIn: { if (fadeAlpha < 255){ fadeAlpha += (fadeSpeed+2); } if (fadeAlpha >= 255){ fadeAlpha = 255; if (board.isActive()){ fadeState = Active; } } break; } case FadeOut: { if (fadeAlpha > 0){ fadeAlpha -= (fadeSpeed+2); } if (fadeAlpha <= 0){ fadeAlpha = 0; if (!board.isActive()){ fadeState = NotActive; } } break; } case Active: case NotActive: default: break; } } void ContextBox::setList(const std::vector<Util::ReferenceCount<ContextItem> > & list){ this->list->clearItems(); for (vector<Util::ReferenceCount<ContextItem> >::const_iterator it = list.begin(); it != list.end(); it++){ const Util::ReferenceCount<ContextItem> & item = *it; this->list->addItem(item.convert<ScrollItem>()); } } void ContextBox::addItem(const Util::ReferenceCount<ContextItem> & item){ this->list->addItem(item.convert<ScrollItem>()); } void ContextBox::setListType(const ListType & type){ switch (type){ case Normal:{ Util::ReferenceCount<ScrollListInterface> newList = new NormalList(); newList->addItems(list->getItems()); list = newList; break; } case Scroll:{ Util::ReferenceCount<ScrollListInterface> newList = new ScrollList(); newList->addItems(list->getItems()); list = newList; break; } default: break; } } void ContextBox::setListWrap(bool wrap){ list->setWrap(wrap); } void ContextBox::drawText(const Graphics::Bitmap & bmp, const Font & font){ const int x1 = board.getArea().getX()+(int)(board.getTransforms().getRadius()/2); const int y1 = board.getArea().getY()+2;//(board.getArea().radius/2); const int x2 = board.getArea().getX2()-(int)(board.getTransforms().getRadius()/2); const int y2 = board.getArea().getY2()-2;//(board.getArea().radius/2); Graphics::Bitmap area(bmp, x1, y1, x2 - x1, y2 - y1); list->render(area, font); } } <commit_msg>clamp rgba values to 0-255<commit_after>#include "util/bitmap.h" #include "util/trans-bitmap.h" #include "context-box.h" #include "util/font.h" #include <math.h> #include "util/token.h" static const double FONT_SPACER = 1.3; static const int GradientMax = 50; static Graphics::Color selectedGradientStart(){ static Graphics::Color color = Graphics::makeColor(19, 167, 168); return color; } static Graphics::Color selectedGradientEnd(){ static Graphics::Color color = Graphics::makeColor(27, 237, 239); return color; } using namespace std; namespace Gui{ Effects::Gradient standardGradient(){ Effects::Gradient standard(GradientMax, selectedGradientStart(), selectedGradientEnd()); return standard; } Effects::Gradient modifiedGradient(Graphics::Color low, Graphics::Color high){ Effects::Gradient modified(GradientMax, low, high); return modified; } ListValues::ListValues(): interpolate(true), lowColor(selectedGradientStart()), highColor(selectedGradientEnd()), selectedColor(selectedGradientStart()), selectedAlpha(255), otherColor(Graphics::makeColor(255, 255, 255)), otherAlpha(255), fade(true){ } ListValues::ListValues(const ListValues & copy): interpolate(copy.interpolate), lowColor(copy.lowColor), highColor(copy.highColor), selectedColor(copy.selectedColor), selectedAlpha(copy.selectedAlpha), otherColor(copy.otherColor), otherAlpha(copy.otherAlpha), fade(copy.fade){ } ListValues::~ListValues(){ } const ListValues & ListValues::operator=(const ListValues & copy){ interpolate = copy.interpolate; lowColor = copy.lowColor; highColor = copy.highColor; selectedColor = copy.selectedColor; selectedAlpha = copy.selectedAlpha; otherColor = copy.otherColor; otherAlpha = copy.otherAlpha; fade = copy.fade; return *this; } static int clamp(int in){ if (in < 0){ return 0; } if (in > 255){ return 255; } return in; } void ListValues::getValues(const Token * token){ TokenView view = token->view(); while (view.hasMore()){ const Token * token; view >> token; try{ int red = 0, green = 0, blue = 0, alpha = 0; if (token->match("interpolate-selected", interpolate)){ } else if (token->match("color-low", red, green, blue)){ lowColor = Graphics::makeColor(clamp(red), clamp(green), clamp(blue)); } else if (token->match("color-high", red, green, blue)){ highColor = Graphics::makeColor(clamp(red), clamp(green), clamp(blue)); } else if (token->match("selected-color", red, green, blue)){ selectedColor = Graphics::makeColor(clamp(red), clamp(green), clamp(blue)); } else if (token->match("selected-color-alpha", alpha)){ selectedAlpha = clamp(alpha); } else if (token->match("other-color", red, green, blue)){ otherColor = Graphics::makeColor(clamp(red), clamp(green), clamp(blue)); } else if (token->match("other-color-alpha", alpha)){ otherAlpha = clamp(alpha); } else if (token->match("distance-fade", fade)){ } } catch (const TokenException & ex){ // Output something } } } ContextItem::ContextItem(const std::string & name, const ContextBox & parent): text(name), parent(parent){ } ContextItem::~ContextItem(){ } void ContextItem::draw(int x, int y, const Graphics::Bitmap & where, const Font & font, int distance) const { if (distance == 0){ if (parent.getListValues().getInterpolate()){ Graphics::Bitmap::transBlender(0, 0, 0, parent.getFadeAlpha()); font.printf(x, y, parent.getSelectedColor(), where.translucent(), getText(), 0); } else { Graphics::Bitmap::transBlender(0, 0, 0, parent.getListValues().getSelectedAlpha()); font.printf(x, y, parent.getListValues().getSelectedColor(), where.translucent(), getText(), 0); } } else { if (parent.getListValues().getDistanceFade()){ int alpha = parent.getFadeAlpha() - fabs((double) distance) * 35; if (alpha < 0){ alpha = 0; } Graphics::Bitmap::transBlender(0, 0, 0, alpha); font.printf(x, y, parent.getListValues().getOtherColor(), where.translucent(), getText(), 0); } else { Graphics::Bitmap::transBlender(0, 0, 0, parent.getListValues().getOtherAlpha()); font.printf(x, y, parent.getListValues().getOtherColor(), where.translucent(), getText(), 0); } } } void ContextItem::setText(const LanguageString & t){ text = t; } int ContextItem::size(const Font & font) const { return font.textLength(getText().c_str()); } ContextBox::ContextBox(): fadeState(NotActive), list(new ScrollList()), /* fontWidth(0), fontHeight(0), */ fadeSpeed(12), fadeAlpha(0), cursorCenter(0), cursorLocation(0), scrollWait(4), selectedGradient(standardGradient()), useGradient(true), renderOnlyText(false){ } ContextBox::ContextBox( const ContextBox & copy ): fadeState(NotActive), list(new ScrollList()), selectedGradient(standardGradient()), renderOnlyText(false){ this->list = copy.list; // this->context = copy.context; /* this->font = copy.font; this->fontWidth = copy.fontWidth; this->fontHeight = copy.fontHeight; */ this->fadeSpeed = copy.fadeSpeed; this->fadeAlpha = copy.fadeAlpha; this->cursorCenter = copy.cursorCenter; this->cursorLocation = copy.cursorLocation; this->scrollWait = copy.scrollWait; this->useGradient = copy.useGradient; this->renderOnlyText = copy.renderOnlyText; } ContextBox::~ContextBox(){ } ContextBox & ContextBox::operator=( const ContextBox & copy){ this->fadeState = NotActive; this->list = copy.list; // this->context = copy.context; /* this->font = copy.font; this->fontWidth = copy.fontWidth; this->fontHeight = copy.fontHeight; */ this->fadeSpeed = copy.fadeSpeed; this->fadeAlpha = copy.fadeAlpha; this->cursorCenter = copy.cursorCenter; this->cursorLocation = copy.cursorLocation; this->scrollWait = copy.scrollWait; this->useGradient = copy.useGradient; this->renderOnlyText = copy.renderOnlyText; return *this; } void ContextBox::act(const Font & font){ // update board board.act(font); // Calculate text info // calculateText(font); list->act(); // do fade doFade(); // Update gradient selectedGradient.update(); } void ContextBox::render(const Graphics::Bitmap & work){ } void ContextBox::render(const Graphics::Bitmap & work, const Font & font){ if (!renderOnlyText){ board.render(work); } drawText(work, font); } bool ContextBox::next(const Font & font){ if (fadeState == FadeOut){ return false; } list->next(); /* cursorLocation += (int)(font.getHeight()/FONT_SPACER); if (current < context.size()-1){ current++; } else { current = 0; } */ return true; } bool ContextBox::previous(const Font & font){ if (fadeState == FadeOut){ return false; } list->previous(); /* cursorLocation -= (int)(font.getHeight()/FONT_SPACER); if (current > 0){ current--; } else { current = context.size()-1; } */ return true; } Graphics::Color ContextBox::getSelectedColor() const { return useGradient ? selectedGradient.current() : selectedGradientStart(); } void ContextBox::setListValues(const Gui::ListValues & values){ this->values = values; if (useGradient){ selectedGradient = modifiedGradient(values.getLowColor(), values.getHighColor()); } } void ContextBox::adjustLeft(){ } void ContextBox::adjustRight(){ } void ContextBox::open(){ // Set the fade stuff fadeState = FadeIn; //board.position = position; board.location = location; board.transforms = transforms; board.colors = colors; board.open(); fadeAlpha = 0; cursorLocation = 0; } void ContextBox::close(){ fadeState = FadeOut; board.close(); fadeAlpha = 255; cursorLocation = 480; } void ContextBox::doFade(){ switch (fadeState){ case FadeIn: { if (fadeAlpha < 255){ fadeAlpha += (fadeSpeed+2); } if (fadeAlpha >= 255){ fadeAlpha = 255; if (board.isActive()){ fadeState = Active; } } break; } case FadeOut: { if (fadeAlpha > 0){ fadeAlpha -= (fadeSpeed+2); } if (fadeAlpha <= 0){ fadeAlpha = 0; if (!board.isActive()){ fadeState = NotActive; } } break; } case Active: case NotActive: default: break; } } void ContextBox::setList(const std::vector<Util::ReferenceCount<ContextItem> > & list){ this->list->clearItems(); for (vector<Util::ReferenceCount<ContextItem> >::const_iterator it = list.begin(); it != list.end(); it++){ const Util::ReferenceCount<ContextItem> & item = *it; this->list->addItem(item.convert<ScrollItem>()); } } void ContextBox::addItem(const Util::ReferenceCount<ContextItem> & item){ this->list->addItem(item.convert<ScrollItem>()); } void ContextBox::setListType(const ListType & type){ switch (type){ case Normal:{ Util::ReferenceCount<ScrollListInterface> newList = new NormalList(); newList->addItems(list->getItems()); list = newList; break; } case Scroll:{ Util::ReferenceCount<ScrollListInterface> newList = new ScrollList(); newList->addItems(list->getItems()); list = newList; break; } default: break; } } void ContextBox::setListWrap(bool wrap){ list->setWrap(wrap); } void ContextBox::drawText(const Graphics::Bitmap & bmp, const Font & font){ const int x1 = board.getArea().getX()+(int)(board.getTransforms().getRadius()/2); const int y1 = board.getArea().getY()+2;//(board.getArea().radius/2); const int x2 = board.getArea().getX2()-(int)(board.getTransforms().getRadius()/2); const int y2 = board.getArea().getY2()-2;//(board.getArea().radius/2); Graphics::Bitmap area(bmp, x1, y1, x2 - x1, y2 - y1); list->render(area, font); } } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "storagecomponent.h" #include <vespa/storage/storageserver/prioritymapper.h> #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/stllike/asciistream.h> #include <vespa/vdslib/distribution/distribution.h> namespace storage { // Defined in cpp file to allow unique pointers of unknown type in header. StorageComponent::~StorageComponent() { } void StorageComponent::setNodeInfo(vespalib::stringref clusterName, const lib::NodeType& nodeType, uint16_t index) { // Assumed to not be set dynamically. _clusterName = clusterName; _nodeType = &nodeType; _index = index; } void StorageComponent::setDocumentTypeRepo(DocumentTypeRepoSP repo) { std::lock_guard<std::mutex> guard(_lock); _docTypeRepo = repo; } void StorageComponent::setLoadTypes(LoadTypeSetSP loadTypes) { std::lock_guard<std::mutex> guard(_lock); _loadTypes = loadTypes; } void StorageComponent::setPriorityConfig(const PriorityConfig& c) { // Priority mapper is already thread safe. _priorityMapper->setConfig(c); } void StorageComponent::setBucketIdFactory(const document::BucketIdFactory& factory) { // Assumed to not be set dynamically. _bucketIdFactory = factory; } void StorageComponent::setDistribution(DistributionSP distribution) { std::lock_guard<std::mutex> guard(_lock); _distribution = distribution; } void StorageComponent::enableMultipleBucketSpaces(bool value) { std::lock_guard<std::mutex> guard(_lock); _enableMultipleBucketSpaces = value; } void StorageComponent::setNodeStateUpdater(NodeStateUpdater& updater) { std::lock_guard<std::mutex> guard(_lock); if (_nodeStateUpdater != 0) { throw vespalib::IllegalStateException( "Node state updater is already set", VESPA_STRLOC); } _nodeStateUpdater = &updater; } StorageComponent::StorageComponent(StorageComponentRegister& compReg, vespalib::stringref name) : Component(compReg, name), _clusterName(), _nodeType(nullptr), _index(0), _docTypeRepo(), _loadTypes(), _priorityMapper(new PriorityMapper), _bucketIdFactory(), _distribution(), _nodeStateUpdater(nullptr), _lock(), _enableMultipleBucketSpaces(false) { compReg.registerStorageComponent(*this); } NodeStateUpdater& StorageComponent::getStateUpdater() const { std::lock_guard<std::mutex> guard(_lock); if (_nodeStateUpdater == 0) { throw vespalib::IllegalStateException( "Component need node state updater at this time, but it has " "not been initialized.", VESPA_STRLOC); } return *_nodeStateUpdater; } vespalib::string StorageComponent::getIdentity() const { vespalib::asciistream name; name << "storage/cluster." << _clusterName << "/" << _nodeType->serialize() << "/" << _index; return name.str(); } uint8_t StorageComponent::getPriority(const documentapi::LoadType& lt) const { return _priorityMapper->getPriority(lt); } StorageComponent::DocumentTypeRepoSP StorageComponent::getTypeRepo() const { std::lock_guard<std::mutex> guard(_lock); return _docTypeRepo; } StorageComponent::LoadTypeSetSP StorageComponent::getLoadTypes() const { std::lock_guard<std::mutex> guard(_lock); return _loadTypes; } StorageComponent::DistributionSP StorageComponent::getDistribution() const { std::lock_guard<std::mutex> guard(_lock); return _distribution; } bool StorageComponent::enableMultipleBucketSpaces() const { std::lock_guard<std::mutex> guard(_lock); return _enableMultipleBucketSpaces; } } // storage <commit_msg>Utilize class template argument deduction (in C++17).<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "storagecomponent.h" #include <vespa/storage/storageserver/prioritymapper.h> #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/stllike/asciistream.h> #include <vespa/vdslib/distribution/distribution.h> namespace storage { // Defined in cpp file to allow unique pointers of unknown type in header. StorageComponent::~StorageComponent() { } void StorageComponent::setNodeInfo(vespalib::stringref clusterName, const lib::NodeType& nodeType, uint16_t index) { // Assumed to not be set dynamically. _clusterName = clusterName; _nodeType = &nodeType; _index = index; } void StorageComponent::setDocumentTypeRepo(DocumentTypeRepoSP repo) { std::lock_guard guard(_lock); _docTypeRepo = repo; } void StorageComponent::setLoadTypes(LoadTypeSetSP loadTypes) { std::lock_guard guard(_lock); _loadTypes = loadTypes; } void StorageComponent::setPriorityConfig(const PriorityConfig& c) { // Priority mapper is already thread safe. _priorityMapper->setConfig(c); } void StorageComponent::setBucketIdFactory(const document::BucketIdFactory& factory) { // Assumed to not be set dynamically. _bucketIdFactory = factory; } void StorageComponent::setDistribution(DistributionSP distribution) { std::lock_guard guard(_lock); _distribution = distribution; } void StorageComponent::enableMultipleBucketSpaces(bool value) { std::lock_guard guard(_lock); _enableMultipleBucketSpaces = value; } void StorageComponent::setNodeStateUpdater(NodeStateUpdater& updater) { std::lock_guard guard(_lock); if (_nodeStateUpdater != 0) { throw vespalib::IllegalStateException( "Node state updater is already set", VESPA_STRLOC); } _nodeStateUpdater = &updater; } StorageComponent::StorageComponent(StorageComponentRegister& compReg, vespalib::stringref name) : Component(compReg, name), _clusterName(), _nodeType(nullptr), _index(0), _docTypeRepo(), _loadTypes(), _priorityMapper(new PriorityMapper), _bucketIdFactory(), _distribution(), _nodeStateUpdater(nullptr), _lock(), _enableMultipleBucketSpaces(false) { compReg.registerStorageComponent(*this); } NodeStateUpdater& StorageComponent::getStateUpdater() const { std::lock_guard guard(_lock); if (_nodeStateUpdater == 0) { throw vespalib::IllegalStateException( "Component need node state updater at this time, but it has " "not been initialized.", VESPA_STRLOC); } return *_nodeStateUpdater; } vespalib::string StorageComponent::getIdentity() const { vespalib::asciistream name; name << "storage/cluster." << _clusterName << "/" << _nodeType->serialize() << "/" << _index; return name.str(); } uint8_t StorageComponent::getPriority(const documentapi::LoadType& lt) const { return _priorityMapper->getPriority(lt); } StorageComponent::DocumentTypeRepoSP StorageComponent::getTypeRepo() const { std::lock_guard guard(_lock); return _docTypeRepo; } StorageComponent::LoadTypeSetSP StorageComponent::getLoadTypes() const { std::lock_guard guard(_lock); return _loadTypes; } StorageComponent::DistributionSP StorageComponent::getDistribution() const { std::lock_guard guard(_lock); return _distribution; } bool StorageComponent::enableMultipleBucketSpaces() const { std::lock_guard guard(_lock); return _enableMultipleBucketSpaces; } } // storage <|endoftext|>