hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4c9bdb7d213a817e163941e3c9b6f6160e5f693e | 36,132 | cpp | C++ | src/MadHighlightingDialog.cpp | xoxox4dev/madedit | 8e0dd08818e040b099251c1eb8833b836cb36c6e | [
"Ruby"
] | 22 | 2015-06-28T17:48:54.000Z | 2021-04-16T08:47:26.000Z | src/MadHighlightingDialog.cpp | mcanthony/madedit | 8e0dd08818e040b099251c1eb8833b836cb36c6e | [
"Ruby"
] | null | null | null | src/MadHighlightingDialog.cpp | mcanthony/madedit | 8e0dd08818e040b099251c1eb8833b836cb36c6e | [
"Ruby"
] | 12 | 2015-04-25T00:40:35.000Z | 2021-11-11T06:39:48.000Z | ///////////////////////////////////////////////////////////////////////////////
// Name: MadHighlightingDialog.cpp
// Description:
// Author: madedit@gmail.com
// Licence: GPL
///////////////////////////////////////////////////////////////////////////////
#include "MadHighlightingDialog.h"
#include "MadUtils.h"
#include "MadEdit/MadSyntax.h"
#include <wx/colordlg.h>
//Do not add custom headers
//wxDev-C++ designer will remove them
////Header Include Start
////Header Include End
#ifdef _DEBUG
#include <crtdbg.h>
#define new new(_NORMAL_BLOCK ,__FILE__, __LINE__)
#endif
extern void ApplySyntaxAttributes(MadSyntax *syn);
MadHighlightingDialog *g_HighlightingDialog=NULL;
enum
{
kindSysAttr1, kindSysAttr2/*aeActiveLine, aeBookmark*/, kindRange, kindKeyword
};
struct KeywordInfo
{
int kind;
MadAttributes *attr; // for kindSysAttr1, kindSysArrt2, kindKeyword
wxColour *range_bgcolor; // for kindRange
KeywordInfo(): kind(0), attr(0), range_bgcolor(0)
{}
KeywordInfo(int k, MadAttributes *a, wxColour *bg): kind(k), attr(a), range_bgcolor(bg)
{}
};
vector<KeywordInfo> g_KeywordInfoTable;
long g_Index=-1;
MadSyntax *g_Syntax=NULL;
wxColourDialog *g_ColourDialog=NULL;
int g_DefaultFontSize;
wxColour GetColourFromUser(const wxColour& colInit, const wxString& caption)
{
if(g_ColourDialog==NULL)
{
wxColourData *data=new wxColourData;
data->SetChooseFull(true);
if ( colInit.Ok() )
{
data->SetColour((wxColour &)colInit); // const_cast
}
g_ColourDialog = new wxColourDialog(g_HighlightingDialog, data);
}
else
{
if ( colInit.Ok() )
{
g_ColourDialog->GetColourData().SetColour(colInit);
}
}
if (!caption.IsEmpty())
g_ColourDialog->SetTitle(caption);
wxColour colRet;
if ( g_ColourDialog->ShowModal() == wxID_OK )
{
colRet = g_ColourDialog->GetColourData().GetColour();
}
return colRet;
}
void SetItemColour(wxListCtrl *listctrl, long item, const wxColour& fc, const wxColour& bc)
{
wxListItem it;
it.SetId(item);
listctrl->GetItem(it);
it.SetTextColour(fc);
it.SetBackgroundColour(bc);
listctrl->SetItem(it);
}
void SetItemTextColour(wxListCtrl *listctrl, long item, const wxColour& fc)
{
wxListItem it;
it.SetId(item);
listctrl->GetItem(it);
it.SetTextColour(fc);
listctrl->SetItem(it);
}
void SetItemBackgroundColour(wxListCtrl *listctrl, long item, const wxColour& bc)
{
wxListItem it;
it.SetId(item);
listctrl->GetItem(it);
it.SetBackgroundColour(bc);
listctrl->SetItem(it);
}
void SetFontStyle(wxFont &font, MadFontStyles fs)
{
if((fs&fsBold)!=0) font.SetWeight(wxFONTWEIGHT_BOLD);
else font.SetWeight(wxFONTWEIGHT_NORMAL);
if((fs&fsItalic)!=0) font.SetStyle(wxFONTSTYLE_ITALIC);
else font.SetStyle(wxFONTSTYLE_NORMAL);
font.SetUnderlined((fs&fsUnderline)!=0);
}
wxFont GetItemFont(wxListCtrl *listctrl, long item)
{
wxListItem it;
it.SetId(item);
listctrl->GetItem(it);
return it.GetFont();
}
void SetItemFont(wxListCtrl *listctrl, long item, wxFont &font)
{
wxListItem it;
it.SetId(item);
listctrl->GetItem(it);
font.SetPointSize(g_DefaultFontSize);
it.SetFont(font);
listctrl->SetItem(it);
}
//----------------------------------------------------------------------------
// MadHighlightingDialog
//----------------------------------------------------------------------------
//Add Custom Events only in the appropriate block.
//Code added in other places will be removed by wxDev-C++
////Event Table Start
BEGIN_EVENT_TABLE(MadHighlightingDialog,wxDialog)
////Manual Code Start
////Manual Code End
EVT_CLOSE(MadHighlightingDialog::MadHighlightingDialogClose)
EVT_ACTIVATE(MadHighlightingDialog::MadHighlightingDialogActivate)
EVT_BUTTON(ID_WXBUTTONBC,MadHighlightingDialog::WxButtonBCClick)
EVT_LIST_ITEM_SELECTED(ID_WXLISTCTRLBC,MadHighlightingDialog::WxListCtrlBCSelected)
EVT_BUTTON(ID_WXBUTTONFC,MadHighlightingDialog::WxButtonFCClick)
EVT_LIST_ITEM_SELECTED(ID_WXLISTCTRLFC,MadHighlightingDialog::WxListCtrlFCSelected)
EVT_CHECKBOX(ID_WXCHECKBOXUNDERLINE,MadHighlightingDialog::WxCheckBoxUnderlineClick)
EVT_CHECKBOX(ID_WXCHECKBOXITALIC,MadHighlightingDialog::WxCheckBoxItalicClick)
EVT_CHECKBOX(ID_WXCHECKBOXBOLD,MadHighlightingDialog::WxCheckBoxBoldClick)
EVT_LIST_ITEM_SELECTED(ID_WXLISTCTRLKEYWORD,MadHighlightingDialog::WxListCtrlKeywordSelected)
EVT_BUTTON(ID_WXBUTTONDELETE,MadHighlightingDialog::WxButtonDeleteClick)
EVT_BUTTON(ID_WXBUTTONSAVE,MadHighlightingDialog::WxButtonSaveClick)
EVT_BUTTON(ID_WXBUTTONLOAD,MadHighlightingDialog::WxButtonLoadClick)
EVT_LISTBOX(ID_WXLISTBOXSYNTAX,MadHighlightingDialog::WxListBoxSyntaxSelected)
END_EVENT_TABLE()
////Event Table End
MadHighlightingDialog::MadHighlightingDialog(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style)
: wxDialog(parent, id, title, position, size, style)
{
m_Syntax=NULL;
m_InitSetting.Empty();
CreateGUIControls();
}
MadHighlightingDialog::~MadHighlightingDialog() {}
//static int gs_MinX=0;
static void ResizeItem(wxBoxSizer* sizer, wxWindow *item, int ax, int ay)
{
int x, y;
wxString str=item->GetLabel();
item->GetTextExtent(str, &x, &y);
item->SetSize(x+=ax, y+=ay);
sizer->SetItemMinSize(item, x, y);
//wxPoint pos=item->GetPosition();
//if(pos.x + x > gs_MinX) gs_MinX = pos.x + x;
}
void MadHighlightingDialog::CreateGUIControls(void)
{
//do not set FontName, it is not exist on all platforms
#define wxFont(p0,p1,p2,p3,p4,p5) wxFont(wxDEFAULT,wxDEFAULT,p2,p3,p4)
//Do not add custom code here
//wxDev-C++ designer will remove them.
//Add the custom code before or after the blocks
////GUI Items Creation Start
WxBoxSizer1 = new wxBoxSizer(wxHORIZONTAL);
this->SetSizer(WxBoxSizer1);
this->SetAutoLayout(true);
wxArrayString arrayStringFor_WxListBoxSyntax;
WxListBoxSyntax = new wxListBox(this, ID_WXLISTBOXSYNTAX, wxPoint(4, 32), wxSize(145, 380), arrayStringFor_WxListBoxSyntax, wxLB_SINGLE | wxLB_HSCROLL);
WxListBoxSyntax->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer1->Add(WxListBoxSyntax,1,wxEXPAND | wxALL,4);
WxBoxSizer2 = new wxBoxSizer(wxVERTICAL);
WxBoxSizer1->Add(WxBoxSizer2, 3, wxEXPAND | wxALL, 0);
WxBoxSizer3 = new wxBoxSizer(wxVERTICAL);
WxBoxSizer2->Add(WxBoxSizer3, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
WxBoxSizer4 = new wxBoxSizer(wxHORIZONTAL);
WxBoxSizer3->Add(WxBoxSizer4, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 4);
WxStaticText1 = new wxStaticText(this, ID_WXSTATICTEXT1, _("Scheme:"), wxPoint(3, 5), wxDefaultSize, 0, _("WxStaticText1"));
WxStaticText1->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer4->Add(WxStaticText1,0,wxALIGN_CENTER_VERTICAL | wxALL,3);
wxArrayString arrayStringFor_WxComboBoxScheme;
WxComboBoxScheme = new wxComboBox(this, ID_WXCOMBOBOXSCHEME, _(""), wxPoint(55, 3), wxSize(145, 21), arrayStringFor_WxComboBoxScheme, 0, wxDefaultValidator, _("WxComboBoxScheme"));
WxComboBoxScheme->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer4->Add(WxComboBoxScheme,0,wxALIGN_CENTER_VERTICAL | wxALL,3);
WxStaticText2 = new wxStaticText(this, ID_WXSTATICTEXT2, _("You cannot modify the scheme with * sign."), wxPoint(206, 5), wxDefaultSize, 0, _("WxStaticText2"));
WxStaticText2->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer4->Add(WxStaticText2,0,wxALIGN_CENTER_VERTICAL | wxALL,3);
WxBoxSizer6 = new wxBoxSizer(wxHORIZONTAL);
WxBoxSizer3->Add(WxBoxSizer6, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 2);
WxButtonLoad = new wxButton(this, ID_WXBUTTONLOAD, _("&Load"), wxPoint(2, 2), wxSize(75, 25), 0, wxDefaultValidator, _("WxButtonLoad"));
WxButtonLoad->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer6->Add(WxButtonLoad,0,wxALIGN_CENTER_VERTICAL | wxALL,2);
WxButtonSave = new wxButton(this, ID_WXBUTTONSAVE, _("&Save"), wxPoint(81, 2), wxSize(75, 25), 0, wxDefaultValidator, _("WxButtonSave"));
WxButtonSave->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer6->Add(WxButtonSave,0,wxALIGN_CENTER_VERTICAL | wxALL,2);
WxButtonDelete = new wxButton(this, ID_WXBUTTONDELETE, _("&Delete"), wxPoint(160, 2), wxSize(75, 25), 0, wxDefaultValidator, _("WxButtonDelete"));
WxButtonDelete->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer6->Add(WxButtonDelete,0,wxALIGN_CENTER_VERTICAL | wxALL,2);
WxStaticLine1 = new wxStaticLine(this, ID_WXSTATICLINE1, wxPoint(47, 69), wxSize(400, -1), wxLI_HORIZONTAL);
WxStaticLine1->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer2->Add(WxStaticLine1,0,wxEXPAND | wxALL,1);
WxBoxSizer5 = new wxBoxSizer(wxHORIZONTAL);
WxBoxSizer2->Add(WxBoxSizer5, 1, wxEXPAND | wxALL, 0);
WxListCtrlKeyword = new wxListCtrl(this, ID_WXLISTCTRLKEYWORD, wxPoint(2, 35), wxSize(145, 259), wxLC_REPORT | wxLC_NO_HEADER | wxLC_SINGLE_SEL, wxDefaultValidator, _("WxListCtrlKeyword"));
WxListCtrlKeyword->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer5->Add(WxListCtrlKeyword,1,wxEXPAND | wxALL,2);
WxBoxSizer8 = new wxBoxSizer(wxVERTICAL);
WxBoxSizer5->Add(WxBoxSizer8, 2, wxEXPAND | wxALL, 0);
WxBoxSizer9 = new wxBoxSizer(wxVERTICAL);
WxBoxSizer8->Add(WxBoxSizer9, 0, wxALIGN_LEFT | wxALL, 2);
WxCheckBoxBold = new wxCheckBox(this, ID_WXCHECKBOXBOLD, _("Bold"), wxPoint(2, 2), wxSize(97, 17), 0, wxDefaultValidator, _("WxCheckBoxBold"));
WxCheckBoxBold->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer9->Add(WxCheckBoxBold,0,wxALIGN_LEFT | wxALL,2);
WxCheckBoxItalic = new wxCheckBox(this, ID_WXCHECKBOXITALIC, _("Italic"), wxPoint(2, 23), wxSize(97, 17), 0, wxDefaultValidator, _("WxCheckBoxItalic"));
WxCheckBoxItalic->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer9->Add(WxCheckBoxItalic,0,wxALIGN_LEFT | wxALL,2);
WxCheckBoxUnderline = new wxCheckBox(this, ID_WXCHECKBOXUNDERLINE, _("Underline"), wxPoint(2, 44), wxSize(97, 17), 0, wxDefaultValidator, _("WxCheckBoxUnderline"));
WxCheckBoxUnderline->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer9->Add(WxCheckBoxUnderline,0,wxALIGN_LEFT | wxALL,2);
WxStaticLine3 = new wxStaticLine(this, ID_WXSTATICLINE3, wxPoint(47, 68), wxSize(250, -1), wxLI_HORIZONTAL);
WxStaticLine3->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer8->Add(WxStaticLine3,0,wxEXPAND | wxALL,1);
WxBoxSizer10 = new wxBoxSizer(wxHORIZONTAL);
WxBoxSizer8->Add(WxBoxSizer10, 1, wxEXPAND | wxALL, 2);
WxBoxSizer11 = new wxBoxSizer(wxVERTICAL);
WxBoxSizer10->Add(WxBoxSizer11, 1, wxEXPAND | wxALL, 2);
WxStaticText3 = new wxStaticText(this, ID_WXSTATICTEXT3, _("Foreground/Text Color"), wxPoint(26, 3), wxDefaultSize, 0, _("WxStaticText3"));
WxStaticText3->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer11->Add(WxStaticText3,0,wxALIGN_CENTER_HORIZONTAL | wxALL,3);
WxStaticTextFCName = new wxStaticText(this, ID_WXSTATICTEXTFCNAME, _("WxStaticTextFCName"), wxPoint(27, 26), wxDefaultSize, wxALIGN_CENTRE, _("WxStaticTextFCName"));
WxStaticTextFCName->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer11->Add(WxStaticTextFCName,0,wxALIGN_CENTER_HORIZONTAL | wxALL,3);
WxPanelFC = new wxPanel(this, ID_WXPANELFC, wxPoint(39, 48), wxSize(85, 20), wxSIMPLE_BORDER);
WxPanelFC->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer11->Add(WxPanelFC,0,wxALIGN_CENTER_HORIZONTAL | wxALL,2);
WxListCtrlFC = new wxListCtrl(this, ID_WXLISTCTRLFC, wxPoint(2, 72), wxSize(160, 140), wxLC_REPORT | wxLC_NO_HEADER | wxLC_SINGLE_SEL, wxDefaultValidator, _("WxListCtrlFC"));
WxListCtrlFC->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer11->Add(WxListCtrlFC,1,wxEXPAND | wxALL,2);
WxButtonFC = new wxButton(this, ID_WXBUTTONFC, _("Other Color"), wxPoint(37, 216), wxSize(90, 25), 0, wxDefaultValidator, _("WxButtonFC"));
WxButtonFC->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer11->Add(WxButtonFC,0,wxALIGN_CENTER_HORIZONTAL | wxALL,2);
WxStaticLine2 = new wxStaticLine(this, ID_WXSTATICLINE2, wxPoint(169, 25), wxSize(-1, 200), wxLI_VERTICAL);
WxStaticLine2->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer10->Add(WxStaticLine2,0,wxEXPAND | wxALL,1);
WxBoxSizer12 = new wxBoxSizer(wxVERTICAL);
WxBoxSizer10->Add(WxBoxSizer12, 1, wxEXPAND | wxALL, 2);
WxStaticText4 = new wxStaticText(this, ID_WXSTATICTEXT4, _("Background Color"), wxPoint(37, 3), wxDefaultSize, 0, _("WxStaticText4"));
WxStaticText4->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer12->Add(WxStaticText4,0,wxALIGN_CENTER_HORIZONTAL | wxALL,3);
WxStaticTextBCName = new wxStaticText(this, ID_WXSTATICTEXTBCNAME, _("WxStaticTextBCName"), wxPoint(27, 26), wxDefaultSize, wxALIGN_CENTRE, _("WxStaticTextBCName"));
WxStaticTextBCName->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer12->Add(WxStaticTextBCName,0,wxALIGN_CENTER_HORIZONTAL | wxALL,3);
WxPanelBC = new wxPanel(this, ID_WXPANELBC, wxPoint(39, 48), wxSize(85, 20), wxSIMPLE_BORDER);
WxPanelBC->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer12->Add(WxPanelBC,0,wxALIGN_CENTER_HORIZONTAL | wxALL,2);
WxListCtrlBC = new wxListCtrl(this, ID_WXLISTCTRLBC, wxPoint(2, 72), wxSize(160, 140), wxLC_REPORT | wxLC_NO_HEADER | wxLC_SINGLE_SEL, wxDefaultValidator, _("WxListCtrlBC"));
WxListCtrlBC->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer12->Add(WxListCtrlBC,1,wxEXPAND | wxALL,2);
WxButtonBC = new wxButton(this, ID_WXBUTTONBC, _("Other Color"), wxPoint(37, 216), wxSize(90, 28), 0, wxDefaultValidator, _("WxButtonBC"));
WxButtonBC->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer12->Add(WxButtonBC,0,wxALIGN_CENTER_HORIZONTAL | wxALL,2);
WxBoxSizer7 = new wxBoxSizer(wxHORIZONTAL);
WxBoxSizer2->Add(WxBoxSizer7, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 2);
WxButtonClose = new wxButton(this, wxID_OK, _("&OK"), wxPoint(5, 3), wxSize(90, 27), 0, wxDefaultValidator, _("WxButtonClose"));
WxButtonClose->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer7->Add(WxButtonClose,0,wxALIGN_CENTER_VERTICAL | wxALL,3);
WxButtonCancel = new wxButton(this, wxID_CANCEL, _("&Cancel"), wxPoint(99, 3), wxSize(90, 27), 0, wxDefaultValidator, _("WxButtonCancel"));
WxButtonCancel->SetFont(wxFont(8, wxSWISS, wxNORMAL, wxNORMAL, false, _("MS Sans Serif")));
WxBoxSizer7->Add(WxButtonCancel,0,wxALIGN_CENTER_VERTICAL | wxALL,3);
SetTitle(_("Syntax Highlighting Settings"));
SetIcon(wxNullIcon);
GetSizer()->Layout();
GetSizer()->Fit(this);
GetSizer()->SetSizeHints(this);
Center();
////GUI Items Creation End
//restore wxFont
#undef wxFont
ResizeItem(WxBoxSizer4, WxStaticText1, 2, 2);
ResizeItem(WxBoxSizer4, WxStaticText2, 2, 2);
ResizeItem(WxBoxSizer9, WxCheckBoxBold, 25, 4);
ResizeItem(WxBoxSizer9, WxCheckBoxItalic, 25, 4);
ResizeItem(WxBoxSizer9, WxCheckBoxUnderline, 25, 4);
ResizeItem(WxBoxSizer11, WxStaticText3, 2, 2);
ResizeItem(WxBoxSizer11, WxStaticTextFCName, 2, 2);
ResizeItem(WxBoxSizer12, WxStaticText4, 2, 2);
ResizeItem(WxBoxSizer12, WxStaticTextBCName, 2, 2);
{ // build scheme list
size_t cnt=MadSyntax::GetSchemeCount();
for(size_t i=0;i<cnt;i++)
{
wxString name=MadSyntax::GetSchemeName(i);
WxComboBoxScheme->Append(name);
if(i==0) WxComboBoxScheme->SetValue(name);
}
}
{ // build syntax type list
size_t cnt=MadSyntax::GetSyntaxCount();
for(size_t i=0;i<cnt;i++)
{
wxString title=MadSyntax::GetSyntaxTitle(i);
WxListBoxSyntax->Append(title);
}
}
g_DefaultFontSize=WxListCtrlKeyword->GetFont().GetPointSize();
WxListCtrlKeyword->InsertColumn(0, wxT("first column"));
// build color list
WxListCtrlFC->Hide();
WxListCtrlBC->Hide();
WxListCtrlFC->InsertColumn(0, wxT("first column"));
WxListCtrlBC->InsertColumn(0, wxT("first column"));
wxListItem it;
it.SetColumn(0);
it.SetId(0);
it.SetText(wxT("(Automatic)"));
it.SetTextColour(wxT("Red"));
WxListCtrlFC->InsertItem(it);
WxListCtrlBC->InsertItem(it);
HtmlColor *hc=HtmlColorTable;
for(int i=0; i<HtmlColorTableCount; ++i, ++hc)
{
it.SetText(hc->name);
it.SetId(i+1);
wxColor c(wxColor(hc->red, hc->green, hc->blue));
it.SetTextColour(c);
it.SetBackgroundColour(wxNullColour);
WxListCtrlFC->InsertItem(it);
if((hc->red+hc->green+hc->blue)/3 >= 128)
it.SetTextColour(*wxBLACK);
else
it.SetTextColour(*wxWHITE);
it.SetBackgroundColour(c);
WxListCtrlBC->InsertItem(it);
}
WxListCtrlFC->SetColumnWidth( 0, wxLIST_AUTOSIZE );
WxListCtrlBC->SetColumnWidth( 0, wxLIST_AUTOSIZE );
WxListCtrlFC->Show();
WxListCtrlBC->Show();
}
void MadHighlightingDialog::MadHighlightingDialogClose(wxCloseEvent& event)
{
if(event.CanVeto())
{
event.Veto();
Show(false);
return;
}
FreeSyntax(false);
g_HighlightingDialog=NULL;
if(g_ColourDialog) delete g_ColourDialog;
Destroy();
}
/*
* WxListBoxSyntaxSelected
*/
void MadHighlightingDialog::WxListBoxSyntaxSelected(wxCommandEvent& event)
{
wxString title=WxListBoxSyntax->GetString(event.GetSelection());
g_Syntax=GetSyntax(title);
// build keyword list
WxListCtrlKeyword->Freeze();
WxListCtrlKeyword->DeleteAllItems();
g_KeywordInfoTable.clear();
int index=0;
// system attributes
for(int ae=aeText; ae<aeNone; ae++)
{
long item = WxListCtrlKeyword->InsertItem(index++, MadSyntax::GetAttributeName((MadAttributeElement)ae));
MadAttributes *attr = g_Syntax->GetAttributes((MadAttributeElement)ae);
int kind=kindSysAttr1;
if(ae==aeActiveLine || ae==aeBookmark) kind=kindSysAttr2;
g_KeywordInfoTable.push_back(KeywordInfo(kind, attr, NULL));
if(ae==aeText)
{
WxListCtrlKeyword->SetBackgroundColour(attr->bgcolor);
}
SetItemColour(WxListCtrlKeyword, item, attr->color, attr->bgcolor);
wxFont font=GetItemFont(WxListCtrlKeyword, item);
SetFontStyle(font, attr->style);
SetItemFont(WxListCtrlKeyword, item, font);
}
// custom ranges
size_t i;
for(i=0; i<g_Syntax->m_CustomRange.size(); ++i)
{
wxString text;
text.Printf(wxT("Range %s %s"), g_Syntax->m_CustomRange[i].begin.c_str(), g_Syntax->m_CustomRange[i].end.c_str());
long item = WxListCtrlKeyword->InsertItem(index++, text);
wxColour *bg = &(g_Syntax->m_CustomRange[i].bgcolor);
g_KeywordInfoTable.push_back( KeywordInfo(kindRange, NULL, bg) );
SetItemColour(WxListCtrlKeyword, item, g_KeywordInfoTable[0].attr->color, *bg);
}
// custom keywords
for(i=0; i<g_Syntax->m_CustomKeyword.size(); ++i)
{
long item = WxListCtrlKeyword->InsertItem(index++, g_Syntax->m_CustomKeyword[i].m_Name);
MadAttributes *attr = &(g_Syntax->m_CustomKeyword[i].m_Attr);
g_KeywordInfoTable.push_back(KeywordInfo(kindKeyword, attr, NULL));
SetItemColour(WxListCtrlKeyword, item, attr->color, attr->bgcolor);
wxFont font=GetItemFont(WxListCtrlKeyword, item);
SetFontStyle(font, attr->style);
SetItemFont(WxListCtrlKeyword, item, font);
}
WxListCtrlKeyword->SetColumnWidth( 0, WxListCtrlKeyword->GetClientSize().x - 4);
WxListCtrlKeyword->Thaw();
g_Index=-1;
wxListEvent e;
e.m_itemIndex=0;
WxListCtrlKeywordSelected(e);
}
void MadHighlightingDialog::SetPanelFC(const wxColor &color)
{
if(color==wxNullColour)
{
WxStaticTextFCName->SetLabel(wxT("(Automatic)"));
WxPanelFC->SetBackgroundColour(WxListCtrlFC->GetItemTextColour(0));
WxPanelFC->ClearBackground();
}
else
{
wxString cname=wxTheColourDatabase->FindName(color);
if(cname.IsEmpty())
{
cname.Printf(wxT("#%02X%02X%02X"), color.Red(), color.Green(), color.Blue());
}
WxStaticTextFCName->SetLabel(cname);
WxPanelFC->SetBackgroundColour(color);
WxPanelFC->ClearBackground();
}
}
void MadHighlightingDialog::SetPanelBC(const wxColor &color)
{
if(color==wxNullColour)
{
WxStaticTextBCName->SetLabel(wxT("(Automatic)"));
WxPanelBC->SetBackgroundColour(WxListCtrlBC->GetItemBackgroundColour(0));
WxPanelBC->ClearBackground();
}
else
{
wxString cname=wxTheColourDatabase->FindName(color);
if(cname.IsEmpty())
{
cname.Printf(wxT("#%02X%02X%02X"), color.Red(), color.Green(), color.Blue());
}
WxStaticTextBCName->SetLabel(cname);
WxPanelBC->SetBackgroundColour(color);
WxPanelBC->ClearBackground();
}
}
/*
* WxListCtrlKeywordSelected
*/
void MadHighlightingDialog::WxListCtrlKeywordSelected(wxListEvent& event)
{
long oldIndex=g_Index;
g_Index = event.m_itemIndex;
WxListCtrlKeyword->Freeze();
WxListCtrlFC->Freeze();
if(oldIndex!=g_Index)
{
wxString str;
if(oldIndex>=0)
{
str = WxListCtrlKeyword->GetItemText(oldIndex);
if(str[0]==wxT('*'))
{
WxListCtrlKeyword->SetItemText(oldIndex, str.Right(str.Len()-1));
}
}
str = WxListCtrlKeyword->GetItemText(g_Index);
WxListCtrlKeyword->SetItemText(g_Index, wxString(wxT('*'))+str);
WxListCtrlKeyword->SetColumnWidth(0, WxListCtrlKeyword->GetClientSize().x - 4);
}
KeywordInfo &kinfo=g_KeywordInfoTable[g_Index];
if(g_Index==0) // set (Automatic) colors
{
SetItemTextColour(WxListCtrlFC, 0, kinfo.attr->color);
int c = (kinfo.attr->bgcolor.Red()+kinfo.attr->bgcolor.Green()+kinfo.attr->bgcolor.Blue())/3;
if(c >= 128)
{
SetItemColour(WxListCtrlBC, 0, *wxBLACK, kinfo.attr->bgcolor);
}
else
{
SetItemColour(WxListCtrlBC, 0, *wxWHITE, kinfo.attr->bgcolor);
}
}
wxColour bgc;
switch(kinfo.kind)
{
case kindSysAttr1:
case kindKeyword:
WxCheckBoxBold->Enable();
WxCheckBoxItalic->Enable();
WxCheckBoxUnderline->Enable();
WxCheckBoxBold->SetValue((kinfo.attr->style&fsBold)!=0);
WxCheckBoxItalic->SetValue((kinfo.attr->style&fsItalic)!=0);
WxCheckBoxUnderline->SetValue((kinfo.attr->style&fsUnderline)!=0);
SetPanelFC(kinfo.attr->color);
SetPanelBC(kinfo.attr->bgcolor);
WxListCtrlFC->Enable();
WxButtonFC->Enable();
WxListCtrlBC->Enable();
WxButtonBC->Enable();
bgc=kinfo.attr->bgcolor;
break;
case kindSysAttr2:
WxCheckBoxBold->SetValue(false);
WxCheckBoxItalic->SetValue(false);
WxCheckBoxUnderline->SetValue(false);
WxCheckBoxBold->Disable();
WxCheckBoxItalic->Disable();
WxCheckBoxUnderline->Disable();
SetPanelFC(kinfo.attr->color);
SetPanelBC(wxNullColour);
WxListCtrlFC->Enable();
WxButtonFC->Enable();
WxListCtrlBC->Disable();
WxButtonBC->Disable();
bgc==wxNullColour;
break;
case kindRange:
WxCheckBoxBold->SetValue(false);
WxCheckBoxItalic->SetValue(false);
WxCheckBoxUnderline->SetValue(false);
WxCheckBoxBold->Disable();
WxCheckBoxItalic->Disable();
WxCheckBoxUnderline->Disable();
SetPanelFC(wxNullColour);
SetPanelBC(*kinfo.range_bgcolor);
WxListCtrlFC->Disable();
WxButtonFC->Disable();
WxListCtrlBC->Enable();
WxButtonBC->Enable();
bgc=*kinfo.range_bgcolor;
break;
}
if(bgc==wxNullColour) bgc=g_KeywordInfoTable[0].attr->bgcolor;
WxListCtrlFC->SetBackgroundColour(bgc);
SetItemBackgroundColour(WxListCtrlFC, 0, bgc);
this->Layout();
WxListCtrlKeyword->SetItemState(event.m_itemIndex, 0, wxLIST_STATE_SELECTED);
WxListCtrlKeyword->Thaw();
WxListCtrlFC->Thaw();
}
/*
* WxListCtrlFCSelected
*/
void MadHighlightingDialog::WxListCtrlFCSelected(wxListEvent& event)
{
wxString colorname=WxListCtrlFC->GetItemText(event.m_itemIndex);
wxColor color=WxListCtrlFC->GetItemTextColour(event.m_itemIndex);
WxStaticTextFCName->SetLabel(colorname);
this->Layout();
WxPanelFC->SetBackgroundColour(color);
WxPanelFC->ClearBackground();
SetAttrFC(color, colorname);
SetToModifiedSyntax(g_Syntax);
WxListCtrlFC->SetItemState(event.m_itemIndex, 0, wxLIST_STATE_SELECTED);
}
/*
* WxListCtrlBCSelected
*/
void MadHighlightingDialog::WxListCtrlBCSelected(wxListEvent& event)
{
wxString colorname=WxListCtrlBC->GetItemText(event.m_itemIndex);
wxColor color=WxListCtrlBC->GetItemBackgroundColour(event.m_itemIndex);
WxStaticTextBCName->SetLabel(colorname);
this->Layout();
WxPanelBC->SetBackgroundColour(color);
WxPanelBC->ClearBackground();
SetAttrBC(color, colorname);
SetToModifiedSyntax(g_Syntax);
WxListCtrlBC->SetItemState(event.m_itemIndex, 0, wxLIST_STATE_SELECTED);
}
/*
* WxCheckBoxBoldClick
*/
void MadHighlightingDialog::WxCheckBoxBoldClick(wxCommandEvent& event)
{
wxFont font=GetItemFont(WxListCtrlKeyword, g_Index);
if(event.IsChecked())
{
g_KeywordInfoTable[g_Index].attr->style |= fsBold;
}
else
{
g_KeywordInfoTable[g_Index].attr->style &= (~fsBold);
}
SetFontStyle(font, g_KeywordInfoTable[g_Index].attr->style);
SetItemFont(WxListCtrlKeyword, g_Index, font);
WxListCtrlKeyword->SetColumnWidth(0, WxListCtrlKeyword->GetClientSize().x - 4);
SetToModifiedSyntax(g_Syntax);
}
/*
* WxCheckBoxItalicClick
*/
void MadHighlightingDialog::WxCheckBoxItalicClick(wxCommandEvent& event)
{
wxFont font=GetItemFont(WxListCtrlKeyword, g_Index);
if(event.IsChecked())
{
g_KeywordInfoTable[g_Index].attr->style |= fsItalic;
}
else
{
g_KeywordInfoTable[g_Index].attr->style &= (~fsItalic);
}
SetFontStyle(font, g_KeywordInfoTable[g_Index].attr->style);
SetItemFont(WxListCtrlKeyword, g_Index, font);
WxListCtrlKeyword->SetColumnWidth(0, WxListCtrlKeyword->GetClientSize().x - 4);
SetToModifiedSyntax(g_Syntax);
}
/*
* WxCheckBoxUnderlineClick
*/
void MadHighlightingDialog::WxCheckBoxUnderlineClick(wxCommandEvent& event)
{
wxFont font=GetItemFont(WxListCtrlKeyword, g_Index);
if(event.IsChecked())
{
g_KeywordInfoTable[g_Index].attr->style |= fsUnderline;
}
else
{
g_KeywordInfoTable[g_Index].attr->style &= (~fsUnderline);
}
SetFontStyle(font, g_KeywordInfoTable[g_Index].attr->style);
SetItemFont(WxListCtrlKeyword, g_Index, font);
WxListCtrlKeyword->SetColumnWidth(0, WxListCtrlKeyword->GetClientSize().x - 4);
SetToModifiedSyntax(g_Syntax);
}
/*
* WxButtonFCClick
*/
void MadHighlightingDialog::WxButtonFCClick(wxCommandEvent& event)
{
wxColour color=GetColourFromUser(WxListCtrlKeyword->GetItemTextColour(g_Index), WxStaticText3->GetLabel());
if(color.Ok())
{
SetPanelFC(color);
this->Layout();
wxString colorname=WxStaticTextFCName->GetLabel();
SetAttrFC(color, colorname);
SetToModifiedSyntax(g_Syntax);
}
}
/*
* WxButtonBCClick
*/
void MadHighlightingDialog::WxButtonBCClick(wxCommandEvent& event)
{
wxColour color=GetColourFromUser(WxPanelBC->GetBackgroundColour(), WxStaticText4->GetLabel());
if(color.Ok())
{
SetPanelBC(color);
this->Layout();
wxString colorname=WxStaticTextBCName->GetLabel();
SetAttrBC(color, colorname);
SetToModifiedSyntax(g_Syntax);
}
}
/*
* MadHighlightingDialogActivate
*/
void MadHighlightingDialog::MadHighlightingDialogActivate(wxActivateEvent& event)
{
if(!m_InitSetting.IsEmpty() && event.GetActive())
{
g_Index=-1;
int i=WxListBoxSyntax->FindString(m_InitSetting);
if(i==wxNOT_FOUND)
{
i=WxListBoxSyntax->GetSelection();
if(i==wxNOT_FOUND) i=0;
}
WxListBoxSyntax->SetSelection(i);
wxCommandEvent e;
e.SetInt(i);
WxListBoxSyntaxSelected(e);
m_InitSetting.Empty();
if(FindFocus()==NULL)
{
WxButtonCancel->SetFocus();
}
}
}
MadSyntax *MadHighlightingDialog::GetSyntax(const wxString &title)
{
if(m_Syntax && m_Syntax->m_Title.CmpNoCase(title)==0)
return m_Syntax;
for(size_t i=0; i<m_ModifiedSyntax.size(); ++i)
{
if(m_ModifiedSyntax[i]->m_Title.CmpNoCase(title)==0)
return m_ModifiedSyntax[i];
}
if(m_Syntax) delete m_Syntax;
m_Syntax=MadSyntax::GetSyntaxByTitle(title);
return m_Syntax;
}
void MadHighlightingDialog::SetToModifiedSyntax(MadSyntax *syn)
{
if(syn==m_Syntax)
{
m_ModifiedSyntax.push_back(syn);
m_Syntax=NULL;
}
ApplySyntaxAttributes(syn);// apply syntax attributes to editor
}
void MadHighlightingDialog::SetAttrFC(const wxColor &color, const wxString &colorname)
{
KeywordInfo &kinfo=g_KeywordInfoTable[g_Index];
if(g_Index==0)
{
SetItemTextColour(WxListCtrlFC, 0, color);
kinfo.attr->color=color;
}
else
{
wxASSERT(kinfo.kind!=kindRange);
if(colorname==wxT("(Automatic)"))
{
kinfo.attr->color=wxNullColour;
}
else
{
kinfo.attr->color=color;
}
}
RepaintKeyword();
}
void MadHighlightingDialog::SetAttrBC(const wxColor &color, const wxString &colorname)
{
KeywordInfo &kinfo=g_KeywordInfoTable[g_Index];
if(g_Index==0)
{
SetItemBackgroundColour(WxListCtrlBC, 0, color);
WxListCtrlKeyword->SetBackgroundColour(color);
kinfo.attr->bgcolor=color;
}
else
{
wxASSERT(kinfo.kind!=kindSysAttr2);
switch(kinfo.kind)
{
case kindSysAttr1:
case kindKeyword:
if(colorname==wxT("(Automatic)")) kinfo.attr->bgcolor=wxNullColour;
else kinfo.attr->bgcolor=color;
break;
case kindRange:
if(colorname==wxT("(Automatic)")) *kinfo.range_bgcolor=wxNullColour;
else *kinfo.range_bgcolor=color;
break;
}
}
RepaintKeyword();
SetItemBackgroundColour(WxListCtrlFC, 0, color);
WxListCtrlFC->SetBackgroundColour(color);
WxListCtrlFC->Refresh();
}
void MadHighlightingDialog::RepaintKeyword()
{
vector<KeywordInfo>::iterator it=g_KeywordInfoTable.begin();
vector<KeywordInfo>::iterator itend=g_KeywordInfoTable.end();
long idx=0;
wxFont font;
wxColour &fc0=it->attr->color;
wxColour &bc0=it->attr->bgcolor;
wxColour fc, bc;
WxListCtrlKeyword->Freeze();
do
{
switch(it->kind)
{
case kindSysAttr1:
case kindSysAttr2:
case kindKeyword:
fc=it->attr->color;
bc=it->attr->bgcolor;
font=GetItemFont(WxListCtrlKeyword, idx);
SetFontStyle(font, it->attr->style);
SetItemFont(WxListCtrlKeyword, idx, font);
break;
case kindRange:
fc=wxNullColour;
bc=*it->range_bgcolor;
break;
}
if(fc==wxNullColour) fc=fc0;
if(bc==wxNullColour) bc=bc0;
SetItemColour(WxListCtrlKeyword, idx, fc, bc);
++idx;
}
while(++it != itend);
WxListCtrlKeyword->SetColumnWidth(0, WxListCtrlKeyword->GetClientSize().x - 4);
WxListCtrlKeyword->Thaw();
}
void MadHighlightingDialog::FreeSyntax(bool restore)
{
if(restore) // restore the original syntax
{
for(size_t i=0; i<m_ModifiedSyntax.size(); ++i)
{
MadSyntax *syn=MadSyntax::GetSyntaxByTitle(m_ModifiedSyntax[i]->m_Title);
ApplySyntaxAttributes(syn);
delete syn;
}
}
else // write the modified syntax back
{
for(size_t i=0; i<m_ModifiedSyntax.size(); ++i)
{
m_ModifiedSyntax[i]->SaveAttributes();
}
}
if(m_Syntax)
{
delete m_Syntax;
m_Syntax=NULL;
}
for(size_t i=0; i<m_ModifiedSyntax.size(); ++i)
{
delete m_ModifiedSyntax[i];
}
m_ModifiedSyntax.clear();
}
/*
* WxButtonLoadClick
*/
void MadHighlightingDialog::WxButtonLoadClick(wxCommandEvent& event)
{
if(MadSyntax::LoadScheme(WxComboBoxScheme->GetValue(), g_Syntax))
{
WxListCtrlKeyword->SetBackgroundColour(g_KeywordInfoTable[0].attr->bgcolor);
RepaintKeyword();
wxListEvent e;
e.m_itemIndex=g_Index;
WxListCtrlKeywordSelected(e);
SetToModifiedSyntax(g_Syntax);
}
else
{
wxMessageBox(_("Cannot load this scheme."), wxT("MadEdit"), wxICON_WARNING|wxOK);
}
}
/*
* WxButtonSaveClick
*/
void MadHighlightingDialog::WxButtonSaveClick(wxCommandEvent& event)
{
wxString schname = WxComboBoxScheme->GetValue();
if(MadSyntax::SaveScheme(schname, g_Syntax))
{
WxComboBoxScheme->Clear();
size_t cnt=MadSyntax::GetSchemeCount();
for(size_t i=0;i<cnt;i++)
{
wxString name=MadSyntax::GetSchemeName(i);
WxComboBoxScheme->Append(name);
}
WxComboBoxScheme->SetValue(schname);
}
else
{
wxMessageBox(_("Cannot save to the scheme."), wxT("MadEdit"), wxICON_WARNING|wxOK);
}
}
/*
* WxButtonDeleteClick
*/
void MadHighlightingDialog::WxButtonDeleteClick(wxCommandEvent& event)
{
if(MadSyntax::DeleteScheme(WxComboBoxScheme->GetValue()))
{
WxComboBoxScheme->Clear();
size_t cnt=MadSyntax::GetSchemeCount();
for(size_t i=0;i<cnt;i++)
{
wxString name=MadSyntax::GetSchemeName(i);
WxComboBoxScheme->Append(name);
if(i==0) WxComboBoxScheme->SetValue(name);
}
}
else
{
wxMessageBox(_("Cannot delete this scheme."), wxT("MadEdit"), wxICON_WARNING|wxOK);
}
}
| 34.842816 | 191 | 0.659914 | xoxox4dev |
4c9c1d2d98dd73aafb672ceac3abece6bf228ddf | 5,061 | cpp | C++ | src/wmecore/TheoraAudioBridge.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | src/wmecore/TheoraAudioBridge.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | src/wmecore/TheoraAudioBridge.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | // This file is part of Wintermute Engine
// For conditions of distribution and use, see copyright notice in license.txt
#include "Wme.h"
#include "TheoraAudioBridge.h"
#include "TheoraVideoClip.h"
#include "Game.h"
namespace Wme
{
//////////////////////////////////////////////////////////////////////////
TheoraAudioBridge::TheoraAudioBridge(TheoraVideoClip* owner, int nChannels, int freq) : TheoraAudioInterface(owner, nChannels, freq), TheoraTimer()
{
m_MaxBuffSize = freq * mNumChannels * 2;
m_BuffSize = 0;
m_NumProcessedSamples = 0;
m_TimeOffset = 0;
m_TempBuffer = new short[m_MaxBuffSize];
m_Source = AL_NONE;
alGenSources(1, &m_Source);
owner->setTimer(this);
m_NumPlayedSamples = 0;
}
//////////////////////////////////////////////////////////////////////////
TheoraAudioBridge::~TheoraAudioBridge()
{
}
//////////////////////////////////////////////////////////////////////////
void TheoraAudioBridge::destroy()
{
SoundManager* soundMgr = Game::GetInstance()->GetSoundMgr();
if (m_Source)
{
alSourceStop(m_Source);
soundMgr->ReclaimSoundSource(m_Source);
m_Source = AL_NONE;
}
while (!m_BufferQueue.empty())
{
OpenAL_Buffer buff = m_BufferQueue.front();
m_BufferQueue.pop();
alDeleteBuffers(1, &buff.id);
}
if (m_TempBuffer)
{
SAFE_DELETE_ARRAY(m_TempBuffer);
}
}
//////////////////////////////////////////////////////////////////////////
void TheoraAudioBridge::insertData(float** data, int nSamples)
{
for (int i = 0; i < nSamples; i++)
{
if (m_BuffSize < m_MaxBuffSize)
{
m_TempBuffer[m_BuffSize++] = float2short(data[0][i]);
if (mNumChannels == 2)
m_TempBuffer[m_BuffSize++] = float2short(data[1][i]);
}
if (m_BuffSize == mFreq * mNumChannels / 4)
{
OpenAL_Buffer buff;
alGenBuffers(1, &buff.id);
ALuint format = (mNumChannels == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
alBufferData(buff.id, format, m_TempBuffer, m_BuffSize * 2, mFreq);
alSourceQueueBuffers(m_Source, 1, &buff.id);
buff.nSamples = m_BuffSize / mNumChannels;
m_NumProcessedSamples += m_BuffSize / mNumChannels;
m_BufferQueue.push(buff);
m_BuffSize = 0;
int state;
alGetSourcei(m_Source, AL_SOURCE_STATE, &state);
if (state != AL_PLAYING)
{
alSourcef(m_Source, AL_SAMPLE_OFFSET, (float)m_NumProcessedSamples - mFreq / 4);
alSourcePlay(m_Source);
}
}
}
}
//////////////////////////////////////////////////////////////////////////
void TheoraAudioBridge::update(float time_increase)
{
int i, state, nProcessed;
OpenAL_Buffer buff;
// process played buffers
alGetSourcei(m_Source, AL_BUFFERS_PROCESSED, &nProcessed);
for (i = 0; i < nProcessed; i++)
{
buff = m_BufferQueue.front();
m_BufferQueue.pop();
m_NumPlayedSamples += buff.nSamples;
alSourceUnqueueBuffers(m_Source, 1, &buff.id);
alDeleteBuffers(1, &buff.id);
}
// control playback and return time position
alGetSourcei(m_Source, AL_SOURCE_STATE, &state);
if (state == AL_PLAYING)
{
alGetSourcef(m_Source, AL_SEC_OFFSET, &mTime);
mTime += (float)m_NumPlayedSamples / mFreq;
m_TimeOffset=0;
}
else
{
mTime = (float)m_NumProcessedSamples / mFreq + m_TimeOffset;
m_TimeOffset += time_increase;
}
float duration = mClip->getDuration();
if (mTime > duration) mTime = duration;
}
//////////////////////////////////////////////////////////////////////////
void TheoraAudioBridge::pause()
{
alSourcePause(m_Source);
TheoraTimer::pause();
}
//////////////////////////////////////////////////////////////////////////
void TheoraAudioBridge::play()
{
alSourcePlay(m_Source);
TheoraTimer::play();
}
//////////////////////////////////////////////////////////////////////////
void TheoraAudioBridge::seek(float time)
{
OpenAL_Buffer buff;
alSourceStop(m_Source);
while (!m_BufferQueue.empty())
{
buff = m_BufferQueue.front();
m_BufferQueue.pop();
alSourceUnqueueBuffers(m_Source, 1, &buff.id);
alDeleteBuffers(1, &buff.id);
}
m_BuffSize = 0;
m_TimeOffset = 0;
m_NumPlayedSamples = m_NumProcessedSamples = (int)time*mFreq;
}
//////////////////////////////////////////////////////////////////////////
short TheoraAudioBridge::float2short(float f)
{
if (f > 1) f = 1;
else if (f < -1) f = -1;
return (short) (f * 32767);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
TheoraAudioBridgeFactory::TheoraAudioBridgeFactory()
{
}
//////////////////////////////////////////////////////////////////////////
TheoraAudioBridgeFactory::~TheoraAudioBridgeFactory()
{
}
//////////////////////////////////////////////////////////////////////////
TheoraAudioBridge* TheoraAudioBridgeFactory::createInstance(TheoraVideoClip* owner, int nChannels, int freq)
{
return new TheoraAudioBridge(owner, nChannels, freq);
}
} // namespace Wme
| 25.560606 | 148 | 0.548903 | retrowork |
4c9eb433599412fac2449ccf30b8bcc427148bef | 1,493 | hpp | C++ | sdk/input.hpp | amizu03/csgo_sdk | 3c229bd592f4463b4a098eb02ee9a1d83cf36f77 | [
"MIT"
] | null | null | null | sdk/input.hpp | amizu03/csgo_sdk | 3c229bd592f4463b4a098eb02ee9a1d83cf36f77 | [
"MIT"
] | null | null | null | sdk/input.hpp | amizu03/csgo_sdk | 3c229bd592f4463b4a098eb02ee9a1d83cf36f77 | [
"MIT"
] | 1 | 2020-03-31T07:06:08.000Z | 2020-03-31T07:06:08.000Z | #pragma once
#include "../utils/vfunc.hpp"
#include "../utils/padding.hpp"
#include "vec3.hpp"
#include "ucmd.hpp"
class c_input {
public:
void* pvftable; //0x00
PAD( 0x8 );
bool m_track_ir_available; //0x04
bool m_mouse_initialized; //0x05
bool m_mouse_active; //0x06
bool m_joystick_advanced_init; //0x07
PAD( 0x2C ); //0x08
void* m_keys; //0x34
PAD( 0x64 ); //0x38
int pad_0x41;
int pad_0x42;
bool m_camera_intercepting_mouse; //0x9C
bool m_camera_in_thirdperson; //0x9D
bool m_camera_moving_with_mouse; //0x9E
vec3_t m_camera_offset; //0xA0
bool m_camera_distance_move; //0xAC
int m_camera_old_x; //0xB0
int m_camera_old_y; //0xB4
int m_camera_x; //0xB8
int m_camera_y; //0xBC
bool m_camera_is_orthographic; //0xC0
vec3_t m_prev_viewangles; //0xC4
vec3_t m_prev_viewangles_tilt; //0xD0
float m_last_forward_move; //0xDC
int m_clear_input_state; //0xE0
ucmd_t* get_usercmd( int slot, int sequence_number ) {
auto _this = ( char* ) this;
auto unk = (int) this;
if ( slot != -1 )
unk = (int)&_this [ 0xDC * slot ];
auto ret = ( ucmd_t* ) ( *( std::uintptr_t *)( std::uintptr_t( unk ) + 0xF4 ) + 100 * ( sequence_number % 150 ) );
if ( ret->m_cmdnum != sequence_number )
ret = nullptr;
return ret;
}
ucmd_t* get_usercmds( int slot ) {
auto _this = ( char* ) this;
auto unk = ( int ) this;
if ( slot != -1 )
unk = ( int ) &_this [ 0xDC * slot ];
return ( ucmd_t* ) ( *( std::uintptr_t* )( std::uintptr_t( unk ) + 0xF4 ) );
}
}; | 25.305085 | 116 | 0.669123 | amizu03 |
4c9ede0a85de0899198cd218ea2c0a789ea2dd43 | 1,684 | cpp | C++ | tests/vm/machine_stores.cpp | aligusnet/mixvm | 1c260f998e1bf187d8ed84b74b19bac8029fe64c | [
"BSD-3-Clause"
] | 2 | 2020-09-14T21:25:35.000Z | 2021-07-14T16:30:06.000Z | tests/vm/machine_stores.cpp | Alexander-Ignatyev/mixvm | 1c260f998e1bf187d8ed84b74b19bac8029fe64c | [
"BSD-3-Clause"
] | null | null | null | tests/vm/machine_stores.cpp | Alexander-Ignatyev/mixvm | 1c260f998e1bf187d8ed84b74b19bac8029fe64c | [
"BSD-3-Clause"
] | 1 | 2021-07-14T16:30:08.000Z | 2021-07-14T16:30:08.000Z | #include "machine_fixture.h"
namespace mix {
class MachineStoresTestSuite : public MachineFixture {};
TEST_F(MachineStoresTestSuite, sta) {
set_reg_a_value(-73);
machine.sta(make_instruction(cmd_sta, 152));
EXPECT_EQ(-73, get_memory_value(152));
}
TEST_F(MachineStoresTestSuite, st1) {
set_reg_i_value(1, 11);
machine.st1(make_instruction(cmd_st1, 152));
EXPECT_EQ(11, get_memory_value(152));
}
TEST_F(MachineStoresTestSuite, st2) {
set_reg_i_value(2, 12);
machine.st2(make_instruction(cmd_st2, 152));
EXPECT_EQ(12, get_memory_value(152));
}
TEST_F(MachineStoresTestSuite, st3) {
set_reg_i_value(3, 13);
machine.st3(make_instruction(cmd_st3, 152));
EXPECT_EQ(13, get_memory_value(152));
}
TEST_F(MachineStoresTestSuite, st4) {
set_reg_i_value(4, 14);
machine.st4(make_instruction(cmd_st4, 152));
EXPECT_EQ(14, get_memory_value(152));
}
TEST_F(MachineStoresTestSuite, st5) {
set_reg_i_value(5, 15);
machine.st5(make_instruction(cmd_st5, 152));
EXPECT_EQ(15, get_memory_value(152));
}
TEST_F(MachineStoresTestSuite, st6) {
set_reg_i_value(6, 16);
machine.st6(make_instruction(cmd_st6, 152));
EXPECT_EQ(16, get_memory_value(152));
}
TEST_F(MachineStoresTestSuite, stx) {
set_reg_x_value(-18);
machine.stx(make_instruction(cmd_stx, 152));
EXPECT_EQ(-18, get_memory_value(152));
}
TEST_F(MachineStoresTestSuite, stj) {
set_next_instruction_address(99);
machine.stj(make_instruction(cmd_stj, 152));
EXPECT_EQ(99, get_memory_value(152));
}
TEST_F(MachineStoresTestSuite, stz) {
set_memory_value(152, -75);
machine.stz(make_instruction(cmd_stz, 152));
EXPECT_EQ(0, get_memory_value(152));
}
} // namespace mix
| 21.87013 | 56 | 0.745843 | aligusnet |
4ca0e50ec9e3bb61446e9b837399ceb5cd000d2b | 846 | cpp | C++ | Data/tests.cpp | wispwisp/associationRuleAnalysis | 978c8caf7fd19d11191461d05343268bcd71732f | [
"MIT"
] | null | null | null | Data/tests.cpp | wispwisp/associationRuleAnalysis | 978c8caf7fd19d11191461d05343268bcd71732f | [
"MIT"
] | null | null | null | Data/tests.cpp | wispwisp/associationRuleAnalysis | 978c8caf7fd19d11191461d05343268bcd71732f | [
"MIT"
] | null | null | null | #include "Data.hpp"
#include <sstream>
#include <stdexcept>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(TestDataClass)
BOOST_AUTO_TEST_CASE(inconsistentDataLenghPerLine)
{
std::string s =
"010101\n"
"0101001"; // <-- one more element
std::stringstream bitsString{ s };
BOOST_CHECK_THROW(Data::parseUniqueDataFromStream(bitsString), std::logic_error);
}
BOOST_AUTO_TEST_CASE(emptyData)
{
std::string s = "";
std::stringstream bitsString{ s };
BOOST_CHECK_THROW(Data::parseUniqueDataFromStream(bitsString), std::logic_error);
}
BOOST_AUTO_TEST_CASE(wrongData)
{
std::string s =
"010101\n"
"0l0101\n"// <-- 'l' instead of '1'
"110100\n";
std::stringstream bitsString{ s };
BOOST_CHECK_THROW(Data::parseUniqueDataFromStream(bitsString), std::logic_error);
}
BOOST_AUTO_TEST_SUITE_END()
| 20.634146 | 83 | 0.72695 | wispwisp |
4cac9c12dd1cd9b7fc188f74cb6883adc1653c3c | 29,046 | cpp | C++ | project/source/game/location/City.cpp | Shdorsh/carpg | 376130a1ed410116fc8a607601b327eae7dca383 | [
"MIT"
] | null | null | null | project/source/game/location/City.cpp | Shdorsh/carpg | 376130a1ed410116fc8a607601b327eae7dca383 | [
"MIT"
] | null | null | null | project/source/game/location/City.cpp | Shdorsh/carpg | 376130a1ed410116fc8a607601b327eae7dca383 | [
"MIT"
] | null | null | null | #include "Pch.h"
#include "GameCore.h"
#include "City.h"
#include "SaveState.h"
#include "Content.h"
#include "ResourceManager.h"
#include "Object.h"
#include "Unit.h"
#include "GameFile.h"
#include "BuildingScript.h"
#include "World.h"
#include "Level.h"
#include "BitStreamFunc.h"
//=================================================================================================
City::~City()
{
DeleteElements(inside_buildings);
}
//=================================================================================================
void City::Save(GameWriter& f, bool local)
{
OutsideLocation::Save(f, local);
f << citizens;
f << citizens_world;
f << settlement_type;
f << flags;
f << variant;
if(last_visit == -1)
{
// list of buildings in this location is generated
f << buildings.size();
for(CityBuilding& b : buildings)
f << b.type->id;
}
else
{
f << entry_points;
f << gates;
f << buildings.size();
for(CityBuilding& b : buildings)
{
f << b.type->id;
f << b.pt;
f << b.unit_pt;
f << b.rot;
f << b.walk_pt;
}
f << inside_offset;
f << inside_buildings.size();
for(InsideBuilding* b : inside_buildings)
b->Save(f, local);
f << quest_mayor;
f << quest_mayor_time;
f << quest_captain;
f << quest_captain_time;
f << arena_time;
f << arena_pos;
}
}
//=================================================================================================
void City::Load(GameReader& f, bool local, LOCATION_TOKEN token)
{
OutsideLocation::Load(f, local, token);
f >> citizens;
f >> citizens_world;
if(LOAD_VERSION >= V_0_5)
{
f >> settlement_type;
f >> flags;
f >> variant;
if(last_visit == -1)
{
// list of buildings in this location is generated
uint count;
f >> count;
buildings.resize(count);
for(CityBuilding& b : buildings)
{
b.type = Building::Get(f.ReadString1());
assert(b.type != nullptr);
}
}
else
{
f >> entry_points;
f >> gates;
uint count;
f >> count;
buildings.resize(count);
for(CityBuilding& b : buildings)
{
b.type = Building::Get(f.ReadString1());
f >> b.pt;
f >> b.unit_pt;
f >> b.rot;
f >> b.walk_pt;
assert(b.type != nullptr);
}
f >> inside_offset;
f >> count;
inside_buildings.resize(count);
int index = 0;
for(InsideBuilding*& b : inside_buildings)
{
b = new InsideBuilding;
b->Load(f, local);
b->ctx.building_id = index;
b->ctx.mine = Int2(b->level_shift.x * 256, b->level_shift.y * 256);
b->ctx.maxe = b->ctx.mine + Int2(256, 256);
++index;
}
f >> quest_mayor;
f >> quest_mayor_time;
f >> quest_captain;
f >> quest_captain_time;
f >> arena_time;
f >> arena_pos;
}
}
else
{
if(token == LT_CITY)
settlement_type = SettlementType::City;
else
{
settlement_type = SettlementType::Village;
image = LI_VILLAGE;
}
flags = 0;
variant = 0;
if(last_visit != -1)
{
int side;
Box2d spawn_area;
Box2d exit_area;
float spawn_dir;
if(LOAD_VERSION < V_0_3)
{
f >> side;
f >> spawn_area;
f >> exit_area;
f >> spawn_dir;
}
else
{
f.ReadVector<byte>(entry_points);
bool have_exit;
f >> have_exit;
gates = f.Read<byte>();
if(have_exit)
flags |= HaveExit;
}
uint count;
f >> count;
buildings.resize(count);
for(CityBuilding& b : buildings)
{
OLD_BUILDING type;
f >> type;
f >> b.pt;
f >> b.unit_pt;
f >> b.rot;
f >> b.walk_pt;
b.type = Building::GetOld(type);
assert(b.type != nullptr);
}
f >> inside_offset;
f >> count;
inside_buildings.resize(count);
int index = 0;
for(InsideBuilding*& b : inside_buildings)
{
b = new InsideBuilding;
b->Load(f, local);
b->ctx.building_id = index;
b->ctx.mine = Int2(b->level_shift.x * 256, b->level_shift.y * 256);
b->ctx.maxe = b->ctx.mine + Int2(256, 256);
++index;
}
f >> quest_mayor;
f >> quest_mayor_time;
f >> quest_captain;
f >> quest_captain_time;
f >> arena_time;
f >> arena_pos;
if(LOAD_VERSION < V_0_3)
{
const float aa = 11.1f;
const float bb = 12.6f;
const float es = 1.3f;
const int mur1 = int(0.15f*size);
const int mur2 = int(0.85f*size);
TERRAIN_TILE road_type;
// setup entrance
switch(side)
{
case 0: // from top
{
Vec2 p(float(size) + 1.f, 0.8f*size * 2);
exit_area = Box2d(p.x - es, p.y + aa, p.x + es, p.y + bb);
gates = GATE_NORTH;
road_type = tiles[size / 2 + int(0.85f*size - 2)*size].t;
}
break;
case 1: // from left
{
Vec2 p(0.2f*size * 2, float(size) + 1.f);
exit_area = Box2d(p.x - bb, p.y - es, p.x - aa, p.y + es);
gates = GATE_WEST;
road_type = tiles[int(0.15f*size) + 2 + (size / 2)*size].t;
}
break;
case 2: // from bottom
{
Vec2 p(float(size) + 1.f, 0.2f*size * 2);
exit_area = Box2d(p.x - es, p.y - bb, p.x + es, p.y - aa);
gates = GATE_SOUTH;
road_type = tiles[size / 2 + int(0.15f*size + 2)*size].t;
}
break;
case 3: // from right
{
Vec2 p(0.8f*size * 2, float(size) + 1.f);
exit_area = Box2d(p.x + aa, p.y - es, p.x + bb, p.y + es);
gates = GATE_EAST;
road_type = tiles[int(0.85f*size) - 2 + (size / 2)*size].t;
}
break;
}
// update terrain tiles
// tiles under walls
for(int i = mur1; i <= mur2; ++i)
{
// north
tiles[i + mur1*size].Set(TT_SAND, TM_BUILDING);
if(tiles[i + (mur1 + 1)*size].t == TT_GRASS)
tiles[i + (mur1 + 1)*size].Set(TT_SAND, TT_GRASS, 128, TM_BUILDING);
// south
tiles[i + mur2*size].Set(TT_SAND, TM_BUILDING);
if(tiles[i + (mur2 - 1)*size].t == TT_GRASS)
tiles[i + (mur2 - 1)*size].Set(TT_SAND, TT_GRASS, 128, TM_BUILDING);
// west
tiles[mur1 + i*size].Set(TT_SAND, TM_BUILDING);
if(tiles[mur1 + 1 + i*size].t == TT_GRASS)
tiles[mur1 + 1 + i*size].Set(TT_SAND, TT_GRASS, 128, TM_BUILDING);
// east
tiles[mur2 + i*size].Set(TT_SAND, TM_BUILDING);
if(tiles[mur2 - 1 + i*size].t == TT_GRASS)
tiles[mur2 - 1 + i*size].Set(TT_SAND, TT_GRASS, 128, TM_BUILDING);
}
// tiles under gates
if(gates == GATE_SOUTH)
{
tiles[size / 2 - 1 + int(0.15f*size)*size].Set(road_type, TM_ROAD);
tiles[size / 2 + int(0.15f*size)*size].Set(road_type, TM_ROAD);
tiles[size / 2 + 1 + int(0.15f*size)*size].Set(road_type, TM_ROAD);
tiles[size / 2 - 1 + (int(0.15f*size) + 1)*size].Set(road_type, TM_ROAD);
tiles[size / 2 + (int(0.15f*size) + 1)*size].Set(road_type, TM_ROAD);
tiles[size / 2 + 1 + (int(0.15f*size) + 1)*size].Set(road_type, TM_ROAD);
}
if(gates == GATE_WEST)
{
tiles[int(0.15f*size) + (size / 2 - 1)*size].Set(road_type, TM_ROAD);
tiles[int(0.15f*size) + (size / 2)*size].Set(road_type, TM_ROAD);
tiles[int(0.15f*size) + (size / 2 + 1)*size].Set(road_type, TM_ROAD);
tiles[int(0.15f*size) + 1 + (size / 2 - 1)*size].Set(road_type, TM_ROAD);
tiles[int(0.15f*size) + 1 + (size / 2)*size].Set(road_type, TM_ROAD);
tiles[int(0.15f*size) + 1 + (size / 2 + 1)*size].Set(road_type, TM_ROAD);
}
if(gates == GATE_NORTH)
{
tiles[size / 2 - 1 + int(0.85f*size)*size].Set(road_type, TM_ROAD);
tiles[size / 2 + int(0.85f*size)*size].Set(road_type, TM_ROAD);
tiles[size / 2 + 1 + int(0.85f*size)*size].Set(road_type, TM_ROAD);
tiles[size / 2 - 1 + (int(0.85f*size) - 1)*size].Set(road_type, TM_ROAD);
tiles[size / 2 + (int(0.85f*size) - 1)*size].Set(road_type, TM_ROAD);
tiles[size / 2 + 1 + (int(0.85f*size) - 1)*size].Set(road_type, TM_ROAD);
}
if(gates == GATE_EAST)
{
tiles[int(0.85f*size) + (size / 2 - 1)*size].Set(road_type, TM_ROAD);
tiles[int(0.85f*size) + (size / 2)*size].Set(road_type, TM_ROAD);
tiles[int(0.85f*size) + (size / 2 + 1)*size].Set(road_type, TM_ROAD);
tiles[int(0.85f*size) - 1 + (size / 2 - 1)*size].Set(road_type, TM_ROAD);
tiles[int(0.85f*size) - 1 + (size / 2)*size].Set(road_type, TM_ROAD);
tiles[int(0.85f*size) - 1 + (size / 2 + 1)*size].Set(road_type, TM_ROAD);
}
// delete old walls
BaseObject* to_remove = BaseObject::Get("to_remove");
LoopAndRemove(objects, [to_remove](const Object* obj)
{
if(obj->base == to_remove)
{
delete obj;
return true;
}
return false;
});
// add new buildings
BaseObject* oWall = BaseObject::Get("wall"),
*oTower = BaseObject::Get("tower");
const int mid = int(0.5f*size);
// walls
for(int i = mur1; i < mur2; i += 3)
{
// top
if(side != 2 || i < mid - 1 || i > mid)
{
Object* o = new Object;
o->pos = Vec3(float(i) * 2 + 1.f, 1.f, int(0.15f*size) * 2 + 1.f);
o->rot = Vec3(0, PI, 0);
o->scale = 1.f;
o->base = oWall;
o->mesh = oWall->mesh;
objects.push_back(o);
}
// bottom
if(side != 0 || i < mid - 1 || i > mid)
{
Object* o = new Object;
o->pos = Vec3(float(i) * 2 + 1.f, 1.f, int(0.85f*size) * 2 + 1.f);
o->rot = Vec3(0, 0, 0);
o->scale = 1.f;
o->base = oWall;
o->mesh = oWall->mesh;
objects.push_back(o);
}
// left
if(side != 1 || i < mid - 1 || i > mid)
{
Object* o = new Object;
o->pos = Vec3(int(0.15f*size) * 2 + 1.f, 1.f, float(i) * 2 + 1.f);
o->rot = Vec3(0, PI * 3 / 2, 0);
o->scale = 1.f;
o->base = oWall;
o->mesh = oWall->mesh;
objects.push_back(o);
}
// right
if(side != 3 || i < mid - 1 || i > mid)
{
Object* o = new Object;
o->pos = Vec3(int(0.85f*size) * 2 + 1.f, 1.f, float(i) * 2 + 1.f);
o->rot = Vec3(0, PI / 2, 0);
o->scale = 1.f;
o->base = oWall;
o->mesh = oWall->mesh;
objects.push_back(o);
}
}
// towers
{
// right top
Object* o = new Object;
o->pos = Vec3(int(0.85f*size) * 2 + 1.f, 1.f, int(0.85f*size) * 2 + 1.f);
o->rot = Vec3(0, 0, 0);
o->scale = 1.f;
o->base = oTower;
o->mesh = oTower->mesh;
objects.push_back(o);
}
{
// right bottom
Object* o = new Object;
o->pos = Vec3(int(0.85f*size) * 2 + 1.f, 1.f, int(0.15f*size) * 2 + 1.f);
o->rot = Vec3(0, PI / 2, 0);
o->scale = 1.f;
o->base = oTower;
o->mesh = oTower->mesh;
objects.push_back(o);
}
{
// left bottom
Object* o = new Object;
o->pos = Vec3(int(0.15f*size) * 2 + 1.f, 1.f, int(0.15f*size) * 2 + 1.f);
o->rot = Vec3(0, PI, 0);
o->scale = 1.f;
o->base = oTower;
o->mesh = oTower->mesh;
objects.push_back(o);
}
{
// left top
Object* o = new Object;
o->pos = Vec3(int(0.15f*size) * 2 + 1.f, 1.f, int(0.85f*size) * 2 + 1.f);
o->rot = Vec3(0, PI * 3 / 2, 0);
o->scale = 1.f;
o->base = oTower;
o->mesh = oTower->mesh;
objects.push_back(o);
}
// gate
Object* o = new Object;
o->rot.x = o->rot.z = 0.f;
o->scale = 1.f;
o->base = BaseObject::Get("gate");
o->mesh = o->base->mesh;
switch(side)
{
case 0:
o->rot.y = 0;
o->pos = Vec3(0.5f*size * 2 + 1.f, 1.f, 0.85f*size * 2);
break;
case 1:
o->rot.y = PI * 3 / 2;
o->pos = Vec3(0.15f*size * 2, 1.f, 0.5f*size * 2 + 1.f);
break;
case 2:
o->rot.y = PI;
o->pos = Vec3(0.5f*size * 2 + 1.f, 1.f, 0.15f*size * 2);
break;
case 3:
o->rot.y = PI / 2;
o->pos = Vec3(0.85f*size * 2, 1.f, 0.5f*size * 2 + 1.f);
break;
}
objects.push_back(o);
// grate
Object* o2 = new Object;
o2->pos = o->pos;
o2->rot = o->rot;
o2->scale = 1.f;
o2->base = BaseObject::Get("grate");
o2->mesh = o2->base->mesh;
objects.push_back(o2);
// exit
EntryPoint& entry = Add1(entry_points);
entry.spawn_area = spawn_area;
entry.spawn_rot = spawn_dir;
entry.exit_area = exit_area;
entry.exit_y = 1.1f;
}
}
if(token == LT_VILLAGE_OLD)
{
OLD_BUILDING v_buildings[2];
f >> v_buildings;
if(LOAD_VERSION <= V_0_3 && v_buildings[1] == OLD_BUILDING::B_COTTAGE)
v_buildings[1] = OLD_BUILDING::B_NONE;
// fix wrong village house building
if(last_visit != -1 && LOAD_VERSION < V_0_4)
{
bool need_fix = false;
Building* village_hall = Building::GetOld(OLD_BUILDING::B_VILLAGE_HALL);
if(LOAD_VERSION < V_0_3)
need_fix = true;
else if(LOAD_VERSION == V_0_3)
{
InsideBuilding* b = FindInsideBuilding(village_hall);
// easiest way to find out if it uses old mesh
if(b->top > 3.5f)
need_fix = true;
}
if(need_fix)
{
Building* village_hall_old = Building::GetOld(OLD_BUILDING::B_VILLAGE_HALL_OLD);
FindBuilding(village_hall)->type = village_hall_old;
for(Object* obj : objects)
{
if(strcmp(obj->mesh->filename, "soltys.qmsh") == 0)
{
obj->mesh = ResourceManager::Get<Mesh>().GetLoaded("soltys_old.qmsh");
break;
}
}
InsideBuilding* b = FindInsideBuilding(village_hall);
b->type = village_hall_old;
for(Object* obj : b->objects)
{
if(strcmp(obj->mesh->filename, "soltys_srodek.qmsh") == 0)
{
obj->mesh = ResourceManager::Get<Mesh>().GetLoaded("soltys_srodek_old.qmsh");
break;
}
}
}
}
if(state == LS_KNOWN)
{
buildings.push_back(CityBuilding(Building::GetOld(OLD_BUILDING::B_VILLAGE_HALL)));
buildings.push_back(CityBuilding(Building::GetOld(OLD_BUILDING::B_MERCHANT)));
buildings.push_back(CityBuilding(Building::GetOld(OLD_BUILDING::B_FOOD_SELLER)));
buildings.push_back(CityBuilding(Building::GetOld(OLD_BUILDING::B_VILLAGE_INN)));
if(v_buildings[0] != OLD_BUILDING::B_NONE)
buildings.push_back(CityBuilding(Building::GetOld(v_buildings[0])));
if(v_buildings[1] != OLD_BUILDING::B_NONE)
buildings.push_back(CityBuilding(Building::GetOld(v_buildings[1])));
std::random_shuffle(buildings.begin() + 1, buildings.end(), MyRand);
buildings.push_back(CityBuilding(Building::GetOld(OLD_BUILDING::B_BARRACKS)));
flags |= HaveInn | HaveMerchant | HaveFoodSeller;
if(v_buildings[0] == OLD_BUILDING::B_TRAINING_GROUNDS || v_buildings[1] == OLD_BUILDING::B_TRAINING_GROUNDS)
flags |= HaveTrainingGrounds;
if(v_buildings[0] == OLD_BUILDING::B_BLACKSMITH || v_buildings[1] == OLD_BUILDING::B_BLACKSMITH)
flags |= HaveBlacksmith;
if(v_buildings[0] == OLD_BUILDING::B_ALCHEMIST || v_buildings[1] == OLD_BUILDING::B_ALCHEMIST)
flags |= HaveAlchemist;
}
}
else if(state == LS_KNOWN)
{
buildings.push_back(CityBuilding(Building::GetOld(OLD_BUILDING::B_CITY_HALL)));
buildings.push_back(CityBuilding(Building::GetOld(OLD_BUILDING::B_ARENA)));
buildings.push_back(CityBuilding(Building::GetOld(OLD_BUILDING::B_MERCHANT)));
buildings.push_back(CityBuilding(Building::GetOld(OLD_BUILDING::B_FOOD_SELLER)));
buildings.push_back(CityBuilding(Building::GetOld(OLD_BUILDING::B_BLACKSMITH)));
buildings.push_back(CityBuilding(Building::GetOld(OLD_BUILDING::B_ALCHEMIST)));
buildings.push_back(CityBuilding(Building::GetOld(OLD_BUILDING::B_INN)));
buildings.push_back(CityBuilding(Building::GetOld(OLD_BUILDING::B_TRAINING_GROUNDS)));
std::random_shuffle(buildings.begin() + 2, buildings.end(), MyRand);
buildings.push_back(CityBuilding(Building::GetOld(OLD_BUILDING::B_BARRACKS)));
flags |= HaveTrainingGrounds | HaveArena | HaveMerchant | HaveFoodSeller | HaveBlacksmith | HaveAlchemist | HaveInn;
}
}
}
//=================================================================================================
void City::Write(BitStreamWriter& f)
{
OutsideLocation::Write(f);
f.WriteCasted<byte>(flags);
f.WriteCasted<byte>(entry_points.size());
for(EntryPoint& entry_point : entry_points)
{
f << entry_point.exit_area;
f << entry_point.exit_y;
}
f.WriteCasted<byte>(buildings.size());
for(CityBuilding& building : buildings)
{
f << building.type->id;
f << building.pt;
f.WriteCasted<byte>(building.rot);
}
f.WriteCasted<byte>(inside_buildings.size());
for(InsideBuilding* inside_building : inside_buildings)
inside_building->Write(f);
}
//=================================================================================================
bool City::Read(BitStreamReader& f)
{
OutsideLocation::Read(f);
// entry points
const int ENTRY_POINT_MIN_SIZE = 20;
byte count;
f.ReadCasted<byte>(flags);
f >> count;
if(!f.Ensure(count * ENTRY_POINT_MIN_SIZE))
{
Error("Read level: Broken packet for city.");
return false;
}
entry_points.resize(count);
for(EntryPoint& entry : entry_points)
{
f.Read(entry.exit_area);
f.Read(entry.exit_y);
}
if(!f)
{
Error("Read level: Broken packet for entry points.");
return false;
}
// buildings
const int BUILDING_MIN_SIZE = 10;
f >> count;
if(!f.Ensure(BUILDING_MIN_SIZE * count))
{
Error("Read level: Broken packet for buildings count.");
return false;
}
buildings.resize(count);
for(CityBuilding& building : buildings)
{
const string& building_id = f.ReadString1();
f >> building.pt;
f.ReadCasted<byte>(building.rot);
if(!f)
{
Error("Read level: Broken packet for buildings.");
return false;
}
building.type = Building::Get(building_id);
if(!building.type)
{
Error("Read level: Invalid building id '%s'.", building_id.c_str());
return false;
}
}
// inside buildings
const int INSIDE_BUILDING_MIN_SIZE = 73;
f >> count;
if(!f.Ensure(INSIDE_BUILDING_MIN_SIZE * count))
{
Error("Read level: Broken packet for inside buildings count.");
return false;
}
inside_buildings.resize(count);
int index = 0;
for(InsideBuilding*& ib : inside_buildings)
{
ib = new InsideBuilding;
L.ApplyContext(ib, ib->ctx);
ib->ctx.building_id = index;
if(!ib->Load(f))
{
Error("Read level: Failed to loading inside building %d.", index);
return false;
}
++index;
}
return true;
}
//=================================================================================================
void City::BuildRefidTables()
{
OutsideLocation::BuildRefidTables();
for(vector<InsideBuilding*>::iterator it2 = inside_buildings.begin(), end2 = inside_buildings.end(); it2 != end2; ++it2)
{
for(vector<Unit*>::iterator it = (*it2)->units.begin(), end = (*it2)->units.end(); it != end; ++it)
{
(*it)->refid = (int)Unit::refid_table.size();
Unit::refid_table.push_back(*it);
}
for(vector<Usable*>::iterator it = (*it2)->usables.begin(), end = (*it2)->usables.end(); it != end; ++it)
{
(*it)->refid = (int)Usable::refid_table.size();
Usable::refid_table.push_back(*it);
}
}
}
//=================================================================================================
bool City::FindUnit(Unit* unit, int* level)
{
assert(unit);
for(Unit* u : units)
{
if(u == unit)
{
if(level)
*level = -1;
return true;
}
}
for(uint i = 0; i < inside_buildings.size(); ++i)
{
for(Unit* u : inside_buildings[i]->units)
{
if(u == unit)
{
if(level)
*level = i;
return true;
}
}
}
return false;
}
//=================================================================================================
Unit* City::FindUnit(UnitData* data, int& at_level)
{
assert(data);
for(Unit* u : units)
{
if(u->data == data)
{
at_level = -1;
return u;
}
}
for(uint i = 0; i < inside_buildings.size(); ++i)
{
for(Unit* u : inside_buildings[i]->units)
{
if(u->data == data)
{
at_level = i;
return u;
}
}
}
return nullptr;
}
//=================================================================================================
bool City::IsInsideCity(const Vec3& _pos)
{
Int2 tile(int(_pos.x / 2), int(_pos.z / 2));
if(tile.x <= int(0.15f*size) || tile.y <= int(0.15f*size) || tile.x >= int(0.85f*size) || tile.y >= int(0.85f*size))
return false;
else
return true;
}
//=================================================================================================
InsideBuilding* City::FindInsideBuilding(Building* type)
{
assert(type);
for(InsideBuilding* i : inside_buildings)
{
if(i->type == type)
return i;
}
return nullptr;
}
//=================================================================================================
InsideBuilding* City::FindInsideBuilding(BuildingGroup* group)
{
assert(group);
for(InsideBuilding* i : inside_buildings)
{
if(i->type->group == group)
return i;
}
return nullptr;
}
//=================================================================================================
InsideBuilding* City::FindInsideBuilding(BuildingGroup* group, int& index)
{
assert(group);
index = 0;
for(InsideBuilding* i : inside_buildings)
{
if(i->type->group == group)
return i;
++index;
}
index = -1;
return nullptr;
}
//=================================================================================================
CityBuilding* City::FindBuilding(BuildingGroup* group)
{
assert(group);
for(CityBuilding& b : buildings)
{
if(b.type->group == group)
return &b;
}
return nullptr;
}
//=================================================================================================
CityBuilding* City::FindBuilding(Building* type)
{
assert(type);
for(CityBuilding& b : buildings)
{
if(b.type == type)
return &b;
}
return nullptr;
}
//=================================================================================================
void City::GenerateCityBuildings(vector<Building*>& buildings, bool required)
{
BuildingScript* script = BuildingScript::Get(IsVillage() ? "village" : "city");
if(variant == -1)
variant = Rand() % script->variants.size();
BuildingScript::Variant* v = script->variants[variant];
int* code = v->code.data();
int* end = code + v->code.size();
for(uint i = 0; i < BuildingScript::MAX_VARS; ++i)
script->vars[i] = 0;
script->vars[BuildingScript::V_COUNT] = 1;
script->vars[BuildingScript::V_CITIZENS] = citizens;
script->vars[BuildingScript::V_CITIZENS_WORLD] = citizens_world;
if(!required)
code += script->required_offset;
vector<int> stack;
int if_level = 0, if_depth = 0;
int shuffle_start = -1;
int& building_count = script->vars[BuildingScript::V_COUNT];
while(code != end)
{
BuildingScript::Code c = (BuildingScript::Code)*code++;
switch(c)
{
case BuildingScript::BS_ADD_BUILDING:
if(if_level == if_depth)
{
BuildingScript::Code type = (BuildingScript::Code)*code++;
if(type == BuildingScript::BS_BUILDING)
{
Building* b = (Building*)*code++;
for(int i = 0; i < building_count; ++i)
buildings.push_back(b);
}
else
{
BuildingGroup* bg = (BuildingGroup*)*code++;
for(int i = 0; i < building_count; ++i)
buildings.push_back(random_item(bg->buildings));
}
}
else
code += 2;
break;
case BuildingScript::BS_RANDOM:
{
uint count = (uint)*code++;
if(if_level != if_depth)
{
code += count * 2;
break;
}
for(int i = 0; i < building_count; ++i)
{
uint index = Rand() % count;
BuildingScript::Code type = (BuildingScript::Code)*(code + index * 2);
if(type == BuildingScript::BS_BUILDING)
{
Building* b = (Building*)*(code + index * 2 + 1);
buildings.push_back(b);
}
else
{
BuildingGroup* bg = (BuildingGroup*)*(code + index * 2 + 1);
buildings.push_back(random_item(bg->buildings));
}
}
code += count * 2;
}
break;
case BuildingScript::BS_SHUFFLE_START:
if(if_level == if_depth)
shuffle_start = (int)buildings.size();
break;
case BuildingScript::BS_SHUFFLE_END:
if(if_level == if_depth)
{
int new_pos = (int)buildings.size();
if(new_pos - shuffle_start >= 2)
std::random_shuffle(buildings.begin() + shuffle_start, buildings.end(), MyRand);
shuffle_start = -1;
}
break;
case BuildingScript::BS_REQUIRED_OFF:
if(required)
goto cleanup;
break;
case BuildingScript::BS_PUSH_INT:
if(if_level == if_depth)
stack.push_back(*code++);
else
++code;
break;
case BuildingScript::BS_PUSH_VAR:
if(if_level == if_depth)
stack.push_back(script->vars[*code++]);
else
++code;
break;
case BuildingScript::BS_SET_VAR:
if(if_level == if_depth)
{
script->vars[*code++] = stack.back();
stack.pop_back();
}
else
++code;
break;
case BuildingScript::BS_INC:
if(if_level == if_depth)
++script->vars[*code++];
else
++code;
break;
case BuildingScript::BS_DEC:
if(if_level == if_depth)
--script->vars[*code++];
else
++code;
break;
case BuildingScript::BS_IF:
if(if_level == if_depth)
{
BuildingScript::Code op = (BuildingScript::Code)*code++;
int right = stack.back();
stack.pop_back();
int left = stack.back();
stack.pop_back();
bool ok = false;
switch(op)
{
case BuildingScript::BS_EQUAL:
ok = (left == right);
break;
case BuildingScript::BS_NOT_EQUAL:
ok = (left != right);
break;
case BuildingScript::BS_GREATER:
ok = (left > right);
break;
case BuildingScript::BS_GREATER_EQUAL:
ok = (left >= right);
break;
case BuildingScript::BS_LESS:
ok = (left < right);
break;
case BuildingScript::BS_LESS_EQUAL:
ok = (left <= right);
break;
}
++if_level;
if(ok)
++if_depth;
}
else
{
++code;
++if_level;
}
break;
case BuildingScript::BS_IF_RAND:
if(if_level == if_depth)
{
int a = stack.back();
stack.pop_back();
if(a > 0 && Rand() % a == 0)
++if_depth;
}
++if_level;
break;
case BuildingScript::BS_ELSE:
if(if_level == if_depth)
--if_depth;
break;
case BuildingScript::BS_ENDIF:
if(if_level == if_depth)
--if_depth;
--if_level;
break;
case BuildingScript::BS_CALL:
case BuildingScript::BS_ADD:
case BuildingScript::BS_SUB:
case BuildingScript::BS_MUL:
case BuildingScript::BS_DIV:
if(if_level == if_depth)
{
int b = stack.back();
stack.pop_back();
int a = stack.back();
stack.pop_back();
int result = 0;
switch(c)
{
case BuildingScript::BS_CALL:
if(a == b)
result = a;
else if(b > a)
result = Random(a, b);
break;
case BuildingScript::BS_ADD:
result = a + b;
break;
case BuildingScript::BS_SUB:
result = a - b;
break;
case BuildingScript::BS_MUL:
result = a * b;
break;
case BuildingScript::BS_DIV:
if(b != 0)
result = a / b;
break;
}
stack.push_back(result);
}
break;
case BuildingScript::BS_NEG:
if(if_level == if_depth)
stack.back() = -stack.back();
break;
}
}
cleanup:
citizens = script->vars[BuildingScript::V_CITIZENS];
citizens_world = script->vars[BuildingScript::V_CITIZENS_WORLD];
}
//=================================================================================================
void City::GetEntry(Vec3& pos, float& rot)
{
if(entry_points.size() == 1)
{
pos = entry_points[0].spawn_area.Midpoint().XZ();
rot = entry_points[0].spawn_rot;
}
else
{
// check which spawn rot i closest to entry rot
float best_dif = 999.f;
int best_index = -1, index = 0;
float dir = Clip(-W.GetTravelDir() + PI / 2);
for(vector<EntryPoint>::iterator it = entry_points.begin(), end = entry_points.end(); it != end; ++it, ++index)
{
float dif = AngleDiff(dir, it->spawn_rot);
if(dif < best_dif)
{
best_dif = dif;
best_index = index;
}
}
pos = entry_points[best_index].spawn_area.Midpoint().XZ();
rot = entry_points[best_index].spawn_rot;
}
}
//=================================================================================================
void City::PrepareCityBuildings(vector<ToBuild>& tobuild)
{
// required buildings
tobuild.reserve(buildings.size());
for(CityBuilding& cb : buildings)
tobuild.push_back(ToBuild(cb.type, true));
buildings.clear();
// not required buildings
LocalVector2<Building*> buildings;
GenerateCityBuildings(buildings.Get(), false);
tobuild.reserve(tobuild.size() + buildings.size());
for(Building* b : buildings)
tobuild.push_back(ToBuild(b, false));
// set flags
for(ToBuild& tb : tobuild)
{
if(tb.type->group == BuildingGroup::BG_TRAINING_GROUNDS)
flags |= HaveTrainingGrounds;
else if(tb.type->group == BuildingGroup::BG_BLACKSMITH)
flags |= HaveBlacksmith;
else if(tb.type->group == BuildingGroup::BG_MERCHANT)
flags |= HaveMerchant;
else if(tb.type->group == BuildingGroup::BG_ALCHEMIST)
flags |= HaveAlchemist;
else if(tb.type->group == BuildingGroup::BG_FOOD_SELLER)
flags |= HaveFoodSeller;
else if(tb.type->group == BuildingGroup::BG_INN)
flags |= HaveInn;
else if(tb.type->group == BuildingGroup::BG_ARENA)
flags |= HaveArena;
}
}
| 26.073609 | 121 | 0.567582 | Shdorsh |
4cae835ea50a1948247087b62f0c22f45a01d3bb | 1,985 | cpp | C++ | test/input.output/file.streams/fstreams/fstream.assign/member_swap.pass.cpp | caiohamamura/libcxx | 27c836ff3a9c505deb9fd1616012924de8ff9279 | [
"MIT"
] | 187 | 2015-02-28T11:50:45.000Z | 2022-02-20T12:51:00.000Z | test/input.output/file.streams/fstreams/fstream.assign/member_swap.pass.cpp | caiohamamura/libcxx | 27c836ff3a9c505deb9fd1616012924de8ff9279 | [
"MIT"
] | 2 | 2019-06-24T20:44:59.000Z | 2020-06-17T18:41:35.000Z | test/input.output/file.streams/fstreams/fstream.assign/member_swap.pass.cpp | caiohamamura/libcxx | 27c836ff3a9c505deb9fd1616012924de8ff9279 | [
"MIT"
] | 80 | 2015-01-02T12:44:41.000Z | 2022-01-20T15:37:54.000Z | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <fstream>
// template <class charT, class traits = char_traits<charT> >
// class basic_fstream
// void swap(basic_fstream& rhs);
#include <fstream>
#include <cassert>
int main()
{
char temp1[L_tmpnam], temp2[L_tmpnam];
tmpnam(temp1);
tmpnam(temp2);
{
std::fstream fs1(temp1, std::ios_base::in | std::ios_base::out
| std::ios_base::trunc);
std::fstream fs2(temp2, std::ios_base::in | std::ios_base::out
| std::ios_base::trunc);
fs1 << 1 << ' ' << 2;
fs2 << 2 << ' ' << 1;
fs1.seekg(0);
fs1.swap(fs2);
fs1.seekg(0);
int i;
fs1 >> i;
assert(i == 2);
fs1 >> i;
assert(i == 1);
i = 0;
fs2 >> i;
assert(i == 1);
fs2 >> i;
assert(i == 2);
}
std::remove(temp1);
std::remove(temp2);
{
std::wfstream fs1(temp1, std::ios_base::in | std::ios_base::out
| std::ios_base::trunc);
std::wfstream fs2(temp2, std::ios_base::in | std::ios_base::out
| std::ios_base::trunc);
fs1 << 1 << ' ' << 2;
fs2 << 2 << ' ' << 1;
fs1.seekg(0);
fs1.swap(fs2);
fs1.seekg(0);
int i;
fs1 >> i;
assert(i == 2);
fs1 >> i;
assert(i == 1);
i = 0;
fs2 >> i;
assert(i == 1);
fs2 >> i;
assert(i == 2);
}
std::remove(temp1);
std::remove(temp2);
}
| 27.569444 | 80 | 0.401008 | caiohamamura |
4caf0233038c4f77854faf0424c5dd7847ccb966 | 1,438 | hpp | C++ | source/reusable/stdlib/all/ppp_facilities.hpp | alf-p-steinbach/NPP-plugin-Empty-files-as-Unicode | aeae720140a1fc4aa4a18104e7a834ace2276875 | [
"MIT"
] | 13 | 2017-06-20T13:24:39.000Z | 2018-02-27T08:49:17.000Z | source/all/ppp_facilities.hpp | alf-p-steinbach/Wrapped-stdlib | 1280c3b68f30197549efd61af35ca57c477d59fe | [
"BSL-1.0"
] | null | null | null | source/all/ppp_facilities.hpp | alf-p-steinbach/Wrapped-stdlib | 1280c3b68f30197549efd61af35ca57c477d59fe | [
"BSL-1.0"
] | 1 | 2018-01-11T17:32:22.000Z | 2018-01-11T17:32:22.000Z | #pragma once // Source encoding: utf-8 with BOM ∩
// #include <stdlib/all/stroustrup_ppp_facilities.hpp>
//
// Corresponds to the `"std_lib_facilities.h"` header for Bjarne Stroustrup's book
// “Programming: Principles and Practice Using C++”, plus `hopefully` and `fail`,
// except that here there's no evil `using namespace std;`.
//
// Copyright © 2017 Alf P. Steinbach, distributed under Boost license 1.0.
// Silly-warning suppression:
#if defined( _MSC_VER )
# define _SCL_SECURE_NO_WARNINGS // Call to 'std::copy' (etc.) may be unsafe.
#endif
#include <stdlib/extension/hopefully_and_fail.hpp>
#include <stdlib/extension/type_builders.hpp>
#include <stdlib/c/math.hpp>
#include <stdlib/c/string.hpp>
#include <stdlib/fstream.hpp>
#include <stdlib/stdexcept.hpp>
#include <stdlib/string.hpp>
#include <stdlib/sstream.hpp>
#include <stdlib/vector.hpp>
//using namespace std; No, Bjarne. No!
namespace ppp {
using std::string;
using std::runtime_error;
using stdlib::ref_;
// Bjarne's functions:
inline STDLIB_NORETURN void error( ref_<const string> message )
{ throw runtime_error( message ); }
inline STDLIB_NORETURN void error( ref_<const string> s1, ref_<const string> s2 )
{ error( s1 + s2 ); }
} // namespace ppp
namespace ppp_ex {
// Functions added here for the same purpose, more convenient:
using namespace stdlib::hopefully_and_fail;
} // namespace ppp_ex
| 28.76 | 85 | 0.713491 | alf-p-steinbach |
4cb8cc2f2fafbcf661fa3390adb2db44bcb77de7 | 1,881 | hpp | C++ | common/utility/inc/DateTimeUtils.hpp | cbtek/SourceGen | 6593300c658529acb06b83982bbc9e698c270aeb | [
"MIT"
] | 1 | 2018-01-23T14:59:28.000Z | 2018-01-23T14:59:28.000Z | common/utility/inc/DateTimeUtils.hpp | cbtek/SourceGen | 6593300c658529acb06b83982bbc9e698c270aeb | [
"MIT"
] | null | null | null | common/utility/inc/DateTimeUtils.hpp | cbtek/SourceGen | 6593300c658529acb06b83982bbc9e698c270aeb | [
"MIT"
] | null | null | null | /**
MIT License
Copyright (c) 2016 cbtek
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.
*/
#ifndef _CBTEK_COMMON_UTILITY_DATETIMEUTILS_HPP_
#define _CBTEK_COMMON_UTILITY_DATETIMEUTILS_HPP_
#include "TimeUtils.hpp"
#include "DateUtils.hpp"
#include "StringUtils.hpp"
namespace cbtek{
namespace common{
namespace utility{
namespace DateTimeUtils{
inline std::string getDisplayTimeStamp()
{
return (DateUtils::toShortDateString(DateUtils::getCurrentDate(),"mm/dd/yyyy")+" at "+StringUtils::toString(TimeUtils::to12HourTimeString(TimeUtils::getCurrentTime())));
}
inline std::string getTimeStamp()
{
return (DateUtils::toShortDateString(DateUtils::getCurrentDate(),"yyyymmdd")+"T"+StringUtils::toString(TimeUtils::getCurrentTime().toTimeInteger())+"."+StringUtils::toString((std::uint64_t)TimeUtils::getMillisecondsNow()));
}
}}}} //namespace
#endif //_CBTEK_COMMON_UTILITY_DATETIMEUTILS_HPP_
| 38.387755 | 227 | 0.796385 | cbtek |
4cba1b6ace6df025d14ed9f7f3236e8504b69af0 | 23,207 | cpp | C++ | PrehistoricEngine/src/engine/prehistoric/core/util/math/Math.cpp | Andrispowq/PrehistoricEngine---C- | 04159c9119b2f5e0148de21a85aa0dab2d6ba60e | [
"Apache-2.0"
] | 1 | 2020-12-04T13:36:03.000Z | 2020-12-04T13:36:03.000Z | PrehistoricEngine/src/engine/prehistoric/core/util/math/Math.cpp | Andrispowq/PrehistoricEngine---C- | 04159c9119b2f5e0148de21a85aa0dab2d6ba60e | [
"Apache-2.0"
] | null | null | null | PrehistoricEngine/src/engine/prehistoric/core/util/math/Math.cpp | Andrispowq/PrehistoricEngine---C- | 04159c9119b2f5e0148de21a85aa0dab2d6ba60e | [
"Apache-2.0"
] | null | null | null | #include "Includes.hpp"
#include "Math.h"
namespace Prehistoric
{
#if defined(PR_FAST_MATH)
inline Vector2f Vector2f::abs() const
{
return Vector2f(fabs((*this).x), fabs((*this).y));
}
Vector2f Vector2f::lerp(const Vector2f& b, const float& t, const bool& invert) const
{
float x_ = x + (b.x - x) * t;
float y_ = y + (b.y - y) * t;
return invert ? Vector2f(y_, x_) : Vector2f(x_, y_);
}
Vector2f Vector2f::lerp(const Vector2f& b, const Vector2f& t, const bool& invert) const
{
float x_ = x + (b.x - x) * t.x;
float y_ = y + (b.y - y) * t.y;
return invert ? Vector2f(y_, x_) : Vector2f(x_, y_);
}
Vector2f Vector2f::swap() const
{
return Vector2f(y, x);
}
inline Vector3f Vector3f::abs() const
{
return Vector3f(std::abs(x), std::abs(y), std::abs(z));
}
Vector3f Vector3f::cross(const Vector3f& v) const
{
float x_ = y * v.z - z * v.y;
float y_ = z * v.x - x * v.z;
float z_ = x * v.y - y * v.x;
return Vector3f(x_, y_, z_);
}
Vector3f Vector3f::reflect(const Vector3f& normal) const
{
return *this - normal * 2 * this->dot(normal);
}
Vector3f Vector3f::refract(const Vector3f& normal, const float& eta) const
{
float k = 1 - std::pow(eta, 2) * (1 - std::pow(this->dot(normal), 2));
if (k < 0)
return Vector3f(0);
else
return *this * eta - normal * (eta * this->dot(normal) + std::sqrt(k));
}
Vector3f Vector3f ::lerp(const Vector3f& b, const float& t) const
{
return _mm_add_ps(_mm_mul_ps(_mm_sub_ps(b.reg, reg), _mm_set_ss(t)), reg);
}
Vector3f Vector3f::lerp(const Vector3f& b, const Vector3f& t) const
{
return _mm_add_ps(_mm_mul_ps(_mm_sub_ps(b.reg, reg), t.reg), reg);
}
Vector3f Vector3f::rotate(const Vector3f& angles) const
{
/*Vector3f rotX = this->rotate(Vector3f(1, 0, 0), angles.x);
Vector3f rotY = this->rotate(Vector3f(0, 1, 0), angles.y);
Vector3f rotZ = this->rotate(Vector3f(0, 0, 1), angles.z);
return rotX + rotY + rotZ - *this * 2;*/
Matrix4f rot = Matrix4f::Rotation(angles);
return (rot * Vector4f(*this, 0)).xyz();
}
Vector3f Vector3f::rotate(const Vector3f& axis, const float& angle) const
{
Vector3f result;
float sinHalfAngle = std::sin(ToRadians(angle / 2));
float cosHalfAngle = std::cos(ToRadians(angle / 2));
float rx = axis.x * sinHalfAngle;
float ry = axis.y * sinHalfAngle;
float rz = axis.z * sinHalfAngle;
float rw = cosHalfAngle;
Quaternionf rotation(rx, ry, rz, rw);
Quaternionf conjugate = rotation.Conjugate();
Quaternionf w = rotation * (*this) * conjugate;
result.x = w.x;
result.y = w.y;
result.z = w.z;
return result;
}
inline Vector4f Vector4f::abs() const
{
return Vector4f(std::abs(x), std::abs(y), std::abs(z), std::abs(w));
}
Vector4f Vector4f::lerp(const Vector4f& b, const float& t) const
{
return _mm_add_ps(_mm_mul_ps(_mm_sub_ps(b.reg, reg), _mm_set_ss(t)), reg);
}
Vector4f Vector4f::lerp(const Vector4f& b, const Vector4f& t) const
{
return _mm_add_ps(_mm_mul_ps(_mm_sub_ps(b.reg, reg), t.reg), reg);
}
Quaternionf Quaternionf::operator*(const Quaternionf& r) const
{
float x_ = x * r.w + w * r.x + y * r.z - z * r.y;
float y_ = y * r.w + w * r.y + z * r.x - x * r.z;
float z_ = z * r.w + w * r.z + x * r.y - y * r.x;
float w_ = w * r.w - x * r.x - y * r.y - z * r.z;
return Quaternionf(x_, y_, z_, w_);
}
Quaternionf Quaternionf::operator*(const Vector4f& r) const
{
float x_ = x * r.w + w * r.x + y * r.z - z * r.y;
float y_ = y * r.w + w * r.y + z * r.x - x * r.z;
float z_ = z * r.w + w * r.z + x * r.y - y * r.x;
float w_ = w * r.w - x * r.x - y * r.y - z * r.z;
return Quaternionf(x_, y_, z_, w_);
}
Quaternionf Quaternionf::operator*(const Vector3f& r) const
{
float x_ = w * r.x + y * r.z - z * r.y;
float y_ = w * r.y + z * r.x - x * r.z;
float z_ = w * r.z + x * r.y - y * r.x;
float w_ = -x * r.x - y * r.y - z * r.z;
return Quaternionf(x_, y_, z_, w_);
}
Quaternionf Quaternionf::operator*=(const Quaternionf& r)
{
float x_ = x * r.w + w * r.x + y * r.z - z * r.y;
float y_ = y * r.w + w * r.y + z * r.x - x * r.z;
float z_ = z * r.w + w * r.z + x * r.y - y * r.x;
float w_ = w * r.w - x * r.x - y * r.y - z * r.z;
this->x = x_;
this->y = y_;
this->z = z_;
this->w = w_;
return *this;
}
Quaternionf Quaternionf::operator*=(const Vector4f& r)
{
float x_ = x * r.w + w * r.x + y * r.z - z * r.y;
float y_ = y * r.w + w * r.y + z * r.x - x * r.z;
float z_ = z * r.w + w * r.z + x * r.y - y * r.x;
float w_ = w * r.w - x * r.x - y * r.y - z * r.z;
this->x = x_;
this->y = y_;
this->z = z_;
this->w = w_;
return *this;
}
Quaternionf Quaternionf::operator*=(const Vector3f& r)
{
float x_ = w * r.x + y * r.z - z * r.y;
float y_ = w * r.y + z * r.x - x * r.z;
float z_ = w * r.z + x * r.y - y * r.x;
float w_ = -x * r.x - y * r.y - z * r.z;
this->x = x_;
this->y = y_;
this->z = z_;
this->w = w_;
return *this;
}
inline Quaternionf Quaternionf::abs() const
{
return Quaternionf(std::abs(x), std::abs(y), std::abs(z), std::abs(w));
}
Quaternionf Quaternionf::lerp(const Quaternionf& b, const float& t) const
{
return _mm_add_ps(_mm_mul_ps(_mm_sub_ps(b.reg, reg), _mm_set_ss(t)), reg);
}
Quaternionf Quaternionf::lerp(const Quaternionf& b, const Quaternionf& t) const
{
return _mm_add_ps(_mm_mul_ps(_mm_sub_ps(b.reg, reg), t.reg), reg);
}
Matrix4f::Matrix4f(const Matrix4f& v)
{
m = new float[4 * 4];
memcpy(this->m, v.m, sizeof(float) * 16);
}
Matrix4f::Matrix4f(Matrix4f&& v) noexcept
{
m = v.m;
v.m = nullptr;
}
Matrix4f::Matrix4f(const Vector4f& v)
{
m = new float[4 * 4];
for (int i = 0; i < 4; i++)
{
m[i * 4 + 0] = v.x;
m[i * 4 + 1] = v.y;
m[i * 4 + 2] = v.z;
m[i * 4 + 3] = v.w;
}
}
Matrix4f::Matrix4f()
{
m = new float[4 * 4];
for (int i = 0; i < 16; i++)
{
m[i] = 0;
}
}
Matrix4f::~Matrix4f()
{
clear();
}
Matrix4f& Matrix4f::operator=(const Matrix4f& v)
{
delete[] m;
this->m = new float[4 * 4];
memcpy(this->m, v.m, sizeof(float) * 16);
return *this;
}
Matrix4f& Matrix4f::operator=(Matrix4f&& v) noexcept
{
this->m = v.m;
v.m = nullptr;
return *this;
}
inline Matrix4f Matrix4f::operator+(const Matrix4f& v) const
{
Matrix4f res;
for (int i = 0; i < 4; i++)
{
res.coloumns[i] = _mm_add_ps(coloumns[i], v.coloumns[i]);
}
return res;
}
inline Matrix4f Matrix4f::operator-(const Matrix4f& v) const
{
Matrix4f res;
for (int i = 0; i < 4; i++)
{
res.coloumns[i] = _mm_sub_ps(coloumns[i], v.coloumns[i]);
}
return res;
}
inline Matrix4f Matrix4f::operator+=(const Matrix4f& v)
{
for (int i = 0; i < 4; i++)
{
coloumns[i] = _mm_add_ps(coloumns[i], v.coloumns[i]);
}
return *this;
}
inline Matrix4f Matrix4f::operator-=(const Matrix4f& v)
{
for (int i = 0; i < 4; i++)
{
coloumns[i] = _mm_sub_ps(coloumns[i], v.coloumns[i]);
}
return *this;
}
inline Matrix4f Matrix4f::operator+(const Vector4f& v) const
{
Matrix4f res;
for (int i = 0; i < 4; i++)
{
res.coloumns[i] = _mm_add_ps(coloumns[i], v.reg);
}
return res;
}
inline Matrix4f Matrix4f::operator-(const Vector4f& v) const
{
Matrix4f res;
for (int i = 0; i < 4; i++)
{
res.coloumns[i] = _mm_sub_ps(coloumns[i], v.reg);
}
return res;
}
inline Matrix4f Matrix4f::operator+=(const Vector4f& v)
{
for (int i = 0; i < 4; i++)
{
coloumns[i] = _mm_add_ps(coloumns[i], v.reg);
}
return *this;
}
inline Matrix4f Matrix4f::operator-=(const Vector4f& v)
{
for (int i = 0; i < 4; i++)
{
coloumns[i] = _mm_sub_ps(coloumns[i], v.reg);
}
return *this;
}
inline Matrix4f Matrix4f::operator+(const float& v) const
{
Matrix4f res;
for (int i = 0; i < 4; i++)
{
res.coloumns[i] = _mm_add_ps(coloumns[i], _mm_set_ps(v, v, v, v));
}
return res;
}
inline Matrix4f Matrix4f::operator-(const float& v) const
{
Matrix4f res;
for (int i = 0; i < 4; i++)
{
res.coloumns[i] = _mm_sub_ps(coloumns[i], _mm_set_ps(v, v, v, v));
}
return res;
}
inline Matrix4f Matrix4f::operator+=(const float& v)
{
for (int i = 0; i < 4; i++)
{
coloumns[i] = _mm_add_ps(coloumns[i], _mm_set_ps(v, v, v, v));
}
return *this;
}
inline Matrix4f Matrix4f::operator-=(const float& v)
{
for (int i = 0; i < 4; i++)
{
coloumns[i] = _mm_sub_ps(coloumns[i], _mm_set_ps(v, v, v, v));
}
return *this;
}
inline Matrix4f Matrix4f::operator*(const Matrix4f& v) const
{
Matrix4f res;
for (int i = 0; i < 4; i++)
{
__m128 res0 = _mm_mul_ps(_mm_set_ps(m[0 * 4 + 3], m[0 * 4 + 2], m[0 * 4 + 1], m[0 * 4 + 0]), _mm_set_ps(v.m[i * 4 + 0], v.m[i * 4 + 0], v.m[i * 4 + 0], v.m[i * 4 + 0]));
__m128 res1 = _mm_mul_ps(_mm_set_ps(m[1 * 4 + 3], m[1 * 4 + 2], m[1 * 4 + 1], m[1 * 4 + 0]), _mm_set_ps(v.m[i * 4 + 1], v.m[i * 4 + 1], v.m[i * 4 + 1], v.m[i * 4 + 1]));
__m128 res2 = _mm_mul_ps(_mm_set_ps(m[2 * 4 + 3], m[2 * 4 + 2], m[2 * 4 + 1], m[2 * 4 + 0]), _mm_set_ps(v.m[i * 4 + 2], v.m[i * 4 + 2], v.m[i * 4 + 2], v.m[i * 4 + 2]));
__m128 res3 = _mm_mul_ps(_mm_set_ps(m[3 * 4 + 3], m[3 * 4 + 2], m[3 * 4 + 1], m[3 * 4 + 0]), _mm_set_ps(v.m[i * 4 + 3], v.m[i * 4 + 3], v.m[i * 4 + 3], v.m[i * 4 + 3]));
res.coloumns[i] = _mm_add_ps(res0, res1);
res.coloumns[i] = _mm_add_ps(res.coloumns[i], res2);
res.coloumns[i] = _mm_add_ps(res.coloumns[i], res3);
}
return res;
}
inline Matrix4f Matrix4f::operator*=(const Matrix4f& v)
{
Matrix4f res;
for (int i = 0; i < 4; i++)
{
__m128 res0 = _mm_mul_ps(_mm_set_ps(m[0 * 4 + 3], m[0 * 4 + 2], m[0 * 4 + 1], m[0 * 4 + 0]), _mm_set_ps(v.m[i * 4 + 0], v.m[i * 4 + 0], v.m[i * 4 + 0], v.m[i * 4 + 0]));
__m128 res1 = _mm_mul_ps(_mm_set_ps(m[1 * 4 + 3], m[1 * 4 + 2], m[1 * 4 + 1], m[1 * 4 + 0]), _mm_set_ps(v.m[i * 4 + 1], v.m[i * 4 + 1], v.m[i * 4 + 1], v.m[i * 4 + 1]));
__m128 res2 = _mm_mul_ps(_mm_set_ps(m[2 * 4 + 3], m[2 * 4 + 2], m[2 * 4 + 1], m[2 * 4 + 0]), _mm_set_ps(v.m[i * 4 + 2], v.m[i * 4 + 2], v.m[i * 4 + 2], v.m[i * 4 + 2]));
__m128 res3 = _mm_mul_ps(_mm_set_ps(m[3 * 4 + 3], m[3 * 4 + 2], m[3 * 4 + 1], m[3 * 4 + 0]), _mm_set_ps(v.m[i * 4 + 3], v.m[i * 4 + 3], v.m[i * 4 + 3], v.m[i * 4 + 3]));
res.coloumns[i] = _mm_add_ps(res0, res1);
res.coloumns[i] = _mm_add_ps(res.coloumns[i], res2);
res.coloumns[i] = _mm_add_ps(res.coloumns[i], res3);
}
for (int i = 0; i < 4; i++)
{
this->coloumns[i] = res.coloumns[i];
}
return *this;
}
Vector4f Matrix4f::operator*(const Vector4f& v) const
{
Vector4f res = Vector4f();
__m128 res0 = _mm_mul_ps(coloumns[0], _mm_set_ps(v.x, v.x, v.x, v.x));
__m128 res1 = _mm_mul_ps(coloumns[1], _mm_set_ps(v.y, v.y, v.y, v.y));
__m128 res2 = _mm_mul_ps(coloumns[2], _mm_set_ps(v.z, v.z, v.z, v.z));
__m128 res3 = _mm_mul_ps(coloumns[3], _mm_set_ps(v.w, v.w, v.w, v.w));
res.reg = _mm_add_ps(res0, res1);
res.reg = _mm_add_ps(res.reg, res2);
res.reg = _mm_add_ps(res.reg, res3);
return res;
}
inline bool Matrix4f::operator==(const Matrix4f& v) const
{
for (int i = 0; i < 4; i++)
{
__m128 res = _mm_cmpeq_ps(coloumns[i], v.coloumns[i]);
if (res.m128_f32[0] != 0 || res.m128_f32[1] != 0 || res.m128_f32[2] != 0 || res.m128_f32[3] != 0)
{
return false;
}
}
return true;
}
std::array<float, 4> Matrix4f::operator[](int index) const
{
std::array<float, 4> arr{};
if (index > 3)
return arr;
for (int i = 0; i < 4; i++)
{
arr[i] = m[index * 4 + i];
}
return arr;
}
Matrix4f Matrix4f::Identity()
{
Matrix4f res;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (i == j)
res.m[i * 4 + j] = 1;
else
res.m[i * 4 + j] = 0;
}
}
return res;
}
Matrix4f Matrix4f::Zero()
{
Matrix4f res;
for (int i = 0; i < 16; i++)
{
res.m[i] = 0;
}
return res;
}
Matrix4f Matrix4f::Translation(const Vector3f& position)
{
Matrix4f res = Matrix4f::Identity();
res.m[3 * 4 + 0] = position.x;
res.m[3 * 4 + 1] = position.y;
res.m[3 * 4 + 2] = position.z;
return res;
}
Matrix4f Matrix4f::Rotation(const Vector3f& rotation)
{
Matrix4f rx = Matrix4f::Identity();
Matrix4f ry = Matrix4f::Identity();
Matrix4f rz = Matrix4f::Identity();
float x = ToRadians(rotation.x);
float y = ToRadians(rotation.y);
float z = ToRadians(rotation.z);
float cosX = cos(x);
float cosY = cos(y);
float cosZ = cos(z);
float sinX = sin(x);
float sinY = sin(y);
float sinZ = sin(z);
rx.m[1 * 4 + 1] = cosX;
rx.m[2 * 4 + 1] = -sinX;
rx.m[1 * 4 + 2] = sinX;
rx.m[2 * 4 + 2] = cosX;
ry.m[0 * 4 + 0] = cosY;
ry.m[2 * 4 + 0] = sinY;
ry.m[0 * 4 + 2] = -sinY;
ry.m[2 * 4 + 2] = cosY;
rz.m[0 * 4 + 0] = cosZ;
rz.m[1 * 4 + 0] = -sinZ;
rz.m[0 * 4 + 1] = sinZ;
rz.m[1 * 4 + 1] = cosZ;
return ry * rx * rz;
}
Matrix4f Matrix4f::Scaling(const Vector3f& scale)
{
Matrix4f res = Matrix4f::Identity();
res.m[0 * 4 + 0] = scale.x;
res.m[1 * 4 + 1] = scale.y;
res.m[2 * 4 + 2] = scale.z;
return res;
}
Matrix4f Matrix4f::Transformation(const Vector3f& translation, const Vector3f& rotation, const Vector3f& scaling)
{
Matrix4f Translation = Matrix4f::Translation(translation);
Matrix4f Rotation = Matrix4f::Rotation(rotation);
Matrix4f Scaling = Matrix4f::Scaling(scaling);
return Translation * Rotation * Scaling;
}
Matrix4f Matrix4f::PerspectiveProjection(const float& fov, const float& aspectRatio, const float& nearPlane, const float& farPlane)
{
Matrix4f res = Matrix4f::Identity();
float tanFOV = tan(ToRadians(fov / 2));
float frustumLength = farPlane - nearPlane;
res.m[0 * 4 + 0] = 1 / (tanFOV * aspectRatio);
res.m[1 * 4 + 1] = 1 / tanFOV;
res.m[2 * 4 + 2] = (farPlane + nearPlane) / frustumLength;
res.m[3 * 4 + 2] = -(2 * farPlane * nearPlane) / frustumLength;
res.m[2 * 4 + 3] = 1;
res.m[3 * 4 + 3] = 0;
return res;
}
Matrix4f Matrix4f::View(const Vector3f& forward, const Vector3f& up)
{
Vector3f right = up.cross(forward);
Matrix4f mat = Matrix4f::Identity();
mat.m[0 * 4 + 0] = right.x;
mat.m[1 * 4 + 0] = right.y;
mat.m[2 * 4 + 0] = right.z;
mat.m[0 * 4 + 1] = up.x;
mat.m[1 * 4 + 1] = up.y;
mat.m[2 * 4 + 1] = up.z;
mat.m[0 * 4 + 2] = forward.x;
mat.m[1 * 4 + 2] = forward.y;
mat.m[2 * 4 + 2] = forward.z;
return mat;
}
/*
The parameter <i> is the index of the row, so to get the first row, the parameter MUST be 0
*/
std::array<float, 4> const Matrix4f::getRow(int i) const
{
std::array<float, 4> arr;
for (int j = 0; j < 4; j++)
{
arr[j] = m[j * 4 + i];
}
return arr;
}
void Matrix4f::clear()
{
delete[] m;
}
#else
Matrix4f::Matrix4f(const Matrix4f& v)
{
m = new float[4 * 4];
memcpy(this->m, v.m, sizeof(float) * 16);
}
Matrix4f::Matrix4f(Matrix4f&& v) noexcept
{
m = v.m;
v.m = nullptr;
}
Matrix4f::Matrix4f(const Vector4f& v)
{
m = new float[4 * 4];
for (int i = 0; i < 4; i++)
{
m[i * 4 + 0] = v.x;
m[i * 4 + 1] = v.y;
m[i * 4 + 2] = v.z;
m[i * 4 + 3] = v.w;
}
}
Matrix4f::Matrix4f()
{
m = new float[4 * 4];
for (int i = 0; i < 16; i++)
{
m[i] = 0;
}
}
Matrix4f::~Matrix4f()
{
clear();
}
Matrix4f& Matrix4f::operator=(const Matrix4f& v)
{
delete[] m;
m = new float[4 * 4];
memcpy(this->m, v.m, sizeof(float) * 16);
return *this;
}
Matrix4f& Matrix4f::operator=(Matrix4f&& v) noexcept
{
m = v.m;
v.m = nullptr;
return *this;
}
inline Matrix4f Matrix4f::operator+(const Matrix4f& v) const
{
Matrix4f res;
for (int i = 0; i < 16; i++)
{
res.m[i] = m[i] + v.m[i];
}
return res;
}
inline Matrix4f Matrix4f::operator-(const Matrix4f& v) const
{
Matrix4f res;
for (int i = 0; i < 16; i++)
{
res.m[i] = m[i] - v.m[i];
}
return res;
}
inline Matrix4f Matrix4f::operator+=(const Matrix4f& v)
{
for (int i = 0; i < 16; i++)
{
this->m[i] = m[i] + v.m[i];
}
return *this;
}
inline Matrix4f Matrix4f::operator-=(const Matrix4f& v)
{
for (int i = 0; i < 16; i++)
{
this->m[i] = m[i] - v.m[i];
}
return *this;
}
inline Matrix4f Matrix4f::operator+(const Vector4f& v) const
{
Matrix4f res;
for (int i = 0; i < 4; i++)
{
res.m[i * 4 + 0] = m[i * 4 + 0] + v.x;
res.m[i * 4 + 1] = m[i * 4 + 1] + v.y;
res.m[i * 4 + 2] = m[i * 4 + 2] + v.z;
res.m[i * 4 + 3] = m[i * 4 + 3] + v.w;
}
return res;
}
inline Matrix4f Matrix4f::operator-(const Vector4f& v) const
{
Matrix4f res;
for (int i = 0; i < 4; i++)
{
res.m[i * 4 + 0] = m[i * 4 + 0] - v.x;
res.m[i * 4 + 1] = m[i * 4 + 1] - v.y;
res.m[i * 4 + 2] = m[i * 4 + 2] - v.z;
res.m[i * 4 + 3] = m[i * 4 + 3] - v.w;
}
return res;
}
inline Matrix4f Matrix4f::operator+=(const Vector4f& v)
{
for (int i = 0; i < 4; i++)
{
m[i * 4 + 0] += v.x;
m[i * 4 + 1] += v.y;
m[i * 4 + 2] += v.z;
m[i * 4 + 3] += v.w;
}
return *this;
}
inline Matrix4f Matrix4f::operator-=(const Vector4f& v)
{
for (int i = 0; i < 4; i++)
{
m[i * 4 + 0] -= v.x;
m[i * 4 + 1] -= v.y;
m[i * 4 + 2] -= v.z;
m[i * 4 + 3] -= v.w;
}
return *this;
}
inline Matrix4f Matrix4f::operator+(const float& v) const
{
Matrix4f res;
for (int i = 0; i < 16; i++)
{
res.m[i] = m[i] + v;
}
return res;
}
inline Matrix4f Matrix4f::operator-(const float& v) const
{
Matrix4f res;
for (int i = 0; i < 16; i++)
{
res.m[i] = m[i] - v;
}
return res;
}
inline Matrix4f Matrix4f::operator+=(const float& v)
{
for (int i = 0; i < 16; i++)
{
this->m[i] += v;
}
return *this;
}
inline Matrix4f Matrix4f::operator-=(const float& v)
{
for (int i = 0; i < 16; i++)
{
this->m[i] -= v;
}
return *this;
}
inline Matrix4f Matrix4f::operator*(const Matrix4f& v) const
{
Matrix4f res;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
//j -> this matrix
//i -> v matrix
res.m[i * 4 + j] = v.m[i * 4 + 0] * m[0 * 4 + j] + v.m[i * 4 + 1] * m[1 * 4 + j] + v.m[i * 4 + 2] * m[2 * 4 + j] + v.m[i * 4 + 3] * m[3 * 4 + j];
}
}
return res;
}
inline Matrix4f Matrix4f::operator*=(const Matrix4f& v)
{
Matrix4f res;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
res.m[i * 4 + j] = v.m[i * 4 + 0] * m[0 * 4 + j] + v.m[i * 4 + 1] * m[1 * 4 + j] + v.m[i * 4 + 2] * m[2 * 4 + j] + v.m[i * 4 + 3] * m[3 * 4 + j];
}
}
for (int i = 0; i < 16; i++)
{
this->m[i] = res.m[i];
}
return *this;
}
Vector4f Matrix4f::operator*(const Vector4f& v) const
{
Vector4f res = Vector4f();
res.x = m[0 * 4 + 0] * v.x + m[1 * 4 + 0] * v.y + m[2 * 4 + 0] * v.z + m[3 * 4 + 0] * v.w;
res.y = m[0 * 4 + 1] * v.x + m[1 * 4 + 1] * v.y + m[2 * 4 + 1] * v.z + m[3 * 4 + 1] * v.w;
res.z = m[0 * 4 + 2] * v.x + m[1 * 4 + 2] * v.y + m[2 * 4 + 2] * v.z + m[3 * 4 + 2] * v.w;
res.w = m[0 * 4 + 3] * v.x + m[1 * 4 + 3] * v.y + m[2 * 4 + 3] * v.z + m[3 * 4 + 3] * v.w;
return res;
}
inline bool Matrix4f::operator==(const Matrix4f& v) const
{
for (int i = 0; i < 16; i++)
{
if (this->m[i] != v.m[i])
{
return false;
}
}
return true;
}
std::array<float, 4> Matrix4f::operator[](int index) const
{
std::array<float, 4> arr;
if (index > 3)
return arr;
for (int i = 0; i < 4; i++)
{
arr[i] = m[index * 4 + i];
}
return arr;
}
Matrix4f Matrix4f::Identity()
{
Matrix4f res;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (i == j)
res.m[i * 4 + j] = 1;
else
res.m[i * 4 + j] = 0;
}
}
return res;
}
Matrix4f Matrix4f::Zero()
{
Matrix4f res;
for (int i = 0; i < 16; i++)
{
res.m[i] = 0;
}
return res;
}
Matrix4f Matrix4f::Translation(const Vector3f& position)
{
Matrix4f res = Matrix4f::Identity();
res.m[3 * 4 + 0] = position.x;
res.m[3 * 4 + 1] = position.y;
res.m[3 * 4 + 2] = position.z;
return res;
}
Matrix4f Matrix4f::Rotation(const Vector3f& rotation)
{
Matrix4f rx = Matrix4f::Identity();
Matrix4f ry = Matrix4f::Identity();
Matrix4f rz = Matrix4f::Identity();
float x = ToRadians(rotation.x);
float y = ToRadians(rotation.y);
float z = ToRadians(rotation.z);
float cosX = cos(x);
float cosY = cos(y);
float cosZ = cos(z);
float sinX = sin(x);
float sinY = sin(y);
float sinZ = sin(z);
rx.m[1 * 4 + 1] = cosX;
rx.m[2 * 4 + 1] = -sinX;
rx.m[1 * 4 + 2] = sinX;
rx.m[2 * 4 + 2] = cosX;
ry.m[0 * 4 + 0] = cosY;
ry.m[2 * 4 + 0] = sinY;
ry.m[0 * 4 + 2] = -sinY;
ry.m[2 * 4 + 2] = cosY;
rz.m[0 * 4 + 0] = cosZ;
rz.m[1 * 4 + 0] = -sinZ;
rz.m[0 * 4 + 1] = sinZ;
rz.m[1 * 4 + 1] = cosZ;
return ry * rx * rz;
}
Matrix4f Matrix4f::Scaling(const Vector3f& scale)
{
Matrix4f res = Matrix4f::Identity();
res.m[0 * 4 + 0] = scale.x;
res.m[1 * 4 + 1] = scale.y;
res.m[2 * 4 + 2] = scale.z;
return res;
}
Matrix4f Matrix4f::Transformation(const Vector3f& translation, const Vector3f& rotation, const Vector3f& scaling)
{
Matrix4f Translation = Matrix4f::Translation(translation);
Matrix4f Rotation = Matrix4f::Rotation(rotation);
Matrix4f Scaling = Matrix4f::Scaling(scaling);
return Translation * Rotation * Scaling;
}
Matrix4f Matrix4f::PerspectiveProjection(const float& fov, const float& aspectRatio, const float& nearPlane, const float& farPlane)
{
Matrix4f res = Matrix4f::Identity();
float tanFOV = tan(ToRadians(fov / 2));
float frustumLength = farPlane - nearPlane;
res.m[0 * 4 + 0] = 1 / (tanFOV * aspectRatio);
res.m[1 * 4 + 1] = 1 / tanFOV;
res.m[2 * 4 + 2] = (farPlane + nearPlane) / frustumLength;
res.m[3 * 4 + 2] = -(2 * farPlane * nearPlane) / frustumLength;
res.m[2 * 4 + 3] = 1;
res.m[3 * 4 + 3] = 0;
return res;
}
Matrix4f Matrix4f::View(const Vector3f& forward, const Vector3f& up)
{
Vector3f right = up.cross(forward);
Matrix4f mat = Matrix4f::Identity();
mat.m[0 * 4 + 0] = right.x;
mat.m[1 * 4 + 0] = right.y;
mat.m[2 * 4 + 0] = right.z;
mat.m[0 * 4 + 1] = up.x;
mat.m[1 * 4 + 1] = up.y;
mat.m[2 * 4 + 1] = up.z;
mat.m[0 * 4 + 2] = forward.x;
mat.m[1 * 4 + 2] = forward.y;
mat.m[2 * 4 + 2] = forward.z;
return mat;
}
/*
The parameter <i> is the index of the row, so to get the first row, the parameter MUST be 0
*/
std::array<float, 4> const Matrix4f::getRow(int i) const
{
std::array<float, 4> arr;
for (int j = 0; j < 4; j++)
{
arr[j] = m[j * 4 + i];
}
return arr;
}
void Matrix4f::clear()
{
delete[] m;
}
#endif
template<typename T>
inline std::ostream& operator<<(std::ostream& os, const Vector2<T>& e)
{
return os << "[ " << e.x << ", " << e.y << " ]";
}
template<typename T>
inline std::ostream& operator<<(std::ostream& os, const Vector3<T>& e)
{
return os << "[ " << e.x << ", " << e.y << ", " << e.z << " ]";
}
template<typename T>
inline std::ostream& operator<<(std::ostream& os, const Vector4<T>& e)
{
return os << "[ " << e.x << ", " << e.y << ", " << e.z << ", " << e.w << " ]";
}
template<typename T>
inline std::ostream& operator<<(std::ostream& os, const Quaternion<T>& e)
{
return os << "[ " << e.x << ", " << e.y << ", " << e.z << ", " << e.w << " ]";
}
inline std::ostream& operator<<(std::ostream& os, const Vector2f& e)
{
return os << "[ " << e.x << ", " << e.y << " ]";
}
inline std::ostream& operator<<(std::ostream& os, const Vector3f& e)
{
return os << "[ " << e.x << ", " << e.y << ", " << e.z << " ]";
}
inline std::ostream& operator<<(std::ostream& os, const Vector4f& e)
{
return os << "[ " << e.x << ", " << e.y << ", " << e.z << ", " << e.w << " ]";
}
inline std::ostream& operator<<(std::ostream& os, const Quaternionf& e)
{
return os << "[ " << e.x << ", " << e.y << ", " << e.z << ", " << e.w << " ]";
}
inline std::ostream& operator<<(std::ostream& os, const Matrix4f& e)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
os << e.m[j * 4 + i];
}
os << '\n';
}
}
};
| 20.250436 | 171 | 0.56009 | Andrispowq |
4cbeb7105b4bbe15fc20c3d2945f03aa263261bc | 1,739 | hpp | C++ | include/goldfish.hpp | bsamseth/Goldfish | c99cb9f2b14bbd04e0c2a9ae32b78e074ff6199b | [
"MIT"
] | 6 | 2019-01-23T03:13:36.000Z | 2020-09-06T09:54:48.000Z | include/goldfish.hpp | bsamseth/Goldfish | c99cb9f2b14bbd04e0c2a9ae32b78e074ff6199b | [
"MIT"
] | 33 | 2015-12-28T08:48:01.000Z | 2019-09-25T11:39:53.000Z | include/goldfish.hpp | bsamseth/Goldfish | c99cb9f2b14bbd04e0c2a9ae32b78e074ff6199b | [
"MIT"
] | 6 | 2018-08-06T14:05:11.000Z | 2022-02-15T01:30:49.000Z | #pragma once
#include "notation.hpp"
#include "protocol.hpp"
#include "search.hpp"
namespace goldfish
{
class Goldfish : public Protocol
{
public:
Goldfish() : search(*this) {}
void run();
void send_best_move(Move best_move, Move ponder_move) final;
void send_status(int current_depth,
int current_max_depth,
uint64_t total_nodes,
uint64_t tb_hits,
Move current_move,
int current_move_number) final;
void send_status(bool force,
int current_depth,
int current_max_depth,
uint64_t total_nodes,
uint64_t tb_hits,
Move current_move,
int current_move_number) final;
void send_move(const RootEntry& entry,
int current_depth,
int current_max_depth,
uint64_t total_nodes,
uint64_t tb_hits) final;
private:
std::chrono::system_clock::time_point start_time;
std::chrono::system_clock::time_point status_start_time;
Search search;
Position current_position = Notation::to_position(Notation::STANDARDPOSITION);
void receive_ready();
void receive_new_game();
void receive_position(std::istringstream& input);
void receive_go(std::istringstream& input);
void receive_ponder_hit();
void receive_stop();
void receive_setoption(std::istringstream& input);
public:
void receive_initialize();
void receive_quit();
void receive_bench();
};
} // namespace goldfish
| 25.202899 | 82 | 0.578493 | bsamseth |
4cbefa89d318676765bdc5bde520032f19fbd707 | 5,123 | cpp | C++ | tests/unit/bf/interpreter_tests.cpp | smacdo/brainfreeze | f60791def994d4861fdae9ee7196c36e434bf56c | [
"MIT",
"BSD-3-Clause"
] | 1 | 2022-03-11T22:17:45.000Z | 2022-03-11T22:17:45.000Z | tests/unit/bf/interpreter_tests.cpp | smacdo/brainfreeze | f60791def994d4861fdae9ee7196c36e434bf56c | [
"MIT",
"BSD-3-Clause"
] | 3 | 2020-04-24T05:04:07.000Z | 2020-04-24T05:07:22.000Z | tests/unit/bf/interpreter_tests.cpp | smacdo/brainfreeze | f60791def994d4861fdae9ee7196c36e434bf56c | [
"MIT",
"BSD-3-Clause"
] | null | null | null | #include "bf/bf.h"
#include "testhelpers.h"
#include <catch2/catch.hpp>
using namespace Brainfreeze;
using namespace Brainfreeze::TestHelpers;
TEST_CASE("empty program runs and does nothing", "[interpreter]")
{
auto app = CreateInterpreter(std::string(""));
app.run();
REQUIRE_THAT(app.instructionPointer(), InstructionPointerIs(0));
REQUIRE_THAT(app.memoryPointer(), MemoryPointerIs(0));
REQUIRE(0u == app.memoryAt(0));
}
TEST_CASE("> increments the memory pointer", "[interpreter]")
{
SECTION("with one increment")
{
auto app = CreateInterpreter(std::string(">"));
app.run();
REQUIRE_THAT(app.memoryPointer(), MemoryPointerIs(1));
REQUIRE(0u == app.memoryAt(0));
}
SECTION("with two increments")
{
auto app = CreateInterpreter(std::string(">>"));
app.run();
REQUIRE_THAT(app.memoryPointer(), MemoryPointerIs(2));
REQUIRE(0u == app.memoryAt(0));
}
}
TEST_CASE("< decrements the memory pointer", "[interpreter]")
{
SECTION("with one decrement after incrementing forward")
{
auto app = CreateInterpreter(std::string(">><"));
app.run();
REQUIRE_THAT(app.memoryPointer(), MemoryPointerIs(1));
REQUIRE(0u == app.memoryAt(0));
}
SECTION("with two decrements after incrementing forward")
{
auto app = CreateInterpreter(std::string(">><<"));
app.run();
REQUIRE_THAT(app.memoryPointer(), MemoryPointerIs(0));
REQUIRE(0u == app.memoryAt(0));
}
}
TEST_CASE("+ increments the value at the memory pointer location", "[interpreter]")
{
SECTION("with one increment")
{
auto app = CreateInterpreter(std::string("+"));
app.run();
REQUIRE_THAT(app.memoryPointer(), MemoryPointerIs(0));
REQUIRE(1u == app.memoryAt(0));
}
SECTION("with two increments")
{
auto app = CreateInterpreter(std::string("++"));
app.run();
REQUIRE_THAT(app.memoryPointer(), MemoryPointerIs(0));
REQUIRE(2u == app.memoryAt(0));
}
SECTION("with one increment at the start and then two in the next cell")
{
auto app = CreateInterpreter(std::string("+>++"));
app.run();
REQUIRE_THAT(app.memoryPointer(), MemoryPointerIs(1));
REQUIRE(1u == app.memoryAt(0));
REQUIRE(2u == app.memoryAt(1));
}
}
TEST_CASE("- decrements the value at the memory pointer location", "[interpreter]")
{
SECTION("with one decrement after first incrementing")
{
auto app = CreateInterpreter(std::string("+++-"));
app.run();
REQUIRE_THAT(app.memoryPointer(), MemoryPointerIs(0));
REQUIRE(2u == app.memoryAt(0));
}
SECTION("with two decrement after first incrementing")
{
auto app = CreateInterpreter(std::string("+++--"));
app.run();
REQUIRE_THAT(app.memoryPointer(), MemoryPointerIs(0));
REQUIRE(1u == app.memoryAt(0));
}
SECTION("with incrementing and then decrementing to zero")
{
auto app = CreateInterpreter(std::string("+-++--"));
app.run();
REQUIRE_THAT(app.memoryPointer(), MemoryPointerIs(0));
REQUIRE(0u == app.memoryAt(0));
}
SECTION("with one decrement at the start and then two in the next cell after incrementing")
{
auto app = CreateInterpreter(std::string("++->++--+-"));
app.run();
REQUIRE_THAT(app.memoryPointer(), MemoryPointerIs(1));
REQUIRE(1u == app.memoryAt(0));
REQUIRE(0u == app.memoryAt(1));
}
}
TEST_CASE(", reads a byte and writes to the current memory location", "[interpreter]")
{
Interpreter::byte_t counter = 42;
auto app = CreateInterpreter(
std::string(",>,"),
[&counter]() { return counter++; },
[](Interpreter::byte_t) {});
app.run();
REQUIRE_THAT(app.memoryPointer(), MemoryPointerIs(1));
REQUIRE(42 == app.memoryAt(0));
REQUIRE(43 == app.memoryAt(1));
}
TEST_CASE(". writes a byte from the current memory location", "[interpreter]")
{
std::vector<Interpreter::byte_t> bytes;
auto app = CreateInterpreter(
std::string("++.>+++++.+"),
[]() { return Interpreter::byte_t{}; },
[&bytes](Interpreter::byte_t v) { bytes.push_back(v); });
app.run();
REQUIRE_THAT(app.memoryPointer(), MemoryPointerIs(1));
REQUIRE(2 == app.memoryAt(0));
REQUIRE(6 == app.memoryAt(1));
REQUIRE(2 == bytes.size());
REQUIRE(2 == bytes[0]);
REQUIRE(5 == bytes[1]);
}
TEST_CASE("[ jumps to ] if current byte is zero", "[interpreter]")
{
auto app = CreateInterpreter(std::string("[++]>+"));
app.run();
REQUIRE_THAT(app.memoryPointer(), MemoryPointerIs(1));
REQUIRE(0 == app.memoryAt(0));
REQUIRE(1 == app.memoryAt(1));
}
TEST_CASE("] jumps to [ if current byte is not zero", "[interpreter]")
{
auto app = CreateInterpreter(std::string("++[-]>+"));
app.run();
REQUIRE_THAT(app.memoryPointer(), MemoryPointerIs(1));
REQUIRE(0 == app.memoryAt(0));
REQUIRE(1 == app.memoryAt(1));
}
| 27.543011 | 95 | 0.604333 | smacdo |
4cc66556f4f481076ebe6cd002c5a3b5fcd28238 | 273 | cpp | C++ | gallery-desktop/src/AlbumListWidget.cpp | buzzcut-s/Q-Gallery | 71d60e3b2b14a125a46032a8cc1f06a98d83361a | [
"MIT"
] | null | null | null | gallery-desktop/src/AlbumListWidget.cpp | buzzcut-s/Q-Gallery | 71d60e3b2b14a125a46032a8cc1f06a98d83361a | [
"MIT"
] | null | null | null | gallery-desktop/src/AlbumListWidget.cpp | buzzcut-s/Q-Gallery | 71d60e3b2b14a125a46032a8cc1f06a98d83361a | [
"MIT"
] | null | null | null | #include "include/AlbumListWidget.h"
#include "ui_AlbumListWidget.h"
AlbumListWidget::AlbumListWidget(QWidget* parent) :
QWidget{parent},
m_ui{new Ui::AlbumListWidget}
{
m_ui->setupUi(this);
}
AlbumListWidget::~AlbumListWidget()
{
delete m_ui;
}
| 17.0625 | 51 | 0.699634 | buzzcut-s |
4ccb8ddddfbcc0b65e2a8866bb80080a23619a1e | 2,249 | cpp | C++ | tests/extension/oneapi_sub_group_mask/sub_group_mask_set_api.cpp | AndreyXRomanov/SYCL-CTS | 9e232c7031c80f28ef55366bcfb7f6e843032b67 | [
"Apache-2.0"
] | null | null | null | tests/extension/oneapi_sub_group_mask/sub_group_mask_set_api.cpp | AndreyXRomanov/SYCL-CTS | 9e232c7031c80f28ef55366bcfb7f6e843032b67 | [
"Apache-2.0"
] | null | null | null | tests/extension/oneapi_sub_group_mask/sub_group_mask_set_api.cpp | AndreyXRomanov/SYCL-CTS | 9e232c7031c80f28ef55366bcfb7f6e843032b67 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
//
// SYCL 2020 Extension Conformance Test
//
// Provides tests to check sub_group_mask set()
//
*******************************************************************************/
#include "sub_group_mask_common.h"
#define TEST_NAME sub_group_mask_set_api
namespace TEST_NAMESPACE {
using namespace sycl_cts;
#ifdef SYCL_EXT_ONEAPI_SUB_GROUP_MASK
struct check_result_set {
bool operator()(sycl::ext::oneapi::sub_group_mask sub_group_mask,
const sycl::sub_group &sub_group) {
// sub_group_mask's size must be in the range between 0 (excluded) and 32
// (included) to rule out UB
if (sub_group_mask.size() > 32 || sub_group_mask.size() == 0) return false;
unsigned long after_set;
sub_group_mask.set();
sub_group_mask.extract_bits(after_set);
// mask off irrelevant bits
unsigned long mask =
ULONG_MAX >> (CHAR_BIT * sizeof(unsigned long) - sub_group_mask.size());
unsigned long all_set = ULONG_MAX & mask;
after_set = after_set & mask;
return after_set == all_set;
}
};
struct check_type_set {
bool operator()(sycl::ext::oneapi::sub_group_mask sub_group_mask) {
return std::is_same<void, decltype(sub_group_mask.set())>::value;
}
};
template <size_t SGSize>
using verification_func_for_even_predicate =
check_mask_api<SGSize, check_result_set, check_type_set, even_predicate,
sycl::ext::oneapi::sub_group_mask>;
#endif // SYCL_EXT_ONEAPI_SUB_GROUP_MASK
/** test sycl::oneapi::sub_group_mask interface
*/
class TEST_NAME : public util::test_base {
public:
/** return information about this test
*/
void get_info(test_base::info &out) const override {
set_test_info(out, TOSTRING(TEST_NAME), TEST_FILE);
}
/** execute the test
*/
void run(util::logger &log) override {
#ifdef SYCL_EXT_ONEAPI_SUB_GROUP_MASK
check_diff_sub_group_sizes<verification_func_for_even_predicate>(log);
#else
log.note("SYCL_EXT_ONEAPI_SUB_GROUP_MASK is not defined, test is skipped");
#endif // SYCL_EXT_ONEAPI_SUB_GROUP_MASK
}
};
// register this test with the test_collection.
util::test_proxy<TEST_NAME> proxy;
} /* namespace TEST_NAMESPACE */
| 31.236111 | 80 | 0.673188 | AndreyXRomanov |
4cd39c2507fa11024c41958727bf88044242228a | 121 | cpp | C++ | TestAsio/TestNetCommon/Test_PacketCommon.cpp | nerv2000/TestAsio | 4c2e7e09211c8708c924c346462e148b18e42565 | [
"MIT"
] | null | null | null | TestAsio/TestNetCommon/Test_PacketCommon.cpp | nerv2000/TestAsio | 4c2e7e09211c8708c924c346462e148b18e42565 | [
"MIT"
] | null | null | null | TestAsio/TestNetCommon/Test_PacketCommon.cpp | nerv2000/TestAsio | 4c2e7e09211c8708c924c346462e148b18e42565 | [
"MIT"
] | null | null | null | #include "Test_PacketCommon.h"
Test_PacketCommon::Test_PacketCommon()
{
}
Test_PacketCommon::~Test_PacketCommon()
{
}
| 11 | 39 | 0.768595 | nerv2000 |
4cd3e5fb8d7f30e39e175f1ec4e8768a69547612 | 107,323 | cxx | C++ | ITSMFT/MFT/MFTbase/AliMFTHeatExchanger.cxx | ktf/AliRoot | 6575f726c8d2b1457e3bded9c9b1bf38e4a02c67 | [
"BSD-3-Clause"
] | null | null | null | ITSMFT/MFT/MFTbase/AliMFTHeatExchanger.cxx | ktf/AliRoot | 6575f726c8d2b1457e3bded9c9b1bf38e4a02c67 | [
"BSD-3-Clause"
] | 2 | 2016-11-25T08:40:56.000Z | 2019-10-11T12:29:29.000Z | ITSMFT/MFT/MFTbase/AliMFTHeatExchanger.cxx | ktf/AliRoot | 6575f726c8d2b1457e3bded9c9b1bf38e4a02c67 | [
"BSD-3-Clause"
] | null | null | null | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// $Id$
//-----------------------------------------------------------------------------
/// \class AliMFTHeatExchanger
///
/// Class building the MFT heat Exchanger
///
// Primary Author: P. Demongodin
// Contact Author Raphael Tieulent <raphael.tieulent@cern.ch>
//-----------------------------------------------------------------------------
#include "TMath.h"
#include "TGeoManager.h"
#include "TGeoCompositeShape.h"
#include "TGeoTube.h"
#include "TGeoBoolNode.h"
#include "AliLog.h"
#include "AliMFTHeatExchanger.h"
#include "TGeoBBox.h"
#include "TGeoVolume.h"
#include "AliMFTGeometry.h"
/// \cond CLASSIMP
ClassImp(AliMFTHeatExchanger);
/// \endcond
//====================================================================================================================================================
AliMFTHeatExchanger::AliMFTHeatExchanger() : TNamed() {
fRWater = 0.1/2.;
fDRPipe = 0.005;
//fHeatExchangerThickness = 1.618; // to get a 13.4 mm thickness for the rohacell... don't implement this value yet! overlapping issue!
fHeatExchangerThickness = 1.4; // initial value
fCarbonThickness = (0.0290)/2.; // total thickness of the carbon plate
InitParameters();
}
//====================================================================================================================================================
AliMFTHeatExchanger::AliMFTHeatExchanger(Double_t rWater,
Double_t dRPipe,
Double_t heatExchangerThickness,
Double_t carbonThickness) : TNamed() {
fRWater = rWater;
fDRPipe = dRPipe;
fHeatExchangerThickness = heatExchangerThickness;
fCarbonThickness = carbonThickness;
InitParameters();
}
//====================================================================================================================================================
TGeoVolumeAssembly* AliMFTHeatExchanger::Create(Int_t half, Int_t disk) {
AliInfo(Form("Creating HeatExchanger_%d_%d", disk, half));
fHalfDisk = new TGeoVolumeAssembly(Form("HeatExchanger_%d_%d", disk, half));
switch (disk) {
case 0: CreateHalfDisk0(half);
break;
case 1: CreateHalfDisk1(half);
break;
case 2: CreateHalfDisk2(half);
break;
case 3: CreateHalfDisk3(half);
break;
case 4: CreateHalfDisk4(half);
break;
}
return fHalfDisk;
}
//====================================================================================================================================================
void AliMFTHeatExchanger::CreateHalfDisk0(Int_t half) {
Int_t disk = 0;
if (half == kTop) printf("Creating MFT heat exchanger for disk0 top\n");
else if (half == kBottom) printf("Creating MFT heat exchanger for disk0 bottom\n");
else printf("No valid option for MFT heat exchanger on disk0\n");
//TGeoMedium *carbon = gGeoManager->GetMedium("MFT_Carbon$");
TGeoMedium *carbon = gGeoManager->GetMedium("MFT_CarbonFiber$");
TGeoMedium *water = gGeoManager->GetMedium("MFT_Water$");
TGeoMedium *rohacell = gGeoManager->GetMedium("MFT_Rohacell");
TGeoMedium *pipe = gGeoManager->GetMedium("MFT_Polyimide");
TGeoVolumeAssembly *cooling = new TGeoVolumeAssembly(Form("cooling_D0_H%d",half));
Float_t lMiddle = fSupportXDimensions[disk][0] - 2.*fLWater; // length of central part
TGeoTranslation *translation = 0;
TGeoRotation *rotation = 0;
TGeoCombiTrans *transformation = 0;
TGeoCombiTrans *transformation1 = 0;
TGeoCombiTrans *transformation2 = 0;
// **************************************** Water part ****************************************
// ------------------- Tube shape -------------------
TGeoVolume *waterTube1 = gGeoManager->MakeTube(Form("waterTube1_D0_H%d",half), water, 0., fRWater, fLWater/2.);
waterTube1->SetLineColor(kBlue);
for (Int_t itube=0; itube<3; itube++) {
translation = new TGeoTranslation(fXPosition0[itube], 0., fLWater/2. + lMiddle/2.);
cooling->AddNode (waterTube1, itube, translation);
translation = new TGeoTranslation(fXPosition0[itube], 0., -fLWater/2. - lMiddle/2.);
cooling->AddNode (waterTube1, itube+3, translation);
}
Double_t angle0rad = fangle0*(TMath::DegToRad());
TGeoVolume *waterTube2 = gGeoManager->MakeTube(Form("waterTube2_D0_H%d",half), water, 0., fRWater, fLpartial0/2.);
waterTube2->SetLineColor(kBlue);
for (Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", -90., -fangle0, 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) +
(fLpartial0/2.)*(TMath::Sin(angle0rad)), 0., - lMiddle/2. +
fradius0*(TMath::Sin(angle0rad)) + (fLpartial0/2.)*TMath::Cos(angle0rad), rotation);
cooling->AddNode (waterTube2, itube, transformation);
rotation = new TGeoRotation ("rotation", -90., fangle0, 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) +
(fLpartial0/2.)*(TMath::Sin(angle0rad)), 0., lMiddle/2. -
fradius0*(TMath::Sin(angle0rad)) - (fLpartial0/2.)*TMath::Cos(angle0rad), rotation);
cooling->AddNode (waterTube2, itube+3, transformation);
}
// ------------------- Torus shape -------------------
// Sides torus
TGeoVolume *waterTorus1 = gGeoManager->MakeTorus(Form("waterTorus1_D0_H%d",half), water, fradius0, 0., fRWater, 0., fangle0);
waterTorus1->SetLineColor(kBlue);
Double_t radius0mid = (lMiddle - 2.*(fradius0*(TMath::Sin(angle0rad)) + fLpartial0*(TMath::Cos(angle0rad))))/(2*(TMath::Sin(angle0rad)));
for (Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fradius0 + fXPosition0[itube], 0., - lMiddle/2., rotation);
cooling->AddNode (waterTorus1, itube, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 0.);
transformation = new TGeoCombiTrans(fradius0 + fXPosition0[itube], 0., lMiddle/2., rotation);
cooling->AddNode (waterTorus1, itube+3, transformation);
}
// Central Torus
TGeoVolume *waterTorus2 = gGeoManager->MakeTorus(Form("waterTorus2_D0_H%d",half), water, radius0mid, 0., fRWater, - fangle0 , 2.*fangle0);
waterTorus2->SetLineColor(kBlue);
for(Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", 0., 90., 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) + fLpartial0*TMath::Sin(angle0rad) - radius0mid*TMath::Cos(angle0rad), 0., 0., rotation);
cooling->AddNode (waterTorus2, itube, transformation);
}
// **************************************** Pipe part ****************************************
// ------------------- Tube shape -------------------
TGeoVolume *pipeTube1 = gGeoManager->MakeTube(Form("pipeTube1_D0_H%d",half), pipe, fRWater, fRWater + fDRPipe, fLWater/2.);
pipeTube1->SetLineColor(10);
for (Int_t itube=0; itube<3; itube++){
translation = new TGeoTranslation(fXPosition0[itube], 0., fLWater/2. + lMiddle/2.);
cooling->AddNode (pipeTube1, itube, translation);
translation = new TGeoTranslation(fXPosition0[itube], 0., -fLWater/2. - lMiddle/2.);
cooling->AddNode (pipeTube1, itube+3, translation);
}
TGeoVolume *pipeTube2 = gGeoManager->MakeTube(Form("pipeTube2_D0_H%d",half), pipe, fRWater, fRWater + fDRPipe, fLpartial0/2.);
waterTube2->SetLineColor(10);
for(Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", -90., -fangle0, 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) +
(fLpartial0/2.)*(TMath::Sin(angle0rad)), 0., - lMiddle/2. +
fradius0*(TMath::Sin(angle0rad)) + (fLpartial0/2.)*TMath::Cos(angle0rad), rotation);
cooling->AddNode (pipeTube2, itube, transformation);
rotation = new TGeoRotation ("rotation", -90., fangle0, 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) +
(fLpartial0/2.)*(TMath::Sin(angle0rad)), 0., lMiddle/2. -
fradius0*(TMath::Sin(angle0rad)) - (fLpartial0/2.)*TMath::Cos(angle0rad), rotation);
cooling->AddNode (pipeTube2, itube+3, transformation);
}
// ------------------- Torus shape -------------------
// Sides Torus
TGeoVolume *pipeTorus1 = gGeoManager->MakeTorus(Form("pipeTorus1_D0_H%d",half), pipe, fradius0, fRWater, fRWater + fDRPipe, 0., fangle0);
pipeTorus1->SetLineColor(10);
for (Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fradius0 + fXPosition0[itube], 0., - lMiddle/2., rotation);
cooling->AddNode (pipeTorus1, itube, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 0.);
transformation = new TGeoCombiTrans(fradius0 + fXPosition0[itube], 0., lMiddle/2., rotation);
cooling->AddNode (pipeTorus1, itube+3, transformation);
}
// Central Torus
TGeoVolume *pipeTorus2 = gGeoManager->MakeTorus(Form("pipeTorus2_D0_H%d",half), pipe, radius0mid, fRWater, fRWater + fDRPipe, - fangle0 , 2.*fangle0);
pipeTorus2->SetLineColor(10);
for(Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", 0., 90., 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) + fLpartial0*TMath::Sin(angle0rad) - radius0mid*TMath::Cos(angle0rad), 0., 0., rotation);
cooling->AddNode (pipeTorus2, itube, transformation);
}
Double_t deltaz = fHeatExchangerThickness - fCarbonThickness*2; // distance between pair of carbon plates
// if (half == kTop) {
// rotation = new TGeoRotation ("rotation", 90., 90., 0.);
// transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] + deltaz/2. - fCarbonThickness - fRWater - fDRPipe, rotation);
// fHalfDisk->AddNode(cooling, 1, transformation);
// transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] - deltaz/2. + fCarbonThickness + fRWater + fDRPipe, rotation);
// fHalfDisk->AddNode(cooling, 2, transformation);
// }
// else if (half == kBottom) {
rotation = new TGeoRotation ("rotation", -90., 90., 0.);
transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] + deltaz/2. - fCarbonThickness - fRWater - fDRPipe, rotation);
fHalfDisk->AddNode(cooling, 3, transformation);
transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] - deltaz/2. + fCarbonThickness + fRWater + fDRPipe, rotation);
fHalfDisk->AddNode(cooling, 4, transformation);
// }
// **************************************** Carbon Plates ****************************************
TGeoVolumeAssembly *carbonPlate = new TGeoVolumeAssembly(Form("carbonPlate_D0_H%d",half));
TGeoBBox *carbonBase0 = new TGeoBBox (Form("carbonBase0_D0_H%d",half), (fSupportXDimensions[disk][0])/2., (fSupportYDimensions[disk][0])/2., fCarbonThickness);
TGeoTranslation *t01= new TGeoTranslation ("t01",0., (fSupportYDimensions[disk][0])/2. + fHalfDiskGap , 0.);
t01-> RegisterYourself();
TGeoTubeSeg *holeCarbon0 = new TGeoTubeSeg(Form("holeCarbon0_D0_H%d",half), 0., fRMin[disk], fCarbonThickness + 0.000001, 0, 180.);
TGeoTranslation *t02= new TGeoTranslation ("t02",0., - fHalfDiskGap , 0.);
t02-> RegisterYourself();
///TGeoCompositeShape *cs0 = new TGeoCompositeShape(Form("cs0_D0_H%d",half), Form("(carbonBase0_D0_H%d:t01)-(holeCarbon0_D0_H%d:t02)",half,half));
TGeoSubtraction *carbonhole0 = new TGeoSubtraction(carbonBase0, holeCarbon0, t01, t02);
TGeoCompositeShape *ch0 = new TGeoCompositeShape(Form("Carbon0_D0_H%d",half), carbonhole0);
TGeoVolume *carbonBaseWithHole0 = new TGeoVolume(Form("carbonBaseWithHole_D0_H%d", half), ch0, carbon);
carbonBaseWithHole0->SetLineColor(kGray+3);
rotation = new TGeoRotation ("rotation", 0., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., 0., rotation);
carbonPlate->AddNode(carbonBaseWithHole0, 0, new TGeoTranslation(0., 0., fZPlan[disk]));
Double_t ty = fSupportYDimensions[disk][0];
for (Int_t ipart=1; ipart<fnPart[disk]; ipart ++) {
ty += fSupportYDimensions[disk][ipart]/2.;
TGeoVolume *partCarbon = gGeoManager->MakeBox(Form("partCarbon_D0_H%d_%d", half,ipart), carbon, fSupportXDimensions[disk][ipart]/2., fSupportYDimensions[disk][ipart]/2., fCarbonThickness);
partCarbon->SetLineColor(kGray+3);
TGeoTranslation *t = new TGeoTranslation ("t", 0, ty + fHalfDiskGap, fZPlan[disk]);
carbonPlate -> AddNode(partCarbon, ipart, t);
ty += fSupportYDimensions[disk][ipart]/2.;
}
// if (half == kTop) {
// rotation = new TGeoRotation ("rotation", 0., 0., 0.);
// transformation = new TGeoCombiTrans(0., 0., deltaz/2., rotation);
// fHalfDisk->AddNode(carbonPlate, 1, transformation);
// transformation = new TGeoCombiTrans(0., 0., -deltaz/2., rotation);
// fHalfDisk->AddNode(carbonPlate, 2, transformation);
// }
// else if (half == kBottom) {
rotation = new TGeoRotation ("rotation", 180., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., deltaz/2., rotation);
fHalfDisk->AddNode(carbonPlate, 3, transformation);
transformation = new TGeoCombiTrans(0., 0., -deltaz/2., rotation);
fHalfDisk->AddNode(carbonPlate, 4, transformation);
// }
// **************************************** Rohacell Plate ****************************************
TGeoVolumeAssembly *rohacellPlate = new TGeoVolumeAssembly(Form("rohacellPlate_D0_H%d",half));
TGeoBBox *rohacellBase0 = new TGeoBBox (Form("rohacellBase0_D0_H%d",half), (fSupportXDimensions[disk][0])/2., (fSupportYDimensions[disk][0])/2., fRohacellThickness);
// TGeoTranslation *t3 = new TGeoTranslation ("t3",0., (fSupportYDimensions[disk][0])/2. + fHalfDiskGap , 0.);
// t3 -> RegisterYourself();
TGeoTubeSeg *holeRohacell0 = new TGeoTubeSeg(Form("holeRohacell0_D0_H%d",half), 0., fRMin[disk], fRohacellThickness + 0.000001, 0, 180.);
// TGeoTranslation *t4= new TGeoTranslation ("t4", 0., - fHalfDiskGap , 0.);
// t4-> RegisterYourself();
///cs0 = new TGeoCompositeShape("cs0", Form("(rohacellBase0_D0_H%d:t01)-(holeRohacell0_D0_H%d:t02)",half,half));
TGeoSubtraction *rohacellhole0 = new TGeoSubtraction(rohacellBase0, holeRohacell0, t01, t02);
TGeoCompositeShape *rh0 = new TGeoCompositeShape(Form("rohacellBase0_D0_H%d",half), rohacellhole0);
TGeoVolume *rohacellBaseWithHole = new TGeoVolume(Form("rohacellBaseWithHole_D0_H%d",half), rh0, rohacell);
rohacellBaseWithHole->SetLineColor(kGray);
rotation = new TGeoRotation ("rotation", 0., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., 0., rotation);
rohacellPlate -> AddNode(rohacellBaseWithHole, 0, new TGeoTranslation(0., 0., fZPlan[disk]));
ty = fSupportYDimensions[disk][0];
for (Int_t ipart=1; ipart<fnPart[disk]; ipart ++) {
ty += fSupportYDimensions[disk][ipart]/2.;
TGeoVolume *partRohacell = gGeoManager->MakeBox(Form("partRohacelli_D0_H%d_%d", half,ipart), rohacell, fSupportXDimensions[disk][ipart]/2., fSupportYDimensions[disk][ipart]/2., fRohacellThickness);
partRohacell->SetLineColor(kGray);
TGeoTranslation *t = new TGeoTranslation ("t", 0, ty + fHalfDiskGap, fZPlan[disk]);
rohacellPlate -> AddNode(partRohacell, ipart, t);
ty += fSupportYDimensions[disk][ipart]/2.;
}
// if (half == kTop) {
// rotation = new TGeoRotation ("rotation", 0., 0., 0.);
// transformation = new TGeoCombiTrans(0., 0., 0., rotation);
// fHalfDisk->AddNode(rohacellPlate, 1, transformation);
// }
// if (half == kBottom) {
rotation = new TGeoRotation ("rotation", 180., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., 0., rotation);
fHalfDisk->AddNode(rohacellPlate, 1, transformation);
// }
// **************************************** Manyfolds right and left, fm ****************************************
/*
Double_t deltay = 0.2; // ecart par rapport au plan median du MFT
Double_t mfX = 2.2; // largeur
Double_t mfY = 6.8; // hauteur
Double_t mfZ = 1.7; // epaisseur
TGeoMedium *kMedPeek = gGeoManager->GetMedium("MFT_PEEK$");
TGeoBBox *boxmanyfold = new TGeoBBox("boxmanyfold", mfX/2, mfY/2, mfZ/2);
TGeoBBox *remove = new TGeoBBox("remove", 0.45/2 + AliMFTGeometry::kEpsilon, mfY/2 + AliMFTGeometry::kEpsilon, 0.6/2 + AliMFTGeometry::kEpsilon);
TGeoTranslation *tL= new TGeoTranslation ("tL", mfX/2-0.45/2, 0., -mfZ/2+0.6/2);
TGeoSubtraction *boxManyFold = new TGeoSubtraction(boxmanyfold, remove, NULL, tL);
TGeoCompositeShape *BoxManyFold = new TGeoCompositeShape("BoxManyFold", boxManyFold);
TGeoTranslation *tR= new TGeoTranslation ("tR", -mfX/2+0.45/2, 0., -mfZ/2+0.6/2);
TGeoSubtraction *boxManyFold1 = new TGeoSubtraction(BoxManyFold, remove, NULL, tR);
TGeoCompositeShape *BoxManyFold1 = new TGeoCompositeShape("BoxManyFold1", boxManyFold1);
TGeoVolume *MF1 = new TGeoVolume("MF1", BoxManyFold1, kMedPeek);
rotation = new TGeoRotation ("rotation", 90., 90., 90.);
transformation1 = new TGeoCombiTrans(fSupportXDimensions[disk][0]/2+mfZ/2, mfY/2+deltay, fZPlan[disk], rotation);
fHalfDisk->AddNode(MF1, 1, transformation1);
TGeoVolume *MF2 = new TGeoVolume("MF2", BoxManyFold1, kMedPeek);
transformation2 = new TGeoCombiTrans(fSupportXDimensions[disk][0]/2+mfZ/2, -mfY/2-deltay, fZPlan[disk], rotation);
fHalfDisk->AddNode(MF2, 1, transformation2);
*/
// ********************************************************************************************************
}
//====================================================================================================================================================
void AliMFTHeatExchanger::CreateHalfDisk1(Int_t half) {
Int_t disk = 1;
if (half == kTop) printf("Creating MFT heat exchanger for disk1 top\n");
else if (half == kBottom) printf("Creating MFT heat exchanger for disk1 bottom\n");
else printf("No valid option for MFT heat exchanger on disk1\n");
//TGeoMedium *carbon = gGeoManager->GetMedium("MFT_Carbon$");
TGeoMedium *carbon = gGeoManager->GetMedium("MFT_CarbonFiber$");
TGeoMedium *water = gGeoManager->GetMedium("MFT_Water$");
TGeoMedium *rohacell = gGeoManager->GetMedium("MFT_Rohacell");
TGeoMedium *pipe = gGeoManager->GetMedium("MFT_Polyimide");
TGeoVolumeAssembly *cooling = new TGeoVolumeAssembly(Form("cooling_D1_H%d",half));
Float_t lMiddle = fSupportXDimensions[disk][0] - 2.*fLWater; // length of central part
TGeoTranslation *translation = 0;
TGeoRotation *rotation = 0;
TGeoCombiTrans *transformation = 0;
// **************************************** Water part ****************************************
// ------------------- Tube shape -------------------
TGeoVolume *waterTube1 = gGeoManager->MakeTube(Form("waterTube1_D1_H%d",half), water, 0., fRWater, fLWater/2.);
waterTube1->SetLineColor(kBlue);
for (Int_t itube=0; itube<3; itube++) {
translation = new TGeoTranslation(fXPosition0[itube], 0., fLWater/2. + lMiddle/2.);
cooling->AddNode (waterTube1, itube, translation);
translation = new TGeoTranslation(fXPosition0[itube], 0., -fLWater/2. - lMiddle/2.);
cooling->AddNode (waterTube1, itube+3, translation);
}
Double_t angle0rad = fangle0*(TMath::DegToRad());
TGeoVolume *waterTube2 = gGeoManager->MakeTube(Form("waterTube2_D1_H%d",half), water, 0., fRWater, fLpartial0/2.);
waterTube2->SetLineColor(kBlue);
for (Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", -90., -fangle0, 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) +
(fLpartial0/2.)*(TMath::Sin(angle0rad)), 0., - lMiddle/2. +
fradius0*(TMath::Sin(angle0rad)) + (fLpartial0/2.)*TMath::Cos(angle0rad), rotation);
cooling->AddNode (waterTube2, itube, transformation);
rotation = new TGeoRotation ("rotation", -90., fangle0, 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) +
(fLpartial0/2.)*(TMath::Sin(angle0rad)), 0., lMiddle/2. -
fradius0*(TMath::Sin(angle0rad)) - (fLpartial0/2.)*TMath::Cos(angle0rad), rotation);
cooling->AddNode (waterTube2, itube+3, transformation);
}
// ------------------- Torus shape -------------------
// Sides torus
TGeoVolume *waterTorus1 = gGeoManager->MakeTorus(Form("waterTorus1_D1_H%d",half), water, fradius0, 0., fRWater, 0., fangle0);
waterTorus1->SetLineColor(kBlue);
Double_t radius0mid = (lMiddle - 2.*(fradius0*(TMath::Sin(angle0rad)) + fLpartial0*(TMath::Cos(angle0rad))))/(2*(TMath::Sin(angle0rad)));
for (Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fradius0 + fXPosition0[itube], 0., - lMiddle/2., rotation);
cooling->AddNode (waterTorus1, itube, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 0.);
transformation = new TGeoCombiTrans(fradius0 + fXPosition0[itube], 0., lMiddle/2., rotation);
cooling->AddNode (waterTorus1, itube+3, transformation);
}
// Central Torus
TGeoVolume *waterTorus2 = gGeoManager->MakeTorus(Form("waterTorus2_D1_H%d",half), water, radius0mid, 0., fRWater, - fangle0 , 2.*fangle0);
waterTorus2->SetLineColor(kBlue);
for(Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", 0., 90., 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) + fLpartial0*TMath::Sin(angle0rad) - radius0mid*TMath::Cos(angle0rad), 0., 0., rotation);
cooling->AddNode (waterTorus2, itube, transformation);
}
// **************************************** Pipe part ****************************************
// ------------------- Tube shape -------------------
TGeoVolume *pipeTube1 = gGeoManager->MakeTube(Form("pipeTube1_D1_H%d",half), pipe, fRWater, fRWater + fDRPipe, fLWater/2.);
pipeTube1->SetLineColor(10);
for (Int_t itube=0; itube<3; itube++){
translation = new TGeoTranslation(fXPosition0[itube], 0., fLWater/2. + lMiddle/2.);
cooling->AddNode (pipeTube1, itube, translation);
translation = new TGeoTranslation(fXPosition0[itube], 0., -fLWater/2. - lMiddle/2.);
cooling->AddNode (pipeTube1, itube+3, translation);
}
TGeoVolume *pipeTube2 = gGeoManager->MakeTube(Form("pipeTube2_D1_H%d",half), pipe, fRWater, fRWater + fDRPipe, fLpartial0/2.);
waterTube2->SetLineColor(10);
for(Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", -90., -fangle0, 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) +
(fLpartial0/2.)*(TMath::Sin(angle0rad)), 0., - lMiddle/2. +
fradius0*(TMath::Sin(angle0rad)) + (fLpartial0/2.)*TMath::Cos(angle0rad), rotation);
cooling->AddNode (pipeTube2, itube, transformation);
rotation = new TGeoRotation ("rotation", -90., fangle0, 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) +
(fLpartial0/2.)*(TMath::Sin(angle0rad)), 0., lMiddle/2. -
fradius0*(TMath::Sin(angle0rad)) - (fLpartial0/2.)*TMath::Cos(angle0rad), rotation);
cooling->AddNode (pipeTube2, itube+3, transformation);
}
// ------------------- Torus shape -------------------
// Sides Torus
TGeoVolume *pipeTorus1 = gGeoManager->MakeTorus(Form("pipeTorus1_D1_H%d",half), pipe, fradius0, fRWater, fRWater + fDRPipe, 0., fangle0);
pipeTorus1->SetLineColor(10);
for (Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fradius0 + fXPosition0[itube], 0., - lMiddle/2., rotation);
cooling->AddNode (pipeTorus1, itube, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 0.);
transformation = new TGeoCombiTrans(fradius0 + fXPosition0[itube], 0., lMiddle/2., rotation);
cooling->AddNode (pipeTorus1, itube+3, transformation);
}
// Central Torus
TGeoVolume *pipeTorus2 = gGeoManager->MakeTorus(Form("pipeTorus2_D1_H%d",half), pipe, radius0mid, fRWater, fRWater + fDRPipe, - fangle0 , 2.*fangle0);
pipeTorus2->SetLineColor(10);
for(Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", 0., 90., 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) + fLpartial0*TMath::Sin(angle0rad) - radius0mid*TMath::Cos(angle0rad), 0., 0., rotation);
cooling->AddNode (pipeTorus2, itube, transformation);
}
Double_t deltaz = fHeatExchangerThickness - fCarbonThickness*2; // distance between pair of carbon plates
// if (half == kTop) {
// rotation = new TGeoRotation ("rotation", 90., 90., 0.);
// transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] + deltaz/2. - fCarbonThickness - fRWater - fDRPipe, rotation);
// fHalfDisk->AddNode(cooling, 1, transformation);
// transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] - deltaz/2. + fCarbonThickness + fRWater + fDRPipe, rotation);
// fHalfDisk->AddNode(cooling, 2, transformation);
// }
// else if (half == kBottom) {
rotation = new TGeoRotation ("rotation", -90., 90., 0.);
transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] + deltaz/2. - fCarbonThickness - fRWater - fDRPipe, rotation);
fHalfDisk->AddNode(cooling, 0, transformation);
transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] - deltaz/2. + fCarbonThickness + fRWater + fDRPipe, rotation);
fHalfDisk->AddNode(cooling, 1, transformation);
// }
// **************************************** Carbon Plates ****************************************
TGeoVolumeAssembly *carbonPlate = new TGeoVolumeAssembly(Form("carbonPlate_D1_H%d",half));
TGeoBBox *carbonBase1 = new TGeoBBox (Form("carbonBase1_D1_H%d",half), (fSupportXDimensions[disk][0])/2., (fSupportYDimensions[disk][0])/2., fCarbonThickness);
TGeoTranslation *t11= new TGeoTranslation ("t11",0., (fSupportYDimensions[disk][0])/2. + fHalfDiskGap , 0.);
t11-> RegisterYourself();
TGeoTubeSeg *holeCarbon1 = new TGeoTubeSeg(Form("holeCarbon1_D1_H%d",half), 0., fRMin[disk], fCarbonThickness + 0.000001, 0, 180.);
TGeoTranslation *t12= new TGeoTranslation ("t12",0., - fHalfDiskGap , 0.);
t12-> RegisterYourself();
////TGeoCompositeShape *cs1 = new TGeoCompositeShape(Form("Carbon1_D1_H%d",half), Form("(carbonBase1_D1_H%d:t11)-(holeCarbon1_D1_H%d:t12)",half,half));
TGeoSubtraction *carbonhole1 = new TGeoSubtraction(carbonBase1, holeCarbon1, t11, t12);
TGeoCompositeShape *ch1 = new TGeoCompositeShape(Form("Carbon1_D1_H%d",half), carbonhole1);
TGeoVolume *carbonBaseWithHole1 = new TGeoVolume(Form("carbonBaseWithHole_D1_H%d",half), ch1, carbon);
carbonBaseWithHole1->SetLineColor(kGray+3);
rotation = new TGeoRotation ("rotation", 0., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., 0., rotation);
carbonPlate->AddNode(carbonBaseWithHole1, 0, new TGeoTranslation(0., 0., fZPlan[disk]));
Double_t ty = fSupportYDimensions[disk][0];
for (Int_t ipart=1; ipart<fnPart[disk]; ipart ++) {
ty += fSupportYDimensions[disk][ipart]/2.;
TGeoVolume *partCarbon = gGeoManager->MakeBox(Form("partCarbon_D1_H%d_%d", half,ipart), carbon, fSupportXDimensions[disk][ipart]/2.,
fSupportYDimensions[disk][ipart]/2., fCarbonThickness);
partCarbon->SetLineColor(kGray+3);
TGeoTranslation *t = new TGeoTranslation ("t", 0, ty + fHalfDiskGap, fZPlan[disk]);
carbonPlate -> AddNode(partCarbon, ipart, t);
ty += fSupportYDimensions[disk][ipart]/2.;
}
// if (half == kTop) {
// rotation = new TGeoRotation ("rotation", 0., 0., 0.);
// transformation = new TGeoCombiTrans(0., 0., deltaz/2., rotation);
// fHalfDisk->AddNode(carbonPlate, 1, transformation);
// transformation = new TGeoCombiTrans(0., 0., -deltaz/2., rotation);
// fHalfDisk->AddNode(carbonPlate, 2, transformation);
// }
// else if (half == kBottom) {
rotation = new TGeoRotation ("rotation", 180., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., deltaz/2., rotation);
fHalfDisk->AddNode(carbonPlate, 0, transformation);
transformation = new TGeoCombiTrans(0., 0., -deltaz/2., rotation);
fHalfDisk->AddNode(carbonPlate, 1, transformation);
// }
// **************************************** Rohacell Plate ****************************************
TGeoVolumeAssembly *rohacellPlate = new TGeoVolumeAssembly(Form("rohacellPlate_D1_H%d",half));
TGeoBBox *rohacellBase1 = new TGeoBBox ("rohacellBase1", (fSupportXDimensions[disk][0])/2., (fSupportYDimensions[disk][0])/2., fRohacellThickness);
// TGeoTranslation *t3 = new TGeoTranslation ("t3",0., (fSupportYDimensions[disk][0])/2. + fHalfDiskGap , 0.);
// t3 -> RegisterYourself();
TGeoTubeSeg *holeRohacell1 = new TGeoTubeSeg("holeRohacell1", 0., fRMin[disk], fRohacellThickness + 0.000001, 0, 180.);
// TGeoTranslation *t4= new TGeoTranslation ("t4", 0., - fHalfDiskGap , 0.);
// t4-> RegisterYourself();
//////cs1 = new TGeoCompositeShape(Form("rohacell_D1_H%d",half), "(rohacellBase1:t11)-(holeRohacell1:t12)");
TGeoSubtraction *rohacellhole1 = new TGeoSubtraction(rohacellBase1, holeRohacell1, t11, t12);
TGeoCompositeShape *rh1 = new TGeoCompositeShape(Form("rohacellBase1_D1_H%d",half), rohacellhole1);
TGeoVolume *rohacellBaseWithHole = new TGeoVolume(Form("rohacellBaseWithHole_D1_H%d",half), rh1, rohacell);
rohacellBaseWithHole->SetLineColor(kGray);
rotation = new TGeoRotation ("rotation", 0., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., 0., rotation);
rohacellPlate -> AddNode(rohacellBaseWithHole, 0, new TGeoTranslation(0., 0., fZPlan[disk]));
ty = fSupportYDimensions[disk][0];
for (Int_t ipart=1; ipart<fnPart[disk]; ipart ++) {
ty += fSupportYDimensions[disk][ipart]/2.;
TGeoVolume *partRohacell = gGeoManager->MakeBox(Form("partRohacelli_D1_H%d_%d",half, ipart), rohacell, fSupportXDimensions[disk][ipart]/2.,
fSupportYDimensions[disk][ipart]/2., fRohacellThickness);
partRohacell->SetLineColor(kGray);
TGeoTranslation *t = new TGeoTranslation ("t", 0, ty + fHalfDiskGap, fZPlan[disk]);
rohacellPlate -> AddNode(partRohacell, ipart, t);
ty += fSupportYDimensions[disk][ipart]/2.;
}
// if (half == kTop) {
// rotation = new TGeoRotation ("rotation", 0., 0., 0.);
// transformation = new TGeoCombiTrans(0., 0., 0., rotation);
// fHalfDisk->AddNode(rohacellPlate, 1, transformation);
// }
// if (half == kBottom) {
rotation = new TGeoRotation ("rotation", 180., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., 0., rotation);
fHalfDisk->AddNode(rohacellPlate, 2, transformation);
// }
}
//====================================================================================================================================================
void AliMFTHeatExchanger::CreateHalfDisk2(Int_t half) {
Int_t disk = 2;
if (half == kTop) printf("Creating MFT heat exchanger for disk2 top\n");
else if (half == kBottom) printf("Creating MFT heat exchanger for disk2 bottom\n");
else printf("No valid option for MFT heat exchanger on disk2\n");
//TGeoMedium *carbon = gGeoManager->GetMedium("MFT_Carbon$");
TGeoMedium *carbon = gGeoManager->GetMedium("MFT_CarbonFiber$");
TGeoMedium *water = gGeoManager->GetMedium("MFT_Water$");
TGeoMedium *rohacell = gGeoManager->GetMedium("MFT_Rohacell");
TGeoMedium *pipe = gGeoManager->GetMedium("MFT_Polyimide");
TGeoVolumeAssembly *cooling = new TGeoVolumeAssembly(Form("cooling_D2_H%d",half));
Float_t lMiddle = fSupportXDimensions[disk][0] - 2.*fLWater; // length of central part
TGeoTranslation *translation = 0;
TGeoRotation *rotation = 0;
TGeoCombiTrans *transformation = 0;
// **************************************** Water part ****************************************
// ------------------- Tube shape -------------------
TGeoVolume *waterTube1 = gGeoManager->MakeTube(Form("waterTube1_D2_H%d",half), water, 0., fRWater, fLWater/2.);
waterTube1->SetLineColor(kBlue);
for (Int_t itube=0; itube<3; itube++) {
translation = new TGeoTranslation(fXPosition0[itube], 0., fLWater/2. + lMiddle/2.);
cooling->AddNode (waterTube1, itube, translation);
translation = new TGeoTranslation(fXPosition0[itube], 0., -fLWater/2. - lMiddle/2.);
cooling->AddNode (waterTube1, itube+3, translation);
}
Double_t angle0rad = fangle0*(TMath::DegToRad());
TGeoVolume *waterTube2 = gGeoManager->MakeTube(Form("waterTube2_D2_H%d",half), water, 0., fRWater, fLpartial0/2.);
waterTube2->SetLineColor(kBlue);
for (Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", -90., -fangle0, 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) +
(fLpartial0/2.)*(TMath::Sin(angle0rad)), 0., - lMiddle/2. +
fradius0*(TMath::Sin(angle0rad)) + (fLpartial0/2.)*TMath::Cos(angle0rad), rotation);
cooling->AddNode (waterTube2, itube, transformation);
rotation = new TGeoRotation ("rotation", -90., fangle0, 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) +
(fLpartial0/2.)*(TMath::Sin(angle0rad)), 0., lMiddle/2. -
fradius0*(TMath::Sin(angle0rad)) - (fLpartial0/2.)*TMath::Cos(angle0rad), rotation);
cooling->AddNode (waterTube2, itube+3, transformation);
}
// ------------------- Torus shape -------------------
// Sides torus
TGeoVolume *waterTorus1 = gGeoManager->MakeTorus(Form("waterTorus1_D2_H%d",half), water, fradius0, 0., fRWater, 0., fangle0);
waterTorus1->SetLineColor(kBlue);
Double_t radius0mid = (lMiddle - 2.*(fradius0*(TMath::Sin(angle0rad)) + fLpartial0*(TMath::Cos(angle0rad))))/(2*(TMath::Sin(angle0rad)));
for (Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fradius0 + fXPosition0[itube], 0., - lMiddle/2., rotation);
cooling->AddNode (waterTorus1, itube, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 0.);
transformation = new TGeoCombiTrans(fradius0 + fXPosition0[itube], 0., lMiddle/2., rotation);
cooling->AddNode (waterTorus1, itube+3, transformation);
}
// Central Torus
TGeoVolume *waterTorus2 = gGeoManager->MakeTorus(Form("waterTorus2_D2_H%d",half), water, radius0mid, 0., fRWater, - fangle0 , 2.*fangle0);
waterTorus2->SetLineColor(kBlue);
for(Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", 0., 90., 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) +
fLpartial0*TMath::Sin(angle0rad) - radius0mid*TMath::Cos(angle0rad), 0., 0., rotation);
cooling->AddNode (waterTorus2, itube, transformation);
}
// **************************************** Pipe part ****************************************
// ------------------- Tube shape -------------------
TGeoVolume *pipeTube1 = gGeoManager->MakeTube(Form("pipeTube1_D2_H%d",half), pipe, fRWater, fRWater + fDRPipe, fLWater/2.);
pipeTube1->SetLineColor(10);
for (Int_t itube=0; itube<3; itube++){
translation = new TGeoTranslation(fXPosition0[itube], 0., fLWater/2. + lMiddle/2.);
cooling->AddNode (pipeTube1, itube, translation);
translation = new TGeoTranslation(fXPosition0[itube], 0., -fLWater/2. - lMiddle/2.);
cooling->AddNode (pipeTube1, itube+3, translation);
}
TGeoVolume *pipeTube2 = gGeoManager->MakeTube(Form("pipeTube2_D2_H%d",half), pipe, fRWater, fRWater + fDRPipe, fLpartial0/2.);
waterTube2->SetLineColor(10);
for(Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", -90., -fangle0, 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) +
(fLpartial0/2.)*(TMath::Sin(angle0rad)), 0., - lMiddle/2. +
fradius0*(TMath::Sin(angle0rad)) + (fLpartial0/2.)*TMath::Cos(angle0rad), rotation);
cooling->AddNode (pipeTube2, itube, transformation);
rotation = new TGeoRotation ("rotation", -90., fangle0, 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) +
(fLpartial0/2.)*(TMath::Sin(angle0rad)), 0., lMiddle/2. -
fradius0*(TMath::Sin(angle0rad)) - (fLpartial0/2.)*TMath::Cos(angle0rad), rotation);
cooling->AddNode (pipeTube2, itube+3, transformation);
}
// ------------------- Torus shape -------------------
// Sides Torus
TGeoVolume *pipeTorus1 = gGeoManager->MakeTorus(Form("pipeTorus1_D2_H%d",half), pipe, fradius0, fRWater, fRWater + fDRPipe, 0., fangle0);
pipeTorus1->SetLineColor(10);
for (Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fradius0 + fXPosition0[itube], 0., - lMiddle/2., rotation);
cooling->AddNode (pipeTorus1, itube, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 0.);
transformation = new TGeoCombiTrans(fradius0 + fXPosition0[itube], 0., lMiddle/2., rotation);
cooling->AddNode (pipeTorus1, itube+3, transformation);
}
// Central Torus
TGeoVolume *pipeTorus2 = gGeoManager->MakeTorus(Form("pipeTorus2_D2_H%d",half), pipe, radius0mid, fRWater, fRWater + fDRPipe, - fangle0 , 2.*fangle0);
pipeTorus2->SetLineColor(10);
for(Int_t itube=0; itube<3; itube++) {
rotation = new TGeoRotation ("rotation", 0., 90., 0.);
transformation = new TGeoCombiTrans(fXPosition0[itube] + fradius0*(1-(TMath::Cos(angle0rad))) +
fLpartial0*TMath::Sin(angle0rad) - radius0mid*TMath::Cos(angle0rad), 0., 0., rotation);
cooling->AddNode (pipeTorus2, itube, transformation);
}
Double_t deltaz = fHeatExchangerThickness - fCarbonThickness*2; // distance between pair of carbon plates
// if (half == kTop) {
// rotation = new TGeoRotation ("rotation", 90., 90., 0.);
// transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] + deltaz/2. - fCarbonThickness - fRWater - fDRPipe, rotation);
// fHalfDisk->AddNode(cooling, 1, transformation);
// transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] - deltaz/2. + fCarbonThickness + fRWater + fDRPipe, rotation);
// fHalfDisk->AddNode(cooling, 2, transformation);
// }
// else if (half == kBottom) {
rotation = new TGeoRotation ("rotation", -90., 90., 0.);
transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] + deltaz/2. - fCarbonThickness - fRWater - fDRPipe, rotation);
fHalfDisk->AddNode(cooling, 3, transformation);
transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] - deltaz/2. + fCarbonThickness + fRWater + fDRPipe, rotation);
fHalfDisk->AddNode(cooling, 4, transformation);
// }
// **************************************** Carbon Plates ****************************************
TGeoVolumeAssembly *carbonPlate = new TGeoVolumeAssembly(Form("carbonPlate_D2_H%d",half));
TGeoBBox *carbonBase2 = new TGeoBBox (Form("carbonBase2_D2_H%d",half), (fSupportXDimensions[disk][0])/2., (fSupportYDimensions[disk][0])/2., fCarbonThickness);
TGeoTranslation *t21= new TGeoTranslation ("t21",0., (fSupportYDimensions[disk][0])/2. + fHalfDiskGap , 0.);
t21-> RegisterYourself();
TGeoTubeSeg *holeCarbon2 = new TGeoTubeSeg(Form("holeCarbon2_D2_H%d",half), 0., fRMin[disk], fCarbonThickness + 0.000001, 0, 180.);
TGeoTranslation *t22= new TGeoTranslation ("t22",0., - fHalfDiskGap , 0.);
t22-> RegisterYourself();
////TGeoCompositeShape *cs2 = new TGeoCompositeShape(Form("carbon2_D2_H%d",half),Form("(carbonBase2_D2_H%d:t21)-(holeCarbon2_D2_H%d:t22)",half,half));
TGeoSubtraction *carbonhole2 = new TGeoSubtraction(carbonBase2, holeCarbon2, t21, t22);
TGeoCompositeShape *cs2 = new TGeoCompositeShape(Form("Carbon2_D2_H%d",half), carbonhole2);
TGeoVolume *carbonBaseWithHole2 = new TGeoVolume(Form("carbonBaseWithHole_D2_H%d", half), cs2, carbon);
carbonBaseWithHole2->SetLineColor(kGray+3);
rotation = new TGeoRotation ("rotation", 0., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., 0., rotation);
carbonPlate->AddNode(carbonBaseWithHole2, 0, new TGeoTranslation(0., 0., fZPlan[disk]));
Double_t ty = fSupportYDimensions[disk][0];
for (Int_t ipart=1; ipart<fnPart[disk]; ipart ++) {
ty += fSupportYDimensions[disk][ipart]/2.;
TGeoVolume *partCarbon = gGeoManager->MakeBox(Form("partCarbon_D2_H%d_%d", half, ipart), carbon, fSupportXDimensions[disk][ipart]/2., fSupportYDimensions[disk][ipart]/2., fCarbonThickness);
partCarbon->SetLineColor(kGray+3);
TGeoTranslation *t = new TGeoTranslation ("t", 0, ty + fHalfDiskGap, fZPlan[disk]);
carbonPlate -> AddNode(partCarbon, ipart, t);
ty += fSupportYDimensions[disk][ipart]/2.;
}
// if (half == kTop) {
// rotation = new TGeoRotation ("rotation", 0., 0., 0.);
// transformation = new TGeoCombiTrans(0., 0., deltaz/2., rotation);
// fHalfDisk->AddNode(carbonPlate, 1, transformation);
// transformation = new TGeoCombiTrans(0., 0., -deltaz/2., rotation);
// fHalfDisk->AddNode(carbonPlate, 2, transformation);
// }
// else if (half == kBottom) {
rotation = new TGeoRotation ("rotation", 180., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., deltaz/2., rotation);
fHalfDisk->AddNode(carbonPlate, 3, transformation);
transformation = new TGeoCombiTrans(0., 0., -deltaz/2., rotation);
fHalfDisk->AddNode(carbonPlate, 4, transformation);
// }
// **************************************** Rohacell Plate ****************************************
TGeoVolumeAssembly *rohacellPlate = new TGeoVolumeAssembly(Form("rohacellPlate_D2_H%d",half));
TGeoBBox *rohacellBase2 = new TGeoBBox (Form("rohacellBase2_D2_H%d",half), (fSupportXDimensions[disk][0])/2., (fSupportYDimensions[disk][0])/2., fRohacellThickness);
// TGeoTranslation *t3 = new TGeoTranslation ("t3",0., (fSupportYDimensions[disk][0])/2. + fHalfDiskGap , 0.);
// t3 -> RegisterYourself();
TGeoTubeSeg *holeRohacell2 = new TGeoTubeSeg(Form("holeRohacell2_D2_H%d",half), 0., fRMin[disk], fRohacellThickness + 0.000001, 0, 180.);
// TGeoTranslation *t4= new TGeoTranslation ("t4", 0., - fHalfDiskGap , 0.);
// t4-> RegisterYourself()
;
///cs2 = new TGeoCompositeShape(Form("rohacell_D2_H%d",half), Form("(rohacellBase2_D2_H%d:t21)-(holeRohacell2_D2_H%d:t22)",half,half));
TGeoSubtraction *rohacellhole2 = new TGeoSubtraction(rohacellBase2, holeRohacell2, t21, t22);
TGeoCompositeShape *rh2 = new TGeoCompositeShape(Form("rohacellBase2_D2_H%d",half), rohacellhole2);
TGeoVolume *rohacellBaseWithHole = new TGeoVolume(Form("rohacellBaseWithHole_D2_H%d",half), rh2, rohacell);
rohacellBaseWithHole->SetLineColor(kGray);
rotation = new TGeoRotation ("rotation", 0., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., 0., rotation);
rohacellPlate -> AddNode(rohacellBaseWithHole, 0, new TGeoTranslation(0., 0., fZPlan[disk]));
ty = fSupportYDimensions[disk][0];
for (Int_t ipart=1; ipart<fnPart[disk]; ipart ++) {
ty += fSupportYDimensions[disk][ipart]/2.;
TGeoVolume *partRohacell = gGeoManager->MakeBox(Form("partRohacelli_D2_H%d_%d", half,ipart), rohacell, fSupportXDimensions[disk][ipart]/2., fSupportYDimensions[disk][ipart]/2., fRohacellThickness);
partRohacell->SetLineColor(kGray);
TGeoTranslation *t = new TGeoTranslation ("t", 0, ty + fHalfDiskGap, fZPlan[disk]);
rohacellPlate -> AddNode(partRohacell, ipart, t);
ty += fSupportYDimensions[disk][ipart]/2.;
}
// if (half == kTop) {
// rotation = new TGeoRotation ("rotation", 0., 0., 0.);
// transformation = new TGeoCombiTrans(0., 0., 0., rotation);
// fHalfDisk->AddNode(rohacellPlate, 1, transformation);
// }
// if (half == kBottom) {
rotation = new TGeoRotation ("rotation", 180., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., 0., rotation);
fHalfDisk->AddNode(rohacellPlate, 2, transformation);
// }
}
//====================================================================================================================================================
void AliMFTHeatExchanger::CreateHalfDisk3(Int_t half) {
Int_t disk = 3;
if (half == kTop) printf("Creating MFT heat exchanger for disk3 top\n");
else if (half == kBottom) printf("Creating MFT heat exchanger for disk3 bottom\n");
else printf("No valid option for MFT heat exchanger on disk3\n");
//TGeoMedium *carbon = gGeoManager->GetMedium("MFT_Carbon$");
TGeoMedium *carbon = gGeoManager->GetMedium("MFT_CarbonFiber$");
TGeoMedium *water = gGeoManager->GetMedium("MFT_Water$");
TGeoMedium *rohacell = gGeoManager->GetMedium("MFT_Rohacell");
TGeoMedium *pipe = gGeoManager->GetMedium("MFT_Polyimide");
TGeoVolumeAssembly *cooling = new TGeoVolumeAssembly(Form("cooling_D3_H%d",half));
Double_t deltaz= fHeatExchangerThickness - fCarbonThickness*2; //distance between pair of carbon plans
Double_t lMiddle3[3] = {fSupportXDimensions[3][0] - 2.*fLWater3[0], fSupportXDimensions[3][0] - 2.*fLWater3[0], 0.};//distance between tube part
TGeoTranslation *translation = 0;
TGeoRotation *rotation = 0;
TGeoCombiTrans *transformation = 0;
Double_t beta3rad[3] = {0., 0., 0.};
for (Int_t i=0; i<3; i++) {
beta3rad[i] = fangle3[i]*(TMath::DegToRad());
}
Double_t fangleThirdPipe3rad= fangleThirdPipe3*(TMath::DegToRad());
Double_t radius3mid[2] = {((lMiddle3[0]) - 2.*(fradius3[0]*(TMath::Sin(beta3rad[0])) +
fLpartial3[0]*(TMath::Cos(beta3rad[0]))))/ (2*(TMath::Sin(beta3rad[0]))), 0.};//radius of central torus
radius3mid[1] = (fSupportXDimensions[3][0]/2. - fLWater3[2]*TMath::Cos(fangleThirdPipe3rad) -
fradius3[2]*(TMath::Sin(beta3rad[2] + fangleThirdPipe3rad) - TMath::Sin(fangleThirdPipe3rad)))/(TMath::Sin(fangleThirdPipe3rad + beta3rad[2]));
lMiddle3[2] = fSupportXDimensions[3][0] - 2.*fLWater3[2]*(TMath::Cos(fangleThirdPipe3rad));
// **************************************** Water part ****************************************
// ------------------- First and second pipe -------------------
for (Int_t itube= 0; itube < 2; itube ++){
// -------- Tube shape --------
TGeoVolume *waterTube1 = gGeoManager->MakeTube(Form("waterTubeone%d_D3_H%d", itube,half), water, 0., fRWater, fLWater3[itube]/2.);
waterTube1->SetLineColor(kBlue);
translation = new TGeoTranslation (fXPosition3[itube], 0., fLWater3[itube]/2. + lMiddle3[itube]/2.);
cooling->AddNode (waterTube1, 1, translation);
TGeoVolume *waterTube2 = gGeoManager->MakeTube(Form("waterTubetwo%d_D3_H%d", itube,half), water, 0., fRWater, fLWater3[itube]/2.);
waterTube2->SetLineColor(kBlue);
translation = new TGeoTranslation (fXPosition3[itube], 0., -fLWater3[itube]/2. - lMiddle3[itube]/2.);
cooling->AddNode (waterTube2, 2, translation);
TGeoVolume *waterTube3 = gGeoManager->MakeTube(Form("waterTubethree%d_D3_H%d", itube,half), water, 0., fRWater, fLpartial3[itube]/2.);
waterTube3->SetLineColor(kBlue);
rotation = new TGeoRotation ("rotation", -90., 0 - fangle3[itube], 0.);
transformation = new TGeoCombiTrans(fXPosition3[itube] + fradius3[itube]*(1-(TMath::Cos(beta3rad[0]))) +
(fLpartial3[itube]/2.)*(TMath::Sin(beta3rad[0])), 0., (fradius3[itube])*(TMath::Sin(beta3rad[0])) +
(fLpartial3[itube]/2.)*(TMath::Cos(beta3rad[0])) - lMiddle3[itube]/2., rotation);
cooling->AddNode (waterTube3, 3, transformation);
rotation = new TGeoRotation ("rotation", 90., 180 - fangle3[itube], 0.);
transformation = new TGeoCombiTrans( fXPosition3[itube] + fradius3[itube]*(1-(TMath::Cos(beta3rad[0]))) +
(fLpartial3[itube]/2.)*(TMath::Sin(beta3rad[0])), 0., lMiddle3[itube]/2. - (fradius3[itube])*(TMath::Sin(beta3rad[0])) -
(fLpartial3[itube]/2.)*(TMath::Cos(beta3rad[0])), rotation);
cooling->AddNode (waterTube3, 4, transformation);
// -------- Torus shape --------
//Sides torus
TGeoVolume *waterTorus1 = gGeoManager->MakeTorus(Form("waterTorusone%d_D3_H%d", itube,half), water, fradius3[itube], 0., fRWater, 0., fangle3[itube]);
waterTorus1->SetLineColor(kBlue);
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fradius3[itube] + fXPosition3[itube], 0., - lMiddle3[itube]/2., rotation);
cooling->AddNode (waterTorus1, 4, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 0.);
transformation = new TGeoCombiTrans(fradius3[itube] + fXPosition3[itube], 0., lMiddle3[itube]/2., rotation);
cooling->AddNode (waterTorus1, 5, transformation);
//Central torus
TGeoVolume *waterTorus2 = gGeoManager->MakeTorus(Form("waterTorustwo%d_D3_H%d", itube,half), water, radius3mid[0], 0., fRWater, -fangle3[itube], 2.*fangle3[itube]);
waterTorus2->SetLineColor(kBlue);
rotation = new TGeoRotation ("rotation", 0., 90., 0.);
transformation = new TGeoCombiTrans(fXPosition3[itube] + fradius3[0]*(1-(TMath::Cos(beta3rad[0])))+fLpartial3[0]*TMath::Sin(beta3rad[0]) -
radius3mid[0]*TMath::Cos(beta3rad[0]) , 0., 0., rotation);
cooling->AddNode (waterTorus2, 6, transformation);
}
// ------------------- Third pipe -------------------
// -------- Tube shape --------
TGeoVolume *waterTube1 = gGeoManager->MakeTube(Form("waterTubeone2_D3_H%d",half), water, 0., fRWater, fLWater3[2]/2.);
waterTube1->SetLineColor(kBlue);
rotation = new TGeoRotation ("rotation", 90., -fangleThirdPipe3, 90.);
transformation = new TGeoCombiTrans (fXPosition3[2] + fLWater3[2]*TMath::Sin(fangleThirdPipe3rad)/2., 0.,
fSupportXDimensions[3][0]/2. - fLWater3[2]*(TMath::Cos(fangleThirdPipe3rad))/2., rotation);
cooling->AddNode (waterTube1, 3, transformation);
rotation = new TGeoRotation ("rotation", 90., fangleThirdPipe3, 90.);
transformation = new TGeoCombiTrans (fXPosition3[2] + fLWater3[2]*TMath::Sin(fangleThirdPipe3rad)/2., 0.,
-fSupportXDimensions[3][0]/2. + fLWater3[2]*(TMath::Cos(fangleThirdPipe3rad))/2., rotation);
cooling->AddNode (waterTube1, 4, transformation);
// -------- Torus shape --------
TGeoVolume *waterTorus1 = gGeoManager->MakeTorus(Form("waterTorusone2_D3_H%d",half), water, fradius3[2], 0., fRWater, fangleThirdPipe3, fangle3[2]);
waterTorus1->SetLineColor(kBlue);
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fXPosition3[2] + fLWater3[2]*TMath::Sin(fangleThirdPipe3rad) +
fradius3[2]*(TMath::Cos(fangleThirdPipe3rad)), 0., -lMiddle3[2]/2. - fradius3[2]*(TMath::Sin(fangleThirdPipe3rad)) , rotation);
cooling->AddNode (waterTorus1, 4, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 0.);
transformation = new TGeoCombiTrans( fXPosition3[2] + fLWater3[2]*TMath::Sin(fangleThirdPipe3rad) +
fradius3[2]*(TMath::Cos(fangleThirdPipe3rad)), 0., lMiddle3[2]/2. + fradius3[2]*(TMath::Sin(fangleThirdPipe3rad)), rotation);
cooling->AddNode (waterTorus1, 5, transformation);
TGeoVolume *waterTorus2 = gGeoManager->MakeTorus(Form("waterTorustwo2_D3_H%d",half), water, radius3mid[1], 0., fRWater, -(fangle3[2] + fangleThirdPipe3),
2.*(fangle3[2] + fangleThirdPipe3));
waterTorus2->SetLineColor(kBlue);
rotation = new TGeoRotation ("rotation", 0., 90., 0.);
transformation = new TGeoCombiTrans( fXPosition3[2] + fLWater3[2]*TMath::Sin(fangleThirdPipe3rad) + fradius3[2]*(TMath::Cos(fangleThirdPipe3rad)) -
(fradius3[2] + radius3mid[1])*(TMath::Cos(beta3rad[2] + fangleThirdPipe3rad)), 0., 0., rotation);
cooling->AddNode (waterTorus2, 6, transformation);
// ------------------- Fourth pipe -------------------
Double_t radius3fourth[4] = {9.6, 2.9, 2.9, 0.};
Double_t alpha3fourth[4] = { 40.8, 50, 60, 0}; //size angle
alpha3fourth[3] = 8 + alpha3fourth[0] - alpha3fourth[1] + alpha3fourth[2];
Double_t alpha3fourthrad[4] = {};
for(Int_t i=0; i<4; i++){
alpha3fourthrad[i] = (TMath::Pi())*(alpha3fourth[i])/180.;
}
Double_t beta3fourth[3] = {8, 8 + alpha3fourth[0], -(-8 - alpha3fourth[0] + alpha3fourth[1])}; //shift angle
Double_t beta3fourthrad[3] = {0., 0., 0.};
for(Int_t i=0; i<3; i++){
beta3fourthrad[i] = (TMath::Pi())*(beta3fourth[i])/180.;
}
radius3fourth[3] = ((-(-(fLWater3[0] + lMiddle3[0]/2.) -
radius3fourth[0]*(TMath::Sin(beta3fourthrad[0])) +
radius3fourth[0]*(TMath::Sin(beta3fourthrad[0] + alpha3fourthrad[0])) +
radius3fourth[1]*(TMath::Cos(TMath::Pi()/2 - beta3fourthrad[0] - alpha3fourthrad[0])) +
radius3fourth[1]*(TMath::Cos(TMath::Pi()/2. - alpha3fourthrad[1] + alpha3fourthrad[0] + beta3fourthrad[0])) +
radius3fourth[2]*(TMath::Sin(alpha3fourthrad[1] - alpha3fourthrad[0] - beta3fourthrad[0])))) -
radius3fourth[2]*TMath::Cos(TMath::Pi()/2 - alpha3fourthrad[3]))/(TMath::Sin(alpha3fourthrad[3]));
Double_t translation3x[4] = { fXPosition3[3] + radius3fourth[0]*(TMath::Cos(beta3fourthrad[0])),
fXPosition3[3] + radius3fourth[0]*((TMath::Cos(beta3fourthrad[0])) - TMath::Cos(beta3fourthrad[0] + alpha3fourthrad[0])) -
radius3fourth[1]*(TMath::Cos(beta3fourthrad[0] + alpha3fourthrad[0])),
fXPosition3[3] + radius3fourth[0]*((TMath::Cos(beta3fourthrad[0])) - TMath::Cos(beta3fourthrad[0] + alpha3fourthrad[0])) -
radius3fourth[1]*(TMath::Cos(beta3fourthrad[0] + alpha3fourthrad[0])) +
radius3fourth[1]*(TMath::Sin(TMath::Pi()/2. - alpha3fourthrad[1] + alpha3fourthrad[0] + beta3fourthrad[0])) +
radius3fourth[2]*(TMath::Cos(alpha3fourthrad[1] - alpha3fourthrad[0] - beta3fourthrad[0])),
fXPosition3[3] + radius3fourth[0]*((TMath::Cos(beta3fourthrad[0])) - TMath::Cos(beta3fourthrad[0] + alpha3fourthrad[0])) -
radius3fourth[1]*(TMath::Cos(beta3fourthrad[0] + alpha3fourthrad[0])) +
radius3fourth[1]*(TMath::Sin(TMath::Pi()/2. - alpha3fourthrad[1] + alpha3fourthrad[0] + beta3fourthrad[0])) +
radius3fourth[2]*(TMath::Cos(alpha3fourthrad[1] - alpha3fourthrad[0] - beta3fourthrad[0])) -
radius3fourth[2]*(TMath::Sin((TMath::Pi()/2.) - alpha3fourthrad[3])) - radius3fourth[3]*(TMath::Cos(alpha3fourthrad[3]))};
Double_t translation3y[3] = {0., 0., 0.};
Double_t translation3z[3] = {-(fLWater3[0] + lMiddle3[0]/2.) - radius3fourth[0]*(TMath::Sin(beta3fourthrad[0])),
-(fLWater3[0] + lMiddle3[0]/2.) - radius3fourth[0]*(TMath::Sin(beta3fourthrad[0])) +
radius3fourth[0]*(TMath::Sin(beta3fourthrad[0] + alpha3fourthrad[0])) + radius3fourth[1]*(TMath::Sin(beta3fourthrad[0] + alpha3fourthrad[0])),
-(fLWater3[0] + lMiddle3[0]/2.) - radius3fourth[0]*(TMath::Sin(beta3fourthrad[0])) +
radius3fourth[0]*(TMath::Sin(beta3fourthrad[0] + alpha3fourthrad[0])) +
radius3fourth[1]*(TMath::Cos(TMath::Pi()/2 - beta3fourthrad[0] - alpha3fourthrad[0])) +
radius3fourth[1]*(TMath::Cos(TMath::Pi()/2. - alpha3fourthrad[1] + alpha3fourthrad[0] +
beta3fourthrad[0])) + radius3fourth[2]*(TMath::Sin(alpha3fourthrad[1] - alpha3fourthrad[0] - beta3fourthrad[0]))};
Double_t rotation3x[3] = {180., 180., 180.};
Double_t rotation3y[3] = {90., 90., 90.};
Double_t rotation3z[3] = {0., 180 - alpha3fourth[1] , 0.};
for (Int_t i= 0; i<3; i++) {
waterTorus1 = gGeoManager->MakeTorus(Form("waterTorusone%d_D3_H%d", i,half), water, radius3fourth[i], 0., fRWater, beta3fourth[i], alpha3fourth[i]);
waterTorus1->SetLineColor(kBlue);
rotation = new TGeoRotation ("rotation", rotation3x[i], rotation3y[i], rotation3z[i]);
transformation = new TGeoCombiTrans(translation3x[i], translation3y[i], translation3z[i], rotation);
cooling->AddNode (waterTorus1, 7, transformation);
rotation = new TGeoRotation ("rotation", rotation3x[i] , rotation3y[i] - 180, rotation3z[i]);
transformation = new TGeoCombiTrans(translation3x[i], translation3y[i], - translation3z[i], rotation);
cooling->AddNode (waterTorus1, 8, transformation);
}
waterTorus2 = gGeoManager->MakeTorus(Form("waterTorusone3_D3_H%d",half), water, radius3fourth[3], 0., fRWater, -alpha3fourth[3], 2*alpha3fourth[3]);
waterTorus2->SetLineColor(kBlue);
rotation = new TGeoRotation ("rotation", 180., 90., 180);
transformation = new TGeoCombiTrans(translation3x[3], 0., 0., rotation);
cooling->AddNode(waterTorus2, 9, transformation);
// **************************************** Pipe part ****************************************
// ------------------- First and second pipe -------------------
for (Int_t itube= 0; itube < 2; itube ++){
// -------- Tube shape --------
TGeoVolume *pipeTube1 = gGeoManager->MakeTube(Form("pipeTubeone%d_D3_H%d", itube,half), pipe, fRWater, fRWater + fDRPipe, fLWater3[itube]/2.);
pipeTube1->SetLineColor(10);
translation = new TGeoTranslation (fXPosition3[itube], 0., fLWater3[itube]/2. + lMiddle3[itube]/2.);
cooling->AddNode (pipeTube1, 1, translation);
TGeoVolume *pipeTube2 = gGeoManager->MakeTube(Form("pipeTubetwo%d_D3_H%d", itube,half), pipe, fRWater, fRWater + fDRPipe, fLWater3[itube]/2.);
pipeTube2->SetLineColor(10);
translation = new TGeoTranslation (fXPosition3[itube], 0., -fLWater3[itube]/2. - lMiddle3[itube]/2.);
cooling->AddNode (pipeTube2, 2, translation);
TGeoVolume *pipeTube3 = gGeoManager->MakeTube(Form("pipeTubethree%d_D3_H%d", itube,half), pipe, fRWater, fRWater + fDRPipe, fLpartial3[itube]/2.);
pipeTube3->SetLineColor(10);
rotation = new TGeoRotation ("rotation", -90., 0 - fangle3[itube], 0.);
transformation = new TGeoCombiTrans(fXPosition3[itube] + fradius3[itube]*(1-(TMath::Cos(beta3rad[0]))) +
(fLpartial3[itube]/2.)*(TMath::Sin(beta3rad[0])), 0., (fradius3[itube])*(TMath::Sin(beta3rad[0])) +
(fLpartial3[itube]/2.)*(TMath::Cos(beta3rad[0])) - lMiddle3[itube]/2., rotation);
cooling->AddNode (pipeTube3, 3, transformation);
rotation = new TGeoRotation ("rotation", 90., 180 - fangle3[itube], 0.);
transformation = new TGeoCombiTrans( fXPosition3[itube] + fradius3[itube]*(1-(TMath::Cos(beta3rad[0]))) +
(fLpartial3[itube]/2.)*(TMath::Sin(beta3rad[0])), 0., lMiddle3[itube]/2. -
(fradius3[itube])*(TMath::Sin(beta3rad[0])) - (fLpartial3[itube]/2.)*(TMath::Cos(beta3rad[0])), rotation);
cooling->AddNode (pipeTube3, 4, transformation);
// -------- Torus shape --------
//Sides torus
TGeoVolume *pipeTorus1 = gGeoManager->MakeTorus(Form("pipeTorusone%d_D3_H%d", itube,half), pipe, fradius3[itube], fRWater, fRWater + fDRPipe, 0., fangle3[itube]);
pipeTorus1->SetLineColor(10);
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fradius3[itube] + fXPosition3[itube], 0., - lMiddle3[itube]/2., rotation);
cooling->AddNode (pipeTorus1, 4, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 0.);
transformation = new TGeoCombiTrans(fradius3[itube] + fXPosition3[itube], 0., lMiddle3[itube]/2., rotation);
cooling->AddNode (pipeTorus1, 5, transformation);
//Central torus
TGeoVolume *pipeTorus2 = gGeoManager->MakeTorus(Form("pipeTorustwo%d_D3_H%d", itube,half), pipe, radius3mid[0], fRWater, fRWater + fDRPipe, -fangle3[itube], 2.*fangle3[itube]);
pipeTorus2->SetLineColor(10);
rotation = new TGeoRotation ("rotation", 0., 90., 0.);
transformation = new TGeoCombiTrans(fXPosition3[itube] + fradius3[0]*(1-(TMath::Cos(beta3rad[0])))+fLpartial3[0]*TMath::Sin(beta3rad[0]) - radius3mid[0]*TMath::Cos(beta3rad[0]) , 0., 0., rotation);
cooling->AddNode (pipeTorus2, 6, transformation);
}
// ------------------- Third pipe -------------------
// -------- Tube shape --------
TGeoVolume *pipeTube1 = gGeoManager->MakeTube(Form("pipeTubeone2_D3_H%d",half), pipe, fRWater, fRWater + fDRPipe, fLWater3[2]/2.);
pipeTube1->SetLineColor(10);
rotation = new TGeoRotation ("rotation", 90., -fangleThirdPipe3, 90.);
transformation = new TGeoCombiTrans (fXPosition3[2] + fLWater3[2]*TMath::Sin(fangleThirdPipe3rad)/2., 0.,
fSupportXDimensions[3][0]/2. - fLWater3[2]*(TMath::Cos(fangleThirdPipe3rad))/2., rotation);
cooling->AddNode (pipeTube1, 3, transformation);
rotation = new TGeoRotation ("rotation", 90., fangleThirdPipe3, 90.);
transformation = new TGeoCombiTrans (fXPosition3[2] + fLWater3[2]*TMath::Sin(fangleThirdPipe3rad)/2., 0.,
-fSupportXDimensions[3][0]/2. + fLWater3[2]*(TMath::Cos(fangleThirdPipe3rad))/2., rotation);
cooling->AddNode (pipeTube1, 4, transformation);
// -------- Torus shape --------
TGeoVolume *pipeTorus1 = gGeoManager->MakeTorus(Form("pipeTorusone2_D3_H%d",half), pipe, fradius3[2], fRWater, fRWater + fDRPipe, fangleThirdPipe3, fangle3[2]);
pipeTorus1->SetLineColor(10);
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fXPosition3[2] + fLWater3[2]*TMath::Sin(fangleThirdPipe3rad) +
fradius3[2]*(TMath::Cos(fangleThirdPipe3rad)), 0., -lMiddle3[2]/2. - fradius3[2]*(TMath::Sin(fangleThirdPipe3rad)), rotation);
cooling->AddNode (pipeTorus1, 4, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 0.);
transformation = new TGeoCombiTrans( fXPosition3[2] + fLWater3[2]*TMath::Sin(fangleThirdPipe3rad) +
fradius3[2]*(TMath::Cos(fangleThirdPipe3rad)), 0., lMiddle3[2]/2. + fradius3[2]*(TMath::Sin(fangleThirdPipe3rad)), rotation);
cooling->AddNode (pipeTorus1, 5, transformation);
TGeoVolume *pipeTorus2 = gGeoManager->MakeTorus(Form("pipeTorustwo2_D3_H%d",half), pipe, radius3mid[1], fRWater, fRWater + fDRPipe,
-(fangle3[2] + fangleThirdPipe3), 2.*(fangle3[2] + fangleThirdPipe3));
pipeTorus2->SetLineColor(10);
rotation = new TGeoRotation ("rotation", 0., 90., 0.);
transformation = new TGeoCombiTrans( fXPosition3[2] + fLWater3[2]*TMath::Sin(fangleThirdPipe3rad) +
fradius3[2]*(TMath::Cos(fangleThirdPipe3rad)) -
(fradius3[2] + radius3mid[1])*(TMath::Cos(beta3rad[2] + fangleThirdPipe3rad)), 0., 0., rotation);
cooling->AddNode (pipeTorus2, 6, transformation);
// ------------------- Fourth pipe -------------------
for(Int_t i= 0; i<3; i++){
pipeTorus1 = gGeoManager->MakeTorus(Form("pipeTorusone%d_D3_H%d", i,half), pipe, radius3fourth[i], fRWater, fRWater + fDRPipe, beta3fourth[i], alpha3fourth[i]);
pipeTorus1->SetLineColor(10);
rotation = new TGeoRotation ("rotation", rotation3x[i], rotation3y[i], rotation3z[i]);
transformation = new TGeoCombiTrans(translation3x[i], translation3y[i], translation3z[i], rotation);
cooling->AddNode (pipeTorus1, 7, transformation);
rotation = new TGeoRotation ("rotation", rotation3x[i] , rotation3y[i] - 180, rotation3z[i]);
transformation = new TGeoCombiTrans(translation3x[i], translation3y[i], - translation3z[i], rotation);
cooling->AddNode (pipeTorus1, 8, transformation);
}
pipeTorus2 = gGeoManager->MakeTorus(Form("pipeTorusone3_D3_H%d",half), pipe, radius3fourth[3], fRWater, fRWater + fDRPipe, -alpha3fourth[3], 2*alpha3fourth[3]);
pipeTorus2->SetLineColor(10);
rotation = new TGeoRotation ("rotation", 180., 90., 180);
transformation = new TGeoCombiTrans(translation3x[3], 0., 0., rotation);
cooling->AddNode(pipeTorus2, 9, transformation);
// if (half == kTop) {
// rotation = new TGeoRotation ("rotation", 90., 90., 0.);
// transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] + deltaz/2. - fCarbonThickness - fRWater - fDRPipe, rotation);
// fHalfDisk->AddNode(cooling, 1, transformation);
// transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] - deltaz/2. + fCarbonThickness + fRWater + fDRPipe, rotation);
// fHalfDisk->AddNode(cooling, 2, transformation);
// }
// else if (half == kBottom) {
rotation = new TGeoRotation ("rotation", -90., 90., 0.);
transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] + deltaz/2. - fCarbonThickness - fRWater - fDRPipe, rotation);
fHalfDisk->AddNode(cooling, 3, transformation);
transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] - deltaz/2. + fCarbonThickness + fRWater + fDRPipe, rotation);
fHalfDisk->AddNode(cooling, 4, transformation);
// }
// **************************************** Carbon Plates ****************************************
TGeoVolumeAssembly *carbonPlate = new TGeoVolumeAssembly(Form("carbonPlate_D3_H%d",half));
TGeoBBox *carbonBase3 = new TGeoBBox (Form("carbonBase3_D3_H%d",half), (fSupportXDimensions[disk][0])/2., (fSupportYDimensions[disk][0])/2., fCarbonThickness);
TGeoTranslation *t31= new TGeoTranslation ("t31",0., (fSupportYDimensions[disk][0])/2.+ fHalfDiskGap , 0.);
t31-> RegisterYourself();
TGeoTubeSeg *holeCarbon3 = new TGeoTubeSeg(Form("holeCarbon3_D3_H%d",half), 0., fRMin[disk], fCarbonThickness + 0.000001, 0, 180.);
TGeoTranslation *t32= new TGeoTranslation ("t32",0., - fHalfDiskGap , 0.);
t32-> RegisterYourself();
///TGeoCompositeShape *cs3 = new TGeoCompositeShape(Form("Carbon3_D3_H%d",half),Form("(carbonBase3_D3_H%d:t31)-(holeCarbon3_D3_H%d:t32)",half,half) );
TGeoSubtraction *carbonhole3 = new TGeoSubtraction(carbonBase3, holeCarbon3, t31, t32);
TGeoCompositeShape *cs3 = new TGeoCompositeShape(Form("Carbon3_D3_H%d",half), carbonhole3);
TGeoVolume *carbonBaseWithHole3 = new TGeoVolume(Form("carbonBaseWithHole_D3_H%d",half), cs3, carbon);
carbonBaseWithHole3->SetLineColor(kGray+3);
rotation = new TGeoRotation ("rotation", 0., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., 0., rotation);
carbonPlate->AddNode(carbonBaseWithHole3, 0, new TGeoTranslation(0., 0., fZPlan[disk]));
Double_t ty = fSupportYDimensions[disk][0];
for (Int_t ipart=1; ipart<fnPart[disk]; ipart ++) {
ty += fSupportYDimensions[disk][ipart]/2.;
TGeoVolume *partCarbon = gGeoManager->MakeBox(Form("partCarbon_D3_H%d_%d", half,ipart), carbon, fSupportXDimensions[disk][ipart]/2.,
fSupportYDimensions[disk][ipart]/2., fCarbonThickness);
partCarbon->SetLineColor(kGray+3);
TGeoTranslation *t = new TGeoTranslation ("t", 0, ty + fHalfDiskGap, fZPlan[disk]);
carbonPlate -> AddNode(partCarbon, ipart, t);
ty += fSupportYDimensions[disk][ipart]/2.;
}
// if (half == kTop) {
// rotation = new TGeoRotation ("rotation", 0., 0., 0.);
// transformation = new TGeoCombiTrans(0., 0., deltaz/2., rotation);
// fHalfDisk->AddNode(carbonPlate, 1, transformation);
// transformation = new TGeoCombiTrans(0., 0., -deltaz/2., rotation);
// fHalfDisk->AddNode(carbonPlate, 2, transformation);
// }
// else if (half == kBottom) {
rotation = new TGeoRotation ("rotation", 180., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., deltaz/2., rotation);
fHalfDisk->AddNode(carbonPlate, 3, transformation);
transformation = new TGeoCombiTrans(0., 0., -deltaz/2., rotation);
fHalfDisk->AddNode(carbonPlate, 4, transformation);
// }
// **************************************** Rohacell Plate ****************************************
TGeoVolumeAssembly *rohacellPlate = new TGeoVolumeAssembly(Form("rohacellPlate_D3_H%d",half));
TGeoBBox *rohacellBase3 = new TGeoBBox (Form("rohacellBase3_D3_H%d",half), (fSupportXDimensions[disk][0])/2., (fSupportYDimensions[disk][0])/2., fRohacellThickness);
// TGeoTranslation *t3 = new TGeoTranslation ("t3",0., (fSupportYDimensions[disk][0])/2. + fHalfDiskGap , 0.);
// t3 -> RegisterYourself();
TGeoTubeSeg *holeRohacell3 = new TGeoTubeSeg(Form("holeRohacell3_D3_H%d",half), 0., fRMin[disk], fRohacellThickness + 0.000001, 0, 180.);
// TGeoTranslation *t4= new TGeoTranslation ("t4", 0., - fHalfDiskGap , 0.);
// t4-> RegisterYourself();
///cs3 = new TGeoCompositeShape(Form("rohacell_D3_H%d",half), Form("(rohacellBase3_D3_H%d:t31)-(holeRohacell3_D3_H%d:t32)",half,half));
TGeoSubtraction *rohacellhole3 = new TGeoSubtraction(rohacellBase3, holeRohacell3, t31, t32);
TGeoCompositeShape *rh3 = new TGeoCompositeShape(Form("rohacellBase3_D3_H%d",half), rohacellhole3);
TGeoVolume *rohacellBaseWithHole = new TGeoVolume(Form("rohacellBaseWithHole_D3_H%d",half), rh3, rohacell);
rohacellBaseWithHole->SetLineColor(kGray);
rotation = new TGeoRotation ("rotation", 0., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., 0., rotation);
rohacellPlate -> AddNode(rohacellBaseWithHole, 0, new TGeoTranslation(0., 0., fZPlan[disk]));
ty = fSupportYDimensions[disk][0];
for (Int_t ipart=1; ipart<fnPart[disk]; ipart ++) {
ty += fSupportYDimensions[disk][ipart]/2.;
TGeoVolume *partRohacell = gGeoManager->MakeBox(Form("partRohacelli_D3_H%d_%d", half, ipart), rohacell, fSupportXDimensions[disk][ipart]/2.,
fSupportYDimensions[disk][ipart]/2., fRohacellThickness);
partRohacell->SetLineColor(kGray);
TGeoTranslation *t = new TGeoTranslation ("t", 0, ty + fHalfDiskGap, fZPlan[disk]);
rohacellPlate -> AddNode(partRohacell, ipart, t);
ty += fSupportYDimensions[disk][ipart]/2.;
}
// if (half == kTop) {
// rotation = new TGeoRotation ("rotation", 0., 0., 0.);
// transformation = new TGeoCombiTrans(0., 0., 0., rotation);
// fHalfDisk->AddNode(rohacellPlate, 1, transformation);
// }
// if (half == kBottom) {
rotation = new TGeoRotation ("rotation", 180., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., 0., rotation);
fHalfDisk->AddNode(rohacellPlate, 2, transformation);
// }
}
//====================================================================================================================================================
void AliMFTHeatExchanger::CreateHalfDisk4(Int_t half) {
Int_t disk = 4;
if (half == kTop) printf("Creating MFT heat exchanger for disk4 top\n");
else if (half == kBottom) printf("Creating MFT heat exchanger for disk4 bottom\n");
else printf("No valid option for MFT heat exchanger on disk4\n");
//TGeoMedium *carbon = gGeoManager->GetMedium("MFT_Carbon$");
TGeoMedium *carbon = gGeoManager->GetMedium("MFT_CarbonFiber$");
TGeoMedium *water = gGeoManager->GetMedium("MFT_Water$");
TGeoMedium *rohacell = gGeoManager->GetMedium("MFT_Rohacell");
TGeoMedium *pipe = gGeoManager->GetMedium("MFT_Polyimide");
TGeoVolumeAssembly *cooling = new TGeoVolumeAssembly(Form("cooling_D4_H%d",half));
Double_t deltaz= fHeatExchangerThickness - fCarbonThickness*2; //distance between pair of carbon plans
TGeoTranslation *translation = 0;
TGeoRotation *rotation = 0;
TGeoCombiTrans *transformation = 0;
Double_t lMiddle4[3] = {fSupportXDimensions[4][0] - 2*fLwater4[0], fSupportXDimensions[4][0] - 2*fLwater4[1], fSupportXDimensions[4][0] - 2*fLwater4[2]}; //distance between tube part
fangle4[5] = (fangle4[3] - fangle4[4]);
Double_t anglerad[6]= {0.}; //angle of the sides torus
for(Int_t i=0; i<6; i++){
anglerad[i] = fangle4[i]*(TMath::DegToRad());
}
Double_t fradius4mid[3] = { (lMiddle4[0]-2.*(fradius4[0]*(TMath::Sin(anglerad[0])) + fLpartial4[0]*(TMath::Cos(anglerad[0]))))/(2*(TMath::Sin(anglerad[0]))) ,
(lMiddle4[1]-2.*(fradius4[1]*(TMath::Sin(anglerad[1])) + fLpartial4[1]*(TMath::Cos(anglerad[1]))))/(2*(TMath::Sin(anglerad[1]))), 0. }; // radius of the central torus
fradius4mid[2] = (fSupportXDimensions[4][0]/2. - fradius4[3]*TMath::Sin(anglerad[3]) - fradius4[4]*(TMath::Sin(anglerad[3]) -
TMath::Sin(anglerad[5])))/(TMath::Sin(anglerad[5]));
// **************************************** Water part ****************************************
// ------------------- First and second pipe -------------------
for (Int_t i=0; i<2; i++){
// -------- Tube shape --------
TGeoVolume *waterTube1 = gGeoManager->MakeTube(Form("waterTubeone%d_D4_H%d", i,half), water, 0., fRWater, fLwater4[i]/2.);
waterTube1->SetLineColor(kBlue);
translation = new TGeoTranslation (fXposition4[i], 0., fLwater4[i]/2. + lMiddle4[i]/2.);
cooling->AddNode (waterTube1, 1, translation);
translation = new TGeoTranslation (fXposition4[i], 0., -fLwater4[i]/2. - lMiddle4[i]/2.);
cooling->AddNode (waterTube1, 2, translation);
TGeoVolume *waterTube2 = gGeoManager->MakeTube(Form("waterTubetwo%d_D4_H%d", i,half), water, 0., fRWater, fLpartial4[i]/2.);
waterTube2->SetLineColor(kBlue);
rotation = new TGeoRotation ("rotation", -90., - fangle4[i], 0.);
transformation = new TGeoCombiTrans( fXposition4[i]+fradius4[i]*(1-(TMath::Cos(anglerad[i])))+fLpartial4[i]*TMath::Sin(anglerad[i])/2., 0.,
-fSupportXDimensions[4][0]/2. + fLwater4[i] + fradius4[i]*(TMath::Sin(anglerad[i])) +
fLpartial4[i]*(TMath::Cos(anglerad[i]))/2., rotation);
cooling->AddNode (waterTube2, 3, transformation);
rotation = new TGeoRotation ("rotation", -90., fangle4[i], 0.);
transformation = new TGeoCombiTrans( fXposition4[i]+fradius4[i]*(1-(TMath::Cos(anglerad[i])))+fLpartial4[i]*TMath::Sin(anglerad[i])/2., 0.,
fSupportXDimensions[4][0]/2. - fLwater4[i] - fradius4[i]*(TMath::Sin(anglerad[i])) -
fLpartial4[i]*(TMath::Cos(anglerad[i]))/2. , rotation);
cooling->AddNode (waterTube2, 4, transformation);
// -------- Torus shape --------
TGeoVolume *waterTorus1 = gGeoManager->MakeTorus(Form("waterTorusone%d_D4_H%d", i,half), water, fradius4[i], 0., fRWater, 0., fangle4[i]);
waterTorus1->SetLineColor(kBlue);
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fXposition4[i] + fradius4[i], 0., -fSupportXDimensions[4][0]/2. + fLwater4[i], rotation);
cooling->AddNode (waterTorus1, 1, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 0.);
transformation = new TGeoCombiTrans(fXposition4[i] + fradius4[i], 0., fSupportXDimensions[4][0]/2. - fLwater4[i], rotation);
cooling->AddNode (waterTorus1, 2, transformation);
TGeoVolume *waterTorus2 = gGeoManager->MakeTorus(Form("waterTorustwo%d_D4_H%d", i,half), water, fradius4mid[i], 0., fRWater, 180 - fangle4[i] ,2*fangle4[i]);
waterTorus2->SetLineColor(kBlue);
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fXposition4[i] + fradius4[i]*(1-(TMath::Cos(anglerad[i])))+fLpartial4[i]*TMath::Sin(anglerad[i]) -
fradius4mid[i]*TMath::Cos(anglerad[i]), 0., 0., rotation);
cooling->AddNode (waterTorus2, 3, transformation);
}
// ------------------- Third pipe -------------------
// -------- Tube shape --------
TGeoVolume *waterTube1 = gGeoManager->MakeTube(Form("waterTubeone2_D4_H%d", half), water, 0., fRWater, fLwater4[2]/2.);
waterTube1->SetLineColor(kBlue);
translation = new TGeoTranslation (fXposition4[2], 0., fLwater4[2]/2. + lMiddle4[2]/2.);
cooling->AddNode (waterTube1, 1, translation);
translation = new TGeoTranslation (fXposition4[2], 0., -fLwater4[2]/2. - lMiddle4[2]/2.);
cooling->AddNode (waterTube1, 2, translation);
TGeoVolume *waterTube2 = gGeoManager->MakeTube(Form("waterTubetwo2_D4_H%d", half), water, 0., fRWater, lMiddle4[2]/2. - 2.*fradius4[2]*TMath::Sin(anglerad[2]));
waterTube2->SetLineColor(kBlue);
translation = new TGeoTranslation (fXposition4[2] + 2.*fradius4[2]*(1-TMath::Cos(anglerad[2])), 0., 0.);
cooling->AddNode (waterTube2, 3, translation);
// -------- Torus shape --------
TGeoVolume *waterTorus1 = gGeoManager->MakeTorus(Form("waterTorusone2_D4_H%d", half), water, fradius4[2], 0., fRWater, 0., fangle4[2]);
waterTorus1->SetLineColor(kBlue);
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fXposition4[2] + fradius4[2], 0., -fSupportXDimensions[4][0]/2. + fLwater4[2], rotation);
cooling->AddNode (waterTorus1, 1, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 180 - fangle4[2]);
transformation = new TGeoCombiTrans(fXposition4[2] + fradius4[2] - 2*fradius4[2]*TMath::Cos(anglerad[2]), 0.,
-fSupportXDimensions[4][0]/2. + fLwater4[2] + 2*fradius4[2]*TMath::Sin(anglerad[2]), rotation);
cooling->AddNode (waterTorus1, 2, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 0.);
transformation = new TGeoCombiTrans(fXposition4[2] + fradius4[2], 0., fSupportXDimensions[4][0]/2. - fLwater4[2], rotation);
cooling->AddNode (waterTorus1, 3, transformation);
rotation = new TGeoRotation ("rotation", 180., 90., 180 - fangle4[2]);
transformation = new TGeoCombiTrans(fXposition4[2] + fradius4[2] - 2*fradius4[2]*TMath::Cos(anglerad[2]), 0.,
fSupportXDimensions[4][0]/2. - fLwater4[2] - 2*fradius4[2]*TMath::Sin(anglerad[2]), rotation);
cooling->AddNode (waterTorus1, 4, transformation);
// ------------------- Fourth pipe -------------------
waterTorus1 = gGeoManager->MakeTorus(Form("waterTorusone3_D4_H%d", half), water, fradius4[3], 0., fRWater, 0., fangle4[3]);
waterTorus1->SetLineColor(kBlue);
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fXposition4[3] + fradius4[3], 0., -fSupportXDimensions[4][0]/2., rotation);
cooling->AddNode (waterTorus1, 1, transformation);
TGeoVolume *waterTorus2 = gGeoManager->MakeTorus(Form("waterTorustwo3_D4_H%d", half), water, fradius4[4] , 0., fRWater, 0., fangle4[4]);
waterTorus2->SetLineColor(kBlue);
rotation = new TGeoRotation ("rotation", 180., -90., 180 - fangle4[3]);
transformation = new TGeoCombiTrans( fXposition4[3] + fradius4[3] - fradius4[3]*TMath::Cos(anglerad[3]) -
fradius4[4]*TMath::Cos(anglerad[3]), 0., -fSupportXDimensions[4][0]/2. +
fradius4[3]*TMath::Sin(anglerad[3]) + fradius4[4]*TMath::Sin(anglerad[3]), rotation);
cooling->AddNode (waterTorus2, 1, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 0.);
transformation = new TGeoCombiTrans(fXposition4[3] + fradius4[3], 0., fSupportXDimensions[4][0]/2., rotation);
cooling->AddNode (waterTorus1, 2, transformation);
rotation = new TGeoRotation ("rotation", 180., 90., 180 - fangle4[3]);
transformation = new TGeoCombiTrans( fXposition4[3] + fradius4[3] - fradius4[3]*TMath::Cos(anglerad[3]) -
fradius4[4]*TMath::Cos(anglerad[3]), 0., fSupportXDimensions[4][0]/2. -
fradius4[3]*TMath::Sin(anglerad[3]) - fradius4[4]*TMath::Sin(anglerad[3]), rotation);
cooling->AddNode (waterTorus2, 2, transformation);
TGeoVolume *waterTorus3 = gGeoManager->MakeTorus(Form("waterTorusthree3_D4_H%d", half), water, fradius4mid[2] , 0., fRWater, -fangle4[5], 2.*fangle4[5]);
waterTorus3->SetLineColor(kBlue);
rotation = new TGeoRotation ("rotation", 0., 90., 0.);
transformation = new TGeoCombiTrans( fXposition4[3] + fradius4[3] - fradius4[3]*TMath::Cos(anglerad[3]) -
fradius4[4]*TMath::Cos(anglerad[3]) - ((fradius4mid[2] - fradius4[4])*TMath::Cos(anglerad[5])), 0., 0., rotation);
cooling->AddNode (waterTorus3, 1, transformation);
// ------------------- Fifth pipe -------------------
fangle4fifth[3] = fangle4fifth[0] - fangle4fifth[1] + fangle4fifth[2];
Double_t angle4fifthrad[4] = {0., 0., 0., 0.};
for(Int_t i=0; i<4; i++){
angle4fifthrad[i] = (TMath::Pi())*(fangle4fifth[i])/180.;
}
Double_t beta4fourth[4] = {0, fangle4fifth[0], fangle4fifth[0] - fangle4fifth[1], 180}; //shift angle
Double_t beta4fourthrad[4] = {};
for(Int_t i=0; i<4; i++){
beta4fourthrad[i] = (TMath::Pi())*(beta4fourth[i])/180.;
}
Double_t translation4x[4] = { fXposition4[4] + fradius4fifth[0]*(TMath::Cos(beta4fourthrad[0])),
fXposition4[4] + fradius4fifth[0]*((TMath::Cos(beta4fourthrad[0])) - TMath::Cos(beta4fourthrad[0] + angle4fifthrad[0])) -
fradius4fifth[1]*(TMath::Cos(beta4fourthrad[0] + angle4fifthrad[0])),
fXposition4[4] + fradius4fifth[0]*((TMath::Cos(beta4fourthrad[0])) - TMath::Cos(beta4fourthrad[0] + angle4fifthrad[0])) -
fradius4fifth[1]*(TMath::Cos(beta4fourthrad[0] + angle4fifthrad[0])) +
fradius4fifth[1]*(TMath::Sin(TMath::Pi()/2. - angle4fifthrad[1] + angle4fifthrad[0] + beta4fourthrad[0])) +
fradius4fifth[2]*(TMath::Cos(angle4fifthrad[1] - angle4fifthrad[0] - beta4fourthrad[0])),
fXposition4[4] + fradius4fifth[0]*((TMath::Cos(beta4fourthrad[0])) - TMath::Cos(beta4fourthrad[0] + angle4fifthrad[0])) -
fradius4fifth[1]*(TMath::Cos(beta4fourthrad[0] + angle4fifthrad[0])) +
fradius4fifth[1]*(TMath::Sin(TMath::Pi()/2. - angle4fifthrad[1] + angle4fifthrad[0] + beta4fourthrad[0])) +
fradius4fifth[2]*(TMath::Cos(angle4fifthrad[1] - angle4fifthrad[0] - beta4fourthrad[0])) -
fradius4fifth[2]*(TMath::Sin((TMath::Pi()/2.) - angle4fifthrad[3])) - fradius4fifth[3]*(TMath::Cos(angle4fifthrad[3]))};
Double_t translation4y[4] = {0., 0., 0., 0.};
Double_t translation4z[4] = {-(fLwater4[0] + lMiddle4[0]/2.) - fradius4fifth[0]*(TMath::Sin(beta4fourthrad[0])),
-(fLwater4[0] + lMiddle4[0]/2.) - fradius4fifth[0]*(TMath::Sin(beta4fourthrad[0])) +
fradius4fifth[0]*(TMath::Sin(beta4fourthrad[0] + angle4fifthrad[0])) +
fradius4fifth[1]*(TMath::Sin(beta4fourthrad[0] + angle4fifthrad[0])),
-(fLwater4[0] + lMiddle4[0]/2.) - fradius4fifth[0]*(TMath::Sin(beta4fourthrad[0])) +
fradius4fifth[0]*(TMath::Sin(beta4fourthrad[0] + angle4fifthrad[0])) +
fradius4fifth[1]*(TMath::Cos(TMath::Pi()/2 - beta4fourthrad[0] - angle4fifthrad[0])) +
fradius4fifth[1]*(TMath::Cos(TMath::Pi()/2. - angle4fifthrad[1] + angle4fifthrad[0] + beta4fourthrad[0])) +
fradius4fifth[2]*(TMath::Sin(angle4fifthrad[1] - angle4fifthrad[0] - beta4fourthrad[0])),
-(fLwater4[0] + lMiddle4[0]/2.) - fradius4fifth[0]*(TMath::Sin(beta4fourthrad[0])) +
fradius4fifth[0]*(TMath::Sin(beta4fourthrad[0] + angle4fifthrad[0])) +
fradius4fifth[1]*(TMath::Cos(TMath::Pi()/2 - beta4fourthrad[0] - angle4fifthrad[0])) +
fradius4fifth[1]*(TMath::Cos(TMath::Pi()/2. - angle4fifthrad[1] + angle4fifthrad[0] + beta4fourthrad[0])) +
fradius4fifth[2]*(TMath::Sin(angle4fifthrad[1] - angle4fifthrad[0] - beta4fourthrad[0])) +
(fradius4fifth[3] + fradius4fifth[2])*(TMath::Sin(angle4fifthrad[3]))
};
Double_t rotation4x[4] = {180., 180., 180., 180};
Double_t rotation4y[4] = {90., 90., 90., 90};
Double_t rotation4z[4] = {0., 180 - fangle4fifth[1] , 0., 0.};
for (Int_t i= 0; i<4; i++){
waterTorus1 = gGeoManager->MakeTorus(Form("waterTorusone%d_D4_H%d", i,half), water, fradius4fifth[i], 0., fRWater, beta4fourth[i], fangle4fifth[i]);
waterTorus1->SetLineColor(kBlue);
rotation = new TGeoRotation ("rotation", rotation4x[i], rotation4y[i], rotation4z[i]);
transformation = new TGeoCombiTrans(translation4x[i], translation4y[i], translation4z[i], rotation);
cooling->AddNode (waterTorus1, 7, transformation);
rotation = new TGeoRotation ("rotation", rotation4x[i] , rotation4y[i] - 180, rotation4z[i]);
transformation = new TGeoCombiTrans(translation4x[i], translation4y[i], - translation4z[i], rotation);
cooling->AddNode (waterTorus1, 8, transformation);
}
TGeoVolume *waterTubeFive = gGeoManager->MakeTube(Form("waterTubeFive1_D4_H%d",half), water, 0., fRWater, -translation4z[3]);
waterTubeFive->SetLineColor(kBlue);
rotation = new TGeoRotation ("rotation", 0., 0., 0.);
transformation = new TGeoCombiTrans(translation4x[3] + fradius4fifth[3], 0., 0., rotation);
cooling->AddNode(waterTubeFive, 1, transformation);
// **************************************** Pipe part ****************************************
// ------------------- First and second pipe -------------------
for(Int_t i=0; i<2; i++){
// -------- Tube shape --------
TGeoVolume *pipeTube1 = gGeoManager->MakeTube(Form("pipeTubeone%d_D4_H%d", i,half), pipe, fRWater, fRWater + fDRPipe, fLwater4[i]/2.);
pipeTube1->SetLineColor(10);
translation = new TGeoTranslation (fXposition4[i], 0., fLwater4[i]/2. + lMiddle4[i]/2.);
cooling->AddNode (pipeTube1, 1, translation);
translation = new TGeoTranslation (fXposition4[i], 0., -fLwater4[i]/2. - lMiddle4[i]/2.);
cooling->AddNode (pipeTube1, 2, translation);
TGeoVolume *pipeTube2 = gGeoManager->MakeTube(Form("pipeTubetwo%d_D4_H%d", i,half), pipe, fRWater, fRWater + fDRPipe, fLpartial4[i]/2.);
pipeTube2->SetLineColor(10);
rotation = new TGeoRotation ("rotation", -90., - fangle4[i], 0.);
transformation = new TGeoCombiTrans( fXposition4[i]+fradius4[i]*(1-(TMath::Cos(anglerad[i])))+fLpartial4[i]*TMath::Sin(anglerad[i])/2., 0.,
-fSupportXDimensions[4][0]/2. + fLwater4[i] + fradius4[i]*(TMath::Sin(anglerad[i])) +
fLpartial4[i]*(TMath::Cos(anglerad[i]))/2., rotation);
cooling->AddNode (pipeTube2, 3, transformation);
rotation = new TGeoRotation ("rotation", -90., fangle4[i], 0.);
transformation = new TGeoCombiTrans( fXposition4[i]+fradius4[i]*(1-(TMath::Cos(anglerad[i])))+fLpartial4[i]*TMath::Sin(anglerad[i])/2., 0.,
fSupportXDimensions[4][0]/2. - fLwater4[i] - fradius4[i]*(TMath::Sin(anglerad[i])) -
fLpartial4[i]*(TMath::Cos(anglerad[i]))/2. , rotation);
cooling->AddNode (pipeTube2, 4, transformation);
// -------- Torus shape --------
TGeoVolume *pipeTorus1 = gGeoManager->MakeTorus(Form("pipeTorusone%d_D4_H%d", i,half), pipe, fradius4[i], fRWater, fRWater + fDRPipe, 0., fangle4[i]);
pipeTorus1->SetLineColor(10);
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fXposition4[i] + fradius4[i], 0., -fSupportXDimensions[4][0]/2. + fLwater4[i], rotation);
cooling->AddNode (pipeTorus1, 1, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 0.);
transformation = new TGeoCombiTrans(fXposition4[i] + fradius4[i], 0., fSupportXDimensions[4][0]/2. - fLwater4[i], rotation);
cooling->AddNode (pipeTorus1, 2, transformation);
TGeoVolume *pipeTorus2 = gGeoManager->MakeTorus(Form("pipeTorustwo%d_D4_H%d", i,half), pipe, fradius4mid[i], fRWater, fRWater + fDRPipe, 180 - fangle4[i] ,2*fangle4[i]);
pipeTorus2->SetLineColor(10);
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fXposition4[i] + fradius4[i]*(1-(TMath::Cos(anglerad[i])))+fLpartial4[i]*TMath::Sin(anglerad[i]) -
fradius4mid[i]*TMath::Cos(anglerad[i]), 0., 0., rotation);
cooling->AddNode (pipeTorus2, 3, transformation);
}
// ------------------- Third pipe -------------------
// -------- Tube shape --------
TGeoVolume *pipeTube1 = gGeoManager->MakeTube(Form("pipeTubeone2_D4_H%d",half), pipe, fRWater, fRWater + fDRPipe, fLwater4[2]/2.);
pipeTube1->SetLineColor(10);
translation = new TGeoTranslation (fXposition4[2], 0., fLwater4[2]/2. + lMiddle4[2]/2.);
cooling->AddNode (pipeTube1, 1, translation);
translation = new TGeoTranslation (fXposition4[2], 0., -fLwater4[2]/2. - lMiddle4[2]/2.);
cooling->AddNode (pipeTube1, 2, translation);
TGeoVolume *pipeTube2 = gGeoManager->MakeTube(Form("pipeTubetwo2_D4_H%d",half), pipe, fRWater, fRWater + fDRPipe, lMiddle4[2]/2. - 2.*fradius4[2]*TMath::Sin(anglerad[2]));
pipeTube2->SetLineColor(10);
translation = new TGeoTranslation (fXposition4[2] + 2.*fradius4[2]*(1-TMath::Cos(anglerad[2])), 0., 0.);
cooling->AddNode (pipeTube2, 3, translation);
// -------- Torus shape --------
TGeoVolume *pipeTorus1 = gGeoManager->MakeTorus(Form("pipeTorusone2_D4_H%d",half), pipe, fradius4[2], fRWater, fRWater + fDRPipe, 0., fangle4[2]);
pipeTorus1->SetLineColor(10);
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fXposition4[2] + fradius4[2], 0., -fSupportXDimensions[4][0]/2. + fLwater4[2], rotation);
cooling->AddNode (pipeTorus1, 1, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 180 - fangle4[2]);
transformation = new TGeoCombiTrans(fXposition4[2] + fradius4[2] - 2*fradius4[2]*TMath::Cos(anglerad[2]), 0.,
-fSupportXDimensions[4][0]/2. + fLwater4[2] + 2*fradius4[2]*TMath::Sin(anglerad[2]), rotation);
cooling->AddNode (pipeTorus1, 2, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 0.);
transformation = new TGeoCombiTrans(fXposition4[2] + fradius4[2], 0., fSupportXDimensions[4][0]/2. - fLwater4[2], rotation);
cooling->AddNode (pipeTorus1, 3, transformation);
rotation = new TGeoRotation ("rotation", 180., 90., 180 - fangle4[2]);
transformation = new TGeoCombiTrans(fXposition4[2] + fradius4[2] - 2*fradius4[2]*TMath::Cos(anglerad[2]), 0.,
fSupportXDimensions[4][0]/2. - fLwater4[2] - 2*fradius4[2]*TMath::Sin(anglerad[2]), rotation);
cooling->AddNode (pipeTorus1, 4, transformation);
// ------------------- Fourth pipe -------------------
pipeTorus1 = gGeoManager->MakeTorus(Form("pipeTorusone3_D4_H%d",half), pipe, fradius4[3], fRWater, fRWater + fDRPipe, 0., fangle4[3]);
pipeTorus1->SetLineColor(10);
rotation = new TGeoRotation ("rotation", 180., 90., 0.);
transformation = new TGeoCombiTrans(fXposition4[3] + fradius4[3], 0., -fSupportXDimensions[4][0]/2., rotation);
cooling->AddNode (pipeTorus1, 1, transformation);
TGeoVolume *pipeTorus2 = gGeoManager->MakeTorus(Form("pipeTorustwo3_D4_H%d",half), pipe, fradius4[4] , fRWater, fRWater + fDRPipe, 0., fangle4[4]);
pipeTorus2->SetLineColor(10);
rotation = new TGeoRotation ("rotation", 180., -90., 180 - fangle4[3]);
transformation = new TGeoCombiTrans( fXposition4[3] + fradius4[3] - fradius4[3]*TMath::Cos(anglerad[3]) -
fradius4[4]*TMath::Cos(anglerad[3]), 0., -fSupportXDimensions[4][0]/2. +
fradius4[3]*TMath::Sin(anglerad[3]) + fradius4[4]*TMath::Sin(anglerad[3]), rotation);
cooling->AddNode (pipeTorus2, 1, transformation);
rotation = new TGeoRotation ("rotation", 180., -90., 0.);
transformation = new TGeoCombiTrans(fXposition4[3] + fradius4[3], 0., fSupportXDimensions[4][0]/2. , rotation);
cooling->AddNode (pipeTorus1, 2, transformation);
rotation = new TGeoRotation ("rotation", 180., 90., 180 - fangle4[3]);
transformation = new TGeoCombiTrans( fXposition4[3] + fradius4[3] - fradius4[3]*TMath::Cos(anglerad[3]) -
fradius4[4]*TMath::Cos(anglerad[3]), 0., fSupportXDimensions[4][0]/2. -
fradius4[3]*TMath::Sin(anglerad[3]) - fradius4[4]*TMath::Sin(anglerad[3]), rotation);
cooling->AddNode (pipeTorus2, 2, transformation);
TGeoVolume *pipeTorus3 = gGeoManager->MakeTorus(Form("pipeTorusthree3_D4_H%d",half), pipe, fradius4mid[2] , fRWater, fRWater + fDRPipe, -fangle4[5], 2.*fangle4[5]);
pipeTorus3->SetLineColor(10);
rotation = new TGeoRotation ("rotation", 0., 90., 0.);
transformation = new TGeoCombiTrans( fXposition4[3] + fradius4[3] - fradius4[3]*TMath::Cos(anglerad[3]) -
fradius4[4]*TMath::Cos(anglerad[3]) - ((fradius4mid[2] - fradius4[4])*TMath::Cos(anglerad[5])), 0., 0., rotation);
cooling->AddNode (pipeTorus3, 1, transformation);
// ------------------- Fifth pipe -------------------
for(Int_t i= 0; i<4; i++){
pipeTorus1 = gGeoManager->MakeTorus(Form("pipeTorusone%d_D4_H%d", i,half), pipe, fradius4fifth[i], fRWater, fRWater + fDRPipe, beta4fourth[i], fangle4fifth[i]);
pipeTorus1->SetLineColor(10);
rotation = new TGeoRotation ("rotation", rotation4x[i], rotation4y[i], rotation4z[i]);
transformation = new TGeoCombiTrans(translation4x[i], translation4y[i], translation4z[i], rotation);
cooling->AddNode (pipeTorus1, 7, transformation);
rotation = new TGeoRotation ("rotation", rotation4x[i] , rotation4y[i] - 180, rotation4z[i]);
transformation = new TGeoCombiTrans(translation4x[i], translation4y[i], - translation4z[i], rotation);
cooling->AddNode (pipeTorus1, 8, transformation);
}
TGeoVolume *pipeTubeFive = gGeoManager->MakeTube(Form("pipeTubeFive1_D4_H%d", half), pipe, fRWater, fRWater + fDRPipe, -translation4z[3]);
pipeTubeFive->SetLineColor(10);
rotation = new TGeoRotation ("rotation", 0., 0., 0.);
transformation = new TGeoCombiTrans(translation4x[3] + fradius4fifth[3], 0., 0., rotation);
cooling->AddNode(pipeTubeFive, 1, transformation);
// if (half == kTop) {
// rotation = new TGeoRotation ("rotation", 90., 90., 0.);
// transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] + deltaz/2. - fCarbonThickness - fRWater - fDRPipe, rotation);
// fHalfDisk->AddNode(cooling, 1, transformation);
// transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] - deltaz/2. + fCarbonThickness + fRWater + fDRPipe, rotation);
// fHalfDisk->AddNode(cooling, 2, transformation);
// }
// else if (half == kBottom) {
rotation = new TGeoRotation ("rotation", -90., 90., 0.);
transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] + deltaz/2. - fCarbonThickness - fRWater - fDRPipe, rotation);
fHalfDisk->AddNode(cooling, 3, transformation);
transformation = new TGeoCombiTrans(0., 0., fZPlan[disk] - deltaz/2. + fCarbonThickness + fRWater + fDRPipe, rotation);
fHalfDisk->AddNode(cooling, 4, transformation);
// }
// **************************************** Carbon Plates ****************************************
TGeoVolumeAssembly *carbonPlate = new TGeoVolumeAssembly(Form("carbonPlate_D4_H%d",half));
TGeoBBox *carbonBase4 = new TGeoBBox (Form("carbonBase4_D4_H%d",half), (fSupportXDimensions[disk][0])/2., (fSupportYDimensions[disk][0])/2., fCarbonThickness);
TGeoTranslation *t41= new TGeoTranslation ("t41",0., (fSupportYDimensions[disk][0])/2. + fHalfDiskGap, 0.);
t41-> RegisterYourself();
TGeoTubeSeg *holeCarbon4 = new TGeoTubeSeg(Form("holeCarbon4_D4_H%d",half), 0., fRMin[disk], fCarbonThickness + 0.000001, 0, 180.);
TGeoTranslation *t42= new TGeoTranslation ("t42",0., - fHalfDiskGap , 0.);
t42-> RegisterYourself();
///TGeoCompositeShape *cs4 = new TGeoCompositeShape(Form("Carbon4_D4_H%d",half),Form("(carbonBase4_D4_H%d:t41)-(holeCarbon4_D4_H%d:t42)",half,half));
TGeoSubtraction *carbonhole4 = new TGeoSubtraction(carbonBase4, holeCarbon4, t41, t42);
TGeoCompositeShape *cs4 = new TGeoCompositeShape(Form("Carbon4_D4_H%d",half), carbonhole4);
TGeoVolume *carbonBaseWithHole4 = new TGeoVolume(Form("carbonBaseWithHole_D4_H%d",half), cs4, carbon);
carbonBaseWithHole4->SetLineColor(kGray+3);
rotation = new TGeoRotation ("rotation", 0., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., 0., rotation);
carbonPlate->AddNode(carbonBaseWithHole4, 0, new TGeoTranslation(0., 0., fZPlan[disk]));
Double_t ty = fSupportYDimensions[disk][0];
for (Int_t ipart=1; ipart<fnPart[disk]; ipart ++) {
ty += fSupportYDimensions[disk][ipart]/2.;
TGeoVolume *partCarbon = gGeoManager->MakeBox(Form("partCarbon_D4_H%d_%d", half,ipart), carbon, fSupportXDimensions[disk][ipart]/2.,
fSupportYDimensions[disk][ipart]/2., fCarbonThickness);
partCarbon->SetLineColor(kGray+3);
TGeoTranslation *t = new TGeoTranslation ("t", 0, ty + fHalfDiskGap, fZPlan[disk]);
carbonPlate -> AddNode(partCarbon, ipart, t);
ty += fSupportYDimensions[disk][ipart]/2.;
}
// if (half == kTop) {
// rotation = new TGeoRotation ("rotation", 0., 0., 0.);
// transformation = new TGeoCombiTrans(0., 0., deltaz/2., rotation);
// fHalfDisk->AddNode(carbonPlate, 1, transformation);
// transformation = new TGeoCombiTrans(0., 0., -deltaz/2., rotation);
// fHalfDisk->AddNode(carbonPlate, 2, transformation);
// }
// else if (half == kBottom) {
rotation = new TGeoRotation ("rotation", 180., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., deltaz/2., rotation);
fHalfDisk->AddNode(carbonPlate, 3, transformation);
transformation = new TGeoCombiTrans(0., 0., -deltaz/2., rotation);
fHalfDisk->AddNode(carbonPlate, 4, transformation);
// }
// **************************************** Rohacell Plate ****************************************
TGeoVolumeAssembly *rohacellPlate = new TGeoVolumeAssembly(Form("rohacellPlate_D4_H%d",half));
TGeoBBox *rohacellBase4 = new TGeoBBox (Form("rohacellBase4_D4_H%d",half), (fSupportXDimensions[disk][0])/2., (fSupportYDimensions[disk][0])/2., fRohacellThickness);
// TGeoTranslation *t3 = new TGeoTranslation ("t3",0., (fSupportYDimensions[disk][0])/2. + fHalfDiskGap , 0.);
// t3 -> RegisterYourself();
TGeoTubeSeg *holeRohacell4 = new TGeoTubeSeg(Form("holeRohacell4_D4_H%d",half), 0., fRMin[disk], fRohacellThickness + 0.000001, 0, 180.);
// TGeoTranslation *t4= new TGeoTranslation ("t4", 0., - fHalfDiskGap , 0.);
// t4-> RegisterYourself();
///cs4 = new TGeoCompositeShape(Form("rohacell_D4_H%d",half), Form("(rohacellBase4_D4_H%d:t41)-(holeRohacell4_D4_H%d:t42)",half,half));
TGeoSubtraction *rohacellhole4 = new TGeoSubtraction(rohacellBase4, holeRohacell4, t41, t42);
TGeoCompositeShape *rh4 = new TGeoCompositeShape(Form("rohacellBase4_D4_H%d",half), rohacellhole4);
TGeoVolume *rohacellBaseWithHole = new TGeoVolume(Form("rohacellBaseWithHole_D4_H%d",half), rh4, rohacell);
rohacellBaseWithHole->SetLineColor(kGray);
rotation = new TGeoRotation ("rotation", 0., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., 0., rotation);
rohacellPlate -> AddNode(rohacellBaseWithHole, 0, new TGeoTranslation(0., 0., fZPlan[disk]));
ty = fSupportYDimensions[disk][0];
for (Int_t ipart=1; ipart<fnPart[disk]; ipart ++) {
ty += fSupportYDimensions[disk][ipart]/2.;
TGeoVolume *partRohacell = gGeoManager->MakeBox(Form("partRohacelli_D4_H%d_%d", half, ipart), rohacell, fSupportXDimensions[disk][ipart]/2.,
fSupportYDimensions[disk][ipart]/2., fRohacellThickness);
partRohacell->SetLineColor(kGray);
TGeoTranslation *t = new TGeoTranslation ("t", 0, ty + fHalfDiskGap, fZPlan[disk]);
rohacellPlate -> AddNode(partRohacell, ipart, t);
ty += fSupportYDimensions[disk][ipart]/2.;
}
// if (half == kTop) {
// rotation = new TGeoRotation ("rotation", 0., 0., 0.);
// transformation = new TGeoCombiTrans(0., 0., 0., rotation);
// fHalfDisk->AddNode(rohacellPlate, 1, transformation);
// }
// if (half == kBottom) {
rotation = new TGeoRotation ("rotation", 180., 0., 0.);
transformation = new TGeoCombiTrans(0., 0., 0., rotation);
fHalfDisk->AddNode(rohacellPlate, 2, transformation);
// }
}
//====================================================================================================================================================
void AliMFTHeatExchanger::InitParameters() {
fNDisks = 5; // Should it be read from some other class?
for (Int_t idisk=0; idisk<fNMaxDisks; idisk++) {
for (Int_t ihalf=0; ihalf<kNHalves; ihalf++) {
fHalfDiskRotation[idisk][ihalf] = new TGeoRotation(Form("rotation%d%d", idisk, ihalf), 0., 0., 0.);
fHalfDiskTransformation[idisk][ihalf] = new TGeoCombiTrans(Form("transformation%d%d", idisk, ihalf), 0., 0., 0., fHalfDiskRotation[idisk][ihalf]);
}
}
fRohacellThickness = fHeatExchangerThickness/2. - 2.*fCarbonThickness - 2*(fRWater + fDRPipe);//thickness of Rohacell plate over 2
printf("Rohacell thickness %f \n",fRohacellThickness);
fHalfDiskGap = 0.2;
fnPart[0] = 3;
fnPart[1] = 3;
fnPart[2] = 3;
fnPart[3] = 5;
fnPart[4] = 4;
fRMin[0] = 2.35;
fRMin[1] = 2.35;
fRMin[2] = 2.35;
fRMin[3] = 3.35;
fRMin[4] = 3.75;
// fZPlan[0] = 46;
// fZPlan[1] = 49.3;
// fZPlan[2] = 53.1;
// fZPlan[3] = 68.7;
// fZPlan[4] = 76.8;
fZPlan[0] = 0;
fZPlan[1] = 0;
fZPlan[2] = 0;
fZPlan[3] = 0;
fZPlan[4] = 0;
fSupportXDimensions= new Double_t*[fNDisks];
fSupportYDimensions= new Double_t*[fNDisks];
for(Int_t i=0; i<fNDisks; i++) {
fSupportXDimensions[i]= new double[fnPart[i]];
fSupportYDimensions[i]= new double[fnPart[i]];
}
fSupportXDimensions[0][0]=21.; fSupportXDimensions[0][1]=14.8; fSupportXDimensions[0][2]=4.4;
fSupportXDimensions[1][0]=21.; fSupportXDimensions[1][1]=14.8; fSupportXDimensions[1][2]=4.4;
fSupportXDimensions[2][0]=22.6; fSupportXDimensions[2][1]=16.1; fSupportXDimensions[2][2]=9.3;
fSupportXDimensions[3][0]=28.4; fSupportXDimensions[3][1]=22.9; fSupportXDimensions[3][2]=18.5 ;fSupportXDimensions[3][3]=8.3; fSupportXDimensions[3][4]=4.9;
fSupportXDimensions[4][0]=28.4; fSupportXDimensions[4][1]=25.204; fSupportXDimensions[4][2]=21.9 ;fSupportXDimensions[4][3]=15.1;
fSupportYDimensions[0][0]=6.2; fSupportYDimensions[0][1]=3.5; fSupportYDimensions[0][2]=1.4;
fSupportYDimensions[1][0]=6.2; fSupportYDimensions[1][1]=3.5; fSupportYDimensions[1][2]=1.4;
fSupportYDimensions[2][0]=6.61; fSupportYDimensions[2][1]=3.01; fSupportYDimensions[2][2]=1.83;
fSupportYDimensions[3][0]=6.61; fSupportYDimensions[3][1]=3.01; fSupportYDimensions[3][2]=3.01 ;fSupportYDimensions[3][3]=1.8; fSupportYDimensions[3][4]=1.15;
fSupportYDimensions[4][0]=6.61; fSupportYDimensions[4][1]=3.01; fSupportYDimensions[4][2]=3.01 ;fSupportYDimensions[4][3]=2.42;
//Paramteters for disks 0, 1, 2
fLWater = 6.759;
fXPosition0[0] = 1.7;
fXPosition0[1] = 4.61;
fXPosition0[2] = 7.72;
fangle0 = 44.6;
fradius0 = 2.5;
fLpartial0 = 1.;
//Parameters for disk 3
fLWater3[0] = 8.032;
fLWater3[1] = 8.032;
fLWater3[2] = 8.2;
fXPosition3[0] = 1.7;
fXPosition3[1] = 4.61;
fXPosition3[2] = 5.5;
fXPosition3[3] = 6.81;
fangle3[0] = 41.3;
fangle3[1] = 41.3;
fangle3[2] = 28;
fradius3[0] = 4.3;
fradius3[1] = 4.3;
fradius3[2] = 7.4;
fangleThirdPipe3 = 15.;
fLpartial3[0] = 2.3;
fLpartial3[1] = 2.3;
fradius3fourth[0] = 9.6;
fradius3fourth[1] = 2.9;
fradius3fourth[2] = 2.9;
fradius3fourth[3] = 0.;
fangle3fourth[0] = 40.8;
fangle3fourth[1] = 50.;
fangle3fourth[2] = 60.;
fangle3fourth[3] = 8 + fangle3fourth[0] - fangle3fourth[1] + fangle3fourth[2];
// Parameters for disk 4
fLwater4[0] = 5.911;
fLwater4[1] = 3.697;
fLwater4[2] = 3.038;
fXposition4[0] = 1.7;
fXposition4[1] = 3.492;
fXposition4[2] = 4.61;
fXposition4[3] = 5.5;
fXposition4[4] = 6.5;
fangle4[0] = 35.5;
fangle4[1] = 30.;
fangle4[2] = 54.;
fangle4[3] = 53.;
fangle4[4] = 40;
fangle4[5] = (fangle4[3] - fangle4[4]);
fradius4[0] = 6.6;
fradius4[1] = 7.2;
fradius4[2] = 4.6;
fradius4[3] = 6.2;
fradius4[4] = 6.;
fLpartial4[0] = 2.5;
fLpartial4[1] = 3.6;
fangle4fifth[0] = 64.;
fangle4fifth[1] = 30.;
fangle4fifth[2] = 27.;
fangle4fifth[3] = fangle4fifth[0] - fangle4fifth[1] + fangle4fifth[2];
fradius4fifth[0] = 2.7;
fradius4fifth[1] = 5.;
fradius4fifth[2] = 5.1;
fradius4fifth[3] = 4.3;
}
//====================================================================================================================================================
| 54.45104 | 201 | 0.631197 | ktf |
4cd55852ec32beaa75fc2bdaa2352f679e427c03 | 9,327 | cpp | C++ | Tests/Core/Math/test_matrix.cpp | xctan/ClanLib | 1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d | [
"Linux-OpenIB"
] | 248 | 2015-01-08T05:21:40.000Z | 2022-03-20T02:59:16.000Z | Tests/Core/Math/test_matrix.cpp | xctan/ClanLib | 1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d | [
"Linux-OpenIB"
] | 39 | 2015-01-14T17:37:07.000Z | 2022-03-17T12:59:26.000Z | Tests/Core/Math/test_matrix.cpp | xctan/ClanLib | 1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d | [
"Linux-OpenIB"
] | 82 | 2015-01-11T13:23:49.000Z | 2022-02-19T03:17:24.000Z | /*
** ClanLib SDK
** Copyright (c) 1997-2020 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Mark Page
** (if your name is missing here, please add it)
*/
#include "test.h"
void TestApp::test_matrix(void)
{
Console::write_line(" Header: matrix4x4.h");
test_matrix_mat2();
test_matrix_mat3();
test_matrix_mat4();
}
void TestApp::test_matrix_mat3()
{
Console::write_line(" Class: Mat3");
Console::write_line(" Function: inverse()");
{
Mat3d test_src(2, 3, 4, 2, -5, 2, -3, 6, -3);
Mat3d test_inv;
Mat3d test_dest;
Mat3d test_ident = Mat3d::identity();
test_dest = test_src;
test_dest.inverse();
test_dest = test_dest * test_src;
if (test_ident != test_dest) fail();
Mat4d test_4d(test_src);
Mat3d test_3d(test_4d);
if (test_3d != test_src) fail();
test_4d =test_src;
test_3d =test_4d;
if (test_3d != test_src) fail();
}
Mat3i test_a(3, 1, 2, 4, 5 ,6, 4, 2, 1);
Mat3i test_b(4, 7, 2, 5, 3, 5, 2, 9, 3);
Console::write_line(" Function: multiply() and operator");
{
Mat3i result = test_b * test_a;
Mat3i answer(21, 42, 17, 53, 97, 51, 28, 43, 21);
if (result != answer) fail();
result = Mat3i::multiply(test_b, test_a);
if (result != answer) fail();
}
Console::write_line(" Function: add() and operator");
{
Mat3i result = test_a + test_b;
if (result != Mat3i(7, 8, 4, 9, 8, 11, 6, 11, 4)) fail();
result = Mat3i::add(test_a, test_b);
if (result != Mat3i(7, 8, 4, 9, 8, 11, 6, 11, 4)) fail();
}
Console::write_line(" Function: subtract() and operator");
{
Mat3i result = test_a - test_b;
if (result != Mat3i(-1, -6, 0, -1, 2, 1, 2, -7, -2)) fail();
result = Mat3i::subtract(test_a, test_b);
if (result != Mat3i(-1, -6, 0, -1, 2, 1, 2, -7, -2)) fail();
}
}
void TestApp::test_matrix_mat4()
{
Console::write_line(" Class: Mat4");
Console::write_line(" Function: inverse()");
{
Mat4f test_src = Mat4f::rotate((Angle(30, AngleUnit::degrees)), 1.0, 0.0, 0.0, true);
Mat4f test_inv;
Mat4f test_dest;
Mat4f test_ident = Mat4f::identity();
test_dest = test_src;
test_dest.inverse();
test_dest = test_dest * test_src;
if (test_ident != test_dest) fail();
}
static int test_a_values[] = {3, 1, 2, 4, 5 ,6, 4, 2, 1, 4, 6, 7, 6, 3, 7, 2};
static int test_b_values[] = {4, 7, 2, 5, 3, 5, 2, 9, 3, 3, 6, 9, 2, 4, 6, 2};
Mat4i test_a(test_a_values);
Mat4i test_b(test_b_values);
Mat4f test_c(test_a);
Mat4f test_c_scaled(test_c);
{
float x = 2.0f;
float y = 3.0f;
float z = 4.0f;
test_c_scaled[0 + 4 * 0] *= x;
test_c_scaled[0 + 4 * 1] *= y;
test_c_scaled[0 + 4 * 2] *= z;
test_c_scaled[1 + 4 * 0] *= x;
test_c_scaled[1 + 4 * 1] *= y;
test_c_scaled[1 + 4 * 2] *= z;
test_c_scaled[2 + 4 * 0] *= x;
test_c_scaled[2 + 4 * 1] *= y;
test_c_scaled[2 + 4 * 2] *= z;
test_c_scaled[3 + 4 * 0] *= x;
test_c_scaled[3 + 4 * 1] *= y;
test_c_scaled[3 + 4 * 2] *= z;
}
Console::write_line(" Function: add() and operator");
{
int answer_values[] = {7, 8, 4, 9, 8, 11, 6, 11, 4, 7, 12, 16, 8, 7, 13, 4};
Mat4i answer(answer_values);
Mat4i result = test_a + test_b;
if (result != answer) fail();
result = Mat4i::add(test_a, test_b);
if (result != answer) fail();
}
Console::write_line(" Function: subtract() and operator");
{
int answer_values[] = {-1, -6, 0, -1, 2, 1, 2, -7, -2, 1, 0, -2, 4, -1, 1, 0};
Mat4i answer(answer_values);
Mat4i result = test_a - test_b;
if (result != answer) fail();
result = Mat4i::subtract(test_a, test_b);
if (result != answer) fail();
}
Console::write_line(" Function: translate()");
{
int answer_values[] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 3, 4, 1};
Mat4i answer(answer_values);
Mat4i result = Mat4i::translate(2, 3, 4);
if (result != answer) fail();
}
Console::write_line(" Function: translate_self() (int)");
{
Mat4i answer(test_a);
Mat4i result = test_a;
result = result * Mat4i::translate(2, 3, 4);
Mat4i result2 = test_a;
result2.translate_self(2,3,4);
if (result != result2) fail();
}
Console::write_line(" Function: translate_self() (float)");
{
Mat4f answer(test_a);
Mat4f result(test_a);
result = result * Mat4f::translate(2, 3, 4);
Mat4f result2(test_a);
result2.translate_self(2, 3, 4);
if (!result.is_equal(result2, 0.00001f))
fail();
}
Console::write_line(" Function: scale_self()");
{
Mat4i answer(test_a);
Mat4i result = test_a;
result = result * Mat4i::scale(2, 3, 4);
Mat4i result2 = test_a;
result2.scale_self(2,3,4);
if (result != result2) fail();
Mat4f test = test_c;
test.scale_self(2.0f, 3.0f, 4.0f);
if (!test.is_equal(test_c_scaled, 0.00001f))
fail();
}
Console::write_line(" Function: rotate (using euler angles)");
{
Mat4f mv = Mat4f::identity();
mv = mv * Mat4f::rotate(Angle(30.0f, AngleUnit::degrees), 0.0f, 0.0f, 1.0f, false);
mv = mv * Mat4f::rotate(Angle(10.0f, AngleUnit::degrees), 1.0f, 0.0f, 0.0f, false);
mv = mv * Mat4f::rotate(Angle(20.0f, AngleUnit::degrees), 0.0f, 1.0f, 0.0f, false);
Mat4f test_matrix;
test_matrix = Mat4f::rotate(Angle(10.0f, AngleUnit::degrees), Angle(20.0f, AngleUnit::degrees), Angle(30.0f, AngleUnit::degrees), EulerOrder::YXZ);
if (!test_matrix.is_equal(mv, 0.00001f))
fail();
}
Console::write_line(" Function: rotate (using euler angles) and get_euler");
{
test_rotate_and_get_euler(EulerOrder::XYZ);
test_rotate_and_get_euler(EulerOrder::XZY);
test_rotate_and_get_euler(EulerOrder::YZX);
test_rotate_and_get_euler(EulerOrder::YXZ);
test_rotate_and_get_euler(EulerOrder::ZXY);
test_rotate_and_get_euler(EulerOrder::ZYX);
}
Console::write_line(" Function: transpose() (float)");
{
Mat4f original(test_a);
Mat4f transposed_matrix;
transposed_matrix[0] = original[0];
transposed_matrix[1] = original[4];
transposed_matrix[2] = original[8];
transposed_matrix[3] = original[12];
transposed_matrix[4] = original[1];
transposed_matrix[5] = original[5];
transposed_matrix[6] = original[9];
transposed_matrix[7] = original[13];
transposed_matrix[8] = original[2];
transposed_matrix[9] = original[6];
transposed_matrix[10] = original[10];
transposed_matrix[11] = original[14];
transposed_matrix[12] = original[3];
transposed_matrix[13] = original[7];
transposed_matrix[14] = original[11];
transposed_matrix[15] = original[15];
Mat4f test = original;
test.transpose();
if (!test.is_equal(transposed_matrix, 0.00001f))
fail();
}
}
void TestApp::test_rotate_and_get_euler(clan::EulerOrder order)
{
for (int ax = 0; ax < 360; ax += 10)
{
for (int ay = 0; ay < 360; ay += 10)
{
for (int az = 0; az < 360; az += 10)
{
Angle angle_x(ax, AngleUnit::degrees);
Angle angle_y(ay, AngleUnit::degrees);
Angle angle_z(az, AngleUnit::degrees);
Mat4f test_matrix;
test_matrix = Mat4f::rotate(angle_x, angle_y, angle_z, order);
Vec3f angles = test_matrix.get_euler(order);
Mat4f test_matrix2;
test_matrix2 = Mat4f::rotate(Angle(angles.x, AngleUnit::radians), Angle(angles.y, AngleUnit::radians), Angle(angles.z, AngleUnit::radians), order);
// Note, since euler angles can have alternative forms, we compare by recreating as a rotation matrix
if (!test_matrix.is_equal(test_matrix2, 0.00001f))
fail();
//check_float(angles.x, angle_x.to_radians());
//check_float(angles.y, angle_y.to_radians());
//check_float(angles.z, angle_z.to_radians());
}
}
}
}
void TestApp::test_matrix_mat2()
{
Console::write_line(" Class: Mat2");
Mat2d test_a = Mat2d(3, 1, 2, 4);
Mat2d test_b = Mat2d(-3, 7, 2, 5);
Console::write_line(" Function: multiply() and operator");
{
Mat2d result = test_b * test_a;
if (result != Mat2d(-7, 26, 2, 34)) fail();
result = Mat2d::multiply(test_b, test_a);
if (result != Mat2d(-7, 26, 2, 34)) fail();
}
Console::write_line(" Function: add() and operator");
{
Mat2d result = test_a + test_b;
if (result != Mat2d(0, 8, 4, 9)) fail();
result = Mat2d::add(test_b, test_a);
if (result != Mat2d(0, 8, 4, 9)) fail();
}
Console::write_line(" Function: subtract() and operator");
{
Mat2d result = test_a - test_b;
if (result != Mat2d(6, -6, 0, -1)) fail();
result = Mat2d::subtract(test_a, test_b);
if (result != Mat2d(6, -6, 0, -1)) fail();
}
}
| 26.199438 | 151 | 0.643401 | xctan |
4cdd06a8cd8129ac7c98e7d956acafdeabc6fd41 | 29,841 | cpp | C++ | Editor/ModelImporter_GLTF.cpp | Svengali/WickedEngine | 6f56672476993ea95039db003b6dcf39231855db | [
"Zlib",
"MIT"
] | 1 | 2022-03-23T04:00:42.000Z | 2022-03-23T04:00:42.000Z | Editor/ModelImporter_GLTF.cpp | Svengali/WickedEngine | 6f56672476993ea95039db003b6dcf39231855db | [
"Zlib",
"MIT"
] | null | null | null | Editor/ModelImporter_GLTF.cpp | Svengali/WickedEngine | 6f56672476993ea95039db003b6dcf39231855db | [
"Zlib",
"MIT"
] | null | null | null | #include "stdafx.h"
#include "ModelImporter.h"
#include "Utility/stb_image.h"
#define TINYGLTF_IMPLEMENTATION
#define TINYGLTF_NO_STB_IMAGE
#define TINYGLTF_NO_STB_IMAGE_WRITE
#include "tiny_gltf.h"
#include <fstream>
#include <sstream>
using namespace std;
using namespace wiGraphicsTypes;
using namespace wiSceneComponents;
// Transform the data from glTF space to engine-space:
const bool transform_to_LH = true;
namespace tinygltf
{
bool LoadImageData(Image *image, std::string *err, std::string *warn,
int req_width, int req_height, const unsigned char *bytes,
int size, void *)
{
(void)warn;
const int requiredComponents = 4;
int w, h, comp;
// if image cannot be decoded, ignore parsing and keep it by its path
// don't break in this case
// FIXME we should only enter this function if the image is embedded. If
// image->uri references
// an image file, it should be left as it is. Image loading should not be
// mandatory (to support other formats)
unsigned char *data = stbi_load_from_memory(bytes, size, &w, &h, &comp, requiredComponents);
if (!data) {
// NOTE: you can use `warn` instead of `err`
if (err) {
(*err) += "Unknown image format.\n";
}
return false;
}
if (w < 1 || h < 1) {
free(data);
if (err) {
(*err) += "Invalid image data.\n";
}
return false;
}
if (req_width > 0) {
if (req_width != w) {
free(data);
if (err) {
(*err) += "Image width mismatch.\n";
}
return false;
}
}
if (req_height > 0) {
if (req_height != h) {
free(data);
if (err) {
(*err) += "Image height mismatch.\n";
}
return false;
}
}
image->width = w;
image->height = h;
//image->component = comp;
image->component = requiredComponents;
image->image.resize(static_cast<size_t>(w * h * image->component));
std::copy(data, data + w * h * image->component, image->image.begin());
free(data);
return true;
//if (!image->uri.empty())
//{
// // external image will be loaded by resource manager
// return true;
//}
//else
//{
// // embedded image
// // We will load the texture2d by hand here and register to the resource manager
// {
// // png, tga, jpg, etc. loader:
// const int channelCount = 4;
// int width, height, bpp;
// unsigned char* rgb = stbi_load_from_memory(bytes, size, &width, &height, &bpp, channelCount);
// if (rgb != nullptr)
// {
// TextureDesc desc;
// desc.ArraySize = 1;
// desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS;
// desc.CPUAccessFlags = 0;
// desc.Format = FORMAT_R8G8B8A8_UNORM;
// desc.Height = static_cast<uint32_t>(height);
// desc.Width = static_cast<uint32_t>(width);
// desc.MipLevels = (UINT)log2(max(width, height));
// desc.MiscFlags = 0;
// desc.Usage = USAGE_DEFAULT;
// UINT mipwidth = width;
// SubresourceData* InitData = new SubresourceData[desc.MipLevels];
// for (UINT mip = 0; mip < desc.MipLevels; ++mip)
// {
// InitData[mip].pSysMem = rgb;
// InitData[mip].SysMemPitch = static_cast<UINT>(mipwidth * channelCount);
// mipwidth = max(1, mipwidth / 2);
// }
// Texture2D* tex = new Texture2D;
// tex->RequestIndependentShaderResourcesForMIPs(true);
// tex->RequestIndependentUnorderedAccessResourcesForMIPs(true);
// HRESULT hr = wiRenderer::GetDevice()->CreateTexture2D(&desc, InitData, &tex);
// assert(SUCCEEDED(hr));
// if (tex != nullptr)
// {
// wiRenderer::AddDeferredMIPGen(tex);
// if (image->name.empty())
// {
// static UINT imgcounter = 0;
// stringstream ss("");
// ss << "gltfLoader_embedded_image" << imgcounter++;
// image->name = ss.str();
// }
// // We loaded the texture2d, so register to the resource manager to be retrieved later:
// wiResourceManager::GetGlobal()->Register(image->name, tex, wiResourceManager::IMAGE);
// }
// }
// free(rgb);
// }
// return true;
//}
//return false;
}
bool WriteImageData(const std::string *basepath, const std::string *filename,
Image *image, bool embedImages, void *)
{
assert(0); // TODO
return false;
}
}
void RegisterTexture2D(tinygltf::Image *image)
{
// We will load the texture2d by hand here and register to the resource manager
{
int width = image->width;
int height = image->height;
int channelCount = image->component;
const unsigned char* rgb = image->image.data();
if (rgb != nullptr)
{
TextureDesc desc;
desc.ArraySize = 1;
desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS;
desc.CPUAccessFlags = 0;
desc.Format = FORMAT_R8G8B8A8_UNORM;
desc.Height = static_cast<uint32_t>(height);
desc.Width = static_cast<uint32_t>(width);
desc.MipLevels = (UINT)log2(max(width, height));
desc.MiscFlags = 0;
desc.Usage = USAGE_DEFAULT;
UINT mipwidth = width;
SubresourceData* InitData = new SubresourceData[desc.MipLevels];
for (UINT mip = 0; mip < desc.MipLevels; ++mip)
{
InitData[mip].pSysMem = rgb;
InitData[mip].SysMemPitch = static_cast<UINT>(mipwidth * channelCount);
mipwidth = max(1, mipwidth / 2);
}
Texture2D* tex = new Texture2D;
tex->RequestIndependentShaderResourcesForMIPs(true);
tex->RequestIndependentUnorderedAccessResourcesForMIPs(true);
HRESULT hr = wiRenderer::GetDevice()->CreateTexture2D(&desc, InitData, &tex);
assert(SUCCEEDED(hr));
if (tex != nullptr)
{
wiRenderer::AddDeferredMIPGen(tex);
if (image->name.empty())
{
static UINT imgcounter = 0;
stringstream ss("");
ss << "gltfLoader_image" << imgcounter++;
image->name = ss.str();
}
// We loaded the texture2d, so register to the resource manager to be retrieved later:
wiResourceManager::GetGlobal()->Register(image->name, tex, wiResourceManager::IMAGE);
}
}
}
}
void LoadNode(tinygltf::Node* node, tinygltf::Node* parent, Model* model, tinygltf::Model& gltfModel, vector<Mesh*>& meshArray, vector<Armature*>& armatureArray)
{
if (node == nullptr)
{
return;
}
Transform transform;
if (!node->scale.empty())
{
transform.scale_rest = XMFLOAT3((float)node->scale[0], (float)node->scale[1], (float)node->scale[2]);
}
if (!node->rotation.empty())
{
transform.rotation_rest = XMFLOAT4((float)node->rotation[0], (float)node->rotation[1], (float)node->rotation[2], (float)node->rotation[3]);
}
if (!node->translation.empty())
{
transform.translation_rest = XMFLOAT3((float)node->translation[0], (float)node->translation[1], (float)node->translation[2]);
}
transform.UpdateTransform();
if (parent != nullptr)
{
transform.parentName = parent->name;
}
if(node->mesh >= 0)
{
Object* object = new Object(node->name);
model->objects.insert(object);
*(Transform*)object = transform;
if (node->mesh < meshArray.size())
{
object->mesh = meshArray[node->mesh];
object->meshName = object->mesh->name;
}
else
{
auto& x = gltfModel.meshes[node->mesh];
Mesh* mesh = new Mesh(x.name);
meshArray.push_back(mesh);
object->mesh = mesh;
object->meshName = mesh->name;
mesh->renderable = true;
XMFLOAT3 min = XMFLOAT3(FLT_MAX, FLT_MAX, FLT_MAX);
XMFLOAT3 max = XMFLOAT3(-FLT_MAX, -FLT_MAX, -FLT_MAX);
for (auto& prim : x.primitives)
{
assert(prim.indices >= 0);
// Fill indices:
const tinygltf::Accessor& accessor = gltfModel.accessors[prim.indices];
const tinygltf::BufferView& bufferView = gltfModel.bufferViews[accessor.bufferView];
const tinygltf::Buffer& buffer = gltfModel.buffers[bufferView.buffer];
int stride = accessor.ByteStride(bufferView);
size_t count = accessor.count;
size_t offset = mesh->indices.size();
mesh->indices.resize(offset + count);
const unsigned char* data = buffer.data.data() + accessor.byteOffset + bufferView.byteOffset;
if (stride == 1)
{
for (size_t i = 0; i < count; i += 3)
{
mesh->indices[offset + i + 0] = data[i + 0];
mesh->indices[offset + i + 1] = data[i + 1];
mesh->indices[offset + i + 2] = data[i + 2];
}
}
else if (stride == 2)
{
for (size_t i = 0; i < count; i += 3)
{
mesh->indices[offset + i + 0] = ((uint16_t*)data)[i + 0];
mesh->indices[offset + i + 1] = ((uint16_t*)data)[i + 1];
mesh->indices[offset + i + 2] = ((uint16_t*)data)[i + 2];
}
}
else if (stride == 4)
{
for (size_t i = 0; i < count; i += 3)
{
mesh->indices[offset + i + 0] = ((uint32_t*)data)[i + 0];
mesh->indices[offset + i + 1] = ((uint32_t*)data)[i + 1];
mesh->indices[offset + i + 2] = ((uint32_t*)data)[i + 2];
}
}
else
{
assert(0 && "unsupported index stride!");
}
// Create mesh subset:
MeshSubset subset;
if (prim.material >= 0)
{
const string& mat_name = gltfModel.materials[prim.material].name;
auto& found_mat = model->materials.find(mat_name);
if (found_mat != model->materials.end())
{
subset.material = found_mat->second;
}
}
if (subset.material == nullptr)
{
subset.material = new Material("gltfLoader_defaultMat");
}
mesh->subsets.push_back(subset);
mesh->materialNames.push_back(subset.material->name);
}
bool hasBoneWeights = false;
bool hasBoneIndices = false;
int matIndex = -1;
for (auto& prim : x.primitives)
{
matIndex++;
size_t offset = mesh->vertices_FULL.size();
for (auto& attr : prim.attributes)
{
const string& attr_name = attr.first;
int attr_data = attr.second;
const tinygltf::Accessor& accessor = gltfModel.accessors[attr_data];
const tinygltf::BufferView& bufferView = gltfModel.bufferViews[accessor.bufferView];
const tinygltf::Buffer& buffer = gltfModel.buffers[bufferView.buffer];
int stride = accessor.ByteStride(bufferView);
size_t count = accessor.count;
if (mesh->vertices_FULL.size() == offset)
{
mesh->vertices_FULL.resize(offset + count);
}
const unsigned char* data = buffer.data.data() + accessor.byteOffset + bufferView.byteOffset;
if (!attr_name.compare("POSITION"))
{
assert(stride == 12);
for (size_t i = 0; i < count; ++i)
{
XMFLOAT3 pos = ((XMFLOAT3*)data)[i];
if (transform_to_LH)
{
pos.z = -pos.z;
}
mesh->vertices_FULL[offset + i].pos = XMFLOAT4(pos.x, pos.y, pos.z, 0);
min = wiMath::Min(min, pos);
max = wiMath::Max(max, pos);
}
}
else if (!attr_name.compare("NORMAL"))
{
assert(stride == 12);
for (size_t i = 0; i < count; ++i)
{
const XMFLOAT3& nor = ((XMFLOAT3*)data)[i];
mesh->vertices_FULL[offset + i].nor.x = nor.x;
mesh->vertices_FULL[offset + i].nor.y = nor.y;
mesh->vertices_FULL[offset + i].nor.z = -nor.z;
}
}
else if (!attr_name.compare("TEXCOORD_0"))
{
assert(stride == 8);
for (size_t i = 0; i < count; ++i)
{
const XMFLOAT2& tex = ((XMFLOAT2*)data)[i];
mesh->vertices_FULL[offset + i].tex.x = tex.x;
mesh->vertices_FULL[offset + i].tex.y = tex.y;
mesh->vertices_FULL[offset + i].tex.z = (float)matIndex /*prim.material*/;
}
}
else if (!attr_name.compare("JOINTS_0"))
{
if (stride == 4)
{
hasBoneIndices = true;
struct JointTmp
{
uint8_t ind[4];
};
for (size_t i = 0; i < count; ++i)
{
const JointTmp& joint = ((JointTmp*)data)[i];
mesh->vertices_FULL[offset + i].ind.x = (float)joint.ind[0];
mesh->vertices_FULL[offset + i].ind.y = (float)joint.ind[1];
mesh->vertices_FULL[offset + i].ind.z = (float)joint.ind[2];
mesh->vertices_FULL[offset + i].ind.w = (float)joint.ind[3];
}
}
else if (stride == 8)
{
hasBoneIndices = true;
struct JointTmp
{
uint16_t ind[4];
};
for (size_t i = 0; i < count; ++i)
{
const JointTmp& joint = ((JointTmp*)data)[i];
mesh->vertices_FULL[offset + i].ind.x = (float)joint.ind[0];
mesh->vertices_FULL[offset + i].ind.y = (float)joint.ind[1];
mesh->vertices_FULL[offset + i].ind.z = (float)joint.ind[2];
mesh->vertices_FULL[offset + i].ind.w = (float)joint.ind[3];
}
}
else
{
assert(0);
}
}
else if (!attr_name.compare("WEIGHTS_0"))
{
hasBoneWeights = true;
assert(stride == 16);
for (size_t i = 0; i < count; ++i)
{
mesh->vertices_FULL[offset + i].wei = ((XMFLOAT4*)data)[i];
}
}
}
}
mesh->aabb.create(min, max);
model->meshes.insert(make_pair(mesh->name, mesh));
if (!armatureArray.empty() && hasBoneIndices && hasBoneWeights)
{
mesh->armature = armatureArray[0]; // How to resolve?
mesh->armatureName = mesh->armature->name;
}
}
}
if (node->camera >= 0)
{
Camera* camera = new Camera;
camera->SetUp((float)wiRenderer::GetInternalResolution().x, (float)wiRenderer::GetInternalResolution().y, 0.1f, 800);
model->cameras.push_back(camera);
*(Transform*)camera = transform;
camera->name = gltfModel.cameras[node->camera].name;
if (camera->name.empty())
{
static int camID = 0;
stringstream ss("");
ss << "cam" << camID++;
camera->name = ss.str();
}
node->name = camera->name;
camera->UpdateProps();
}
if (!node->children.empty())
{
for (int child : node->children)
{
LoadNode(&gltfModel.nodes[child], node, model, gltfModel, meshArray, armatureArray);
}
}
}
Model* ImportModel_GLTF(const std::string& fileName)
{
string directory, name;
wiHelper::SplitPath(fileName, directory, name);
string extension = wiHelper::toUpper(wiHelper::GetExtensionFromFileName(name));
wiHelper::RemoveExtensionFromFileName(name);
vector<Armature*> armatureArray;
vector<Mesh*> meshArray;
tinygltf::Model gltfModel;
tinygltf::TinyGLTF loader;
std::string err;
std::string warn;
loader.SetImageLoader(tinygltf::LoadImageData, nullptr);
loader.SetImageWriter(tinygltf::WriteImageData, nullptr);
bool ret;
if (!extension.compare("GLTF"))
{
ret = loader.LoadASCIIFromFile(&gltfModel, &err, &warn, fileName);
}
else
{
ret = loader.LoadBinaryFromFile(&gltfModel, &err, &warn, fileName); // for binary glTF(.glb)
}
if (!ret) {
wiHelper::messageBox(err, "GLTF error!");
return nullptr;
}
Model* model = new Model;
model->name = name;
for (auto& x : gltfModel.materials)
{
Material* material = new Material(x.name);
model->materials.insert(make_pair(material->name, material));
material->baseColor = XMFLOAT3(1, 1, 1);
material->roughness = 1.0f;
material->metalness = 1.0f;
material->reflectance = 0.02f;
material->emissive = 0;
auto& baseColorTexture = x.values.find("baseColorTexture");
auto& metallicRoughnessTexture = x.values.find("metallicRoughnessTexture");
auto& normalTexture = x.additionalValues.find("normalTexture");
auto& emissiveTexture = x.additionalValues.find("emissiveTexture");
auto& occlusionTexture = x.additionalValues.find("occlusionTexture");
auto& baseColorFactor = x.values.find("baseColorFactor");
auto& roughnessFactor = x.values.find("roughnessFactor");
auto& metallicFactor = x.values.find("metallicFactor");
auto& emissiveFactor = x.additionalValues.find("emissiveFactor");
auto& alphaCutoff = x.additionalValues.find("alphaCutoff");
if (baseColorTexture != x.values.end())
{
auto& tex = gltfModel.textures[baseColorTexture->second.TextureIndex()];
auto& img = gltfModel.images[tex.source];
RegisterTexture2D(&img);
material->textureName = img.name;
}
else if(!gltfModel.images.empty())
{
// For some reason, we don't have diffuse texture, but have other textures
// I have a problem, because one model viewer displays textures on a model which has no basecolor set in its material...
// This is probably not how it should be (todo)
RegisterTexture2D(&gltfModel.images[0]);
material->textureName = gltfModel.images[0].name;
}
tinygltf::Image* img_nor = nullptr;
tinygltf::Image* img_met_rough = nullptr;
tinygltf::Image* img_emissive = nullptr;
if (normalTexture != x.additionalValues.end())
{
auto& tex = gltfModel.textures[normalTexture->second.TextureIndex()];
img_nor = &gltfModel.images[tex.source];
}
if (metallicRoughnessTexture != x.values.end())
{
auto& tex = gltfModel.textures[metallicRoughnessTexture->second.TextureIndex()];
img_met_rough = &gltfModel.images[tex.source];
}
if (emissiveTexture != x.additionalValues.end())
{
auto& tex = gltfModel.textures[emissiveTexture->second.TextureIndex()];
img_emissive = &gltfModel.images[tex.source];
}
// Now we will begin interleaving texture data to match engine layout:
if (img_nor != nullptr)
{
uint32_t* data32_roughness = nullptr;
if (img_met_rough != nullptr && img_met_rough->width == img_nor->width && img_met_rough->height == img_nor->height)
{
data32_roughness = (uint32_t*)img_met_rough->image.data();
}
else if (img_met_rough != nullptr)
{
wiBackLog::post("[gltf] Warning: there is a normalmap and roughness texture, but not the same size! Roughness will not be baked in!");
}
// Convert normal map:
uint32_t* data32 = (uint32_t*)img_nor->image.data();
for (int i = 0; i < img_nor->width * img_nor->height; ++i)
{
uint32_t pixel = data32[i];
float r = ((pixel >> 0) & 255) / 255.0f;
float g = ((pixel >> 8) & 255) / 255.0f;
float b = ((pixel >> 16) & 255) / 255.0f;
float a = ((pixel >> 24) & 255) / 255.0f;
// swap normal y direction:
g = 1 - g;
// reset roughness:
a = 1;
if (data32_roughness != nullptr)
{
// add roughness from texture (G):
a = ((data32_roughness[i] >> 8) & 255) / 255.0f;
a = max(1.0f / 255.0f, a); // disallow 0 roughness (but is it really a good idea to do it here???)
}
uint32_t rgba8 = 0;
rgba8 |= (uint32_t)(r * 255.0f) << 0;
rgba8 |= (uint32_t)(g * 255.0f) << 8;
rgba8 |= (uint32_t)(b * 255.0f) << 16;
rgba8 |= (uint32_t)(a * 255.0f) << 24;
data32[i] = rgba8;
}
RegisterTexture2D(img_nor);
material->normalMapName = img_nor->name;
}
if (img_met_rough != nullptr)
{
uint32_t* data32_emissive = nullptr;
if (img_emissive != nullptr && img_emissive->width == img_met_rough->width && img_emissive->height == img_met_rough->height)
{
data32_emissive = (uint32_t*)img_emissive->image.data();
}
uint32_t* data32 = (uint32_t*)img_met_rough->image.data();
for (int i = 0; i < img_met_rough->width * img_met_rough->height; ++i)
{
uint32_t pixel = data32[i];
float r = ((pixel >> 0) & 255) / 255.0f;
float g = ((pixel >> 8) & 255) / 255.0f;
float b = ((pixel >> 16) & 255) / 255.0f;
float a = ((pixel >> 24) & 255) / 255.0f;
float reflectance = 1;
float metalness = b;
float emissive = 0;
float sss = 1;
if (data32_emissive != nullptr)
{
// add emissive from texture (R):
// (Currently only supporting single channel emissive)
emissive = ((data32_emissive[i] >> 0) & 255) / 255.0f;
}
uint32_t rgba8 = 0;
rgba8 |= (uint32_t)(reflectance * 255.0f) << 0;
rgba8 |= (uint32_t)(metalness * 255.0f) << 8;
rgba8 |= (uint32_t)(emissive * 255.0f) << 16;
rgba8 |= (uint32_t)(sss * 255.0f) << 24;
data32[i] = rgba8;
}
RegisterTexture2D(img_met_rough);
material->surfaceMapName = img_met_rough->name;
}
else if (img_emissive != nullptr)
{
// No metalness texture, just emissive...
uint32_t* data32 = (uint32_t*)img_emissive->image.data();
if (data32 != nullptr)
{
for (int i = 0; i < img_emissive->width * img_emissive->height; ++i)
{
uint32_t pixel = data32[i];
float r = ((pixel >> 0) & 255) / 255.0f;
float g = ((pixel >> 8) & 255) / 255.0f;
float b = ((pixel >> 16) & 255) / 255.0f;
float a = ((pixel >> 24) & 255) / 255.0f;
float reflectance = 1;
float metalness = 1;
float emissive = r;
float sss = 1;
uint32_t rgba8 = 0;
rgba8 |= (uint32_t)(reflectance * 255.0f) << 0;
rgba8 |= (uint32_t)(metalness * 255.0f) << 8;
rgba8 |= (uint32_t)(emissive * 255.0f) << 16;
rgba8 |= (uint32_t)(sss * 255.0f) << 24;
data32[i] = rgba8;
}
RegisterTexture2D(img_emissive);
material->surfaceMapName = img_emissive->name;
}
}
// Retrieve textures by name:
if (!material->textureName.empty())
material->texture = (Texture2D*)wiResourceManager::GetGlobal()->add(material->textureName);
if (!material->normalMapName.empty())
material->normalMap = (Texture2D*)wiResourceManager::GetGlobal()->add(material->normalMapName);
if (!material->surfaceMapName.empty())
material->surfaceMap = (Texture2D*)wiResourceManager::GetGlobal()->add(material->surfaceMapName);
if (baseColorFactor != x.values.end())
{
material->baseColor.x = static_cast<float>(baseColorFactor->second.ColorFactor()[0]);
material->baseColor.y = static_cast<float>(baseColorFactor->second.ColorFactor()[1]);
material->baseColor.z = static_cast<float>(baseColorFactor->second.ColorFactor()[2]);
}
if (roughnessFactor != x.values.end())
{
material->roughness = static_cast<float>(roughnessFactor->second.Factor());
}
if (metallicFactor != x.values.end())
{
material->metalness = static_cast<float>(metallicFactor->second.Factor());
}
if (emissiveFactor != x.additionalValues.end())
{
material->emissive = static_cast<float>(emissiveFactor->second.ColorFactor()[0]);
}
if (alphaCutoff != x.additionalValues.end())
{
material->alphaRef = 1 - static_cast<float>(alphaCutoff->second.Factor());
}
}
for(auto& skin : gltfModel.skins)
{
Armature* armature = new Armature(skin.name);
model->armatures.insert(armature);
armatureArray.push_back(armature);
const tinygltf::Node& skeleton_node = gltfModel.nodes[skin.skeleton];
const size_t jointCount = skin.joints.size();
armature->boneCollection.resize(jointCount);
// Create bone collection:
for (size_t i = 0; i < jointCount; ++i)
{
int jointIndex = skin.joints[i];
const tinygltf::Node& joint_node = gltfModel.nodes[jointIndex];
Bone* bone = new Bone(joint_node.name);
if (bone->name.empty())
{
// GLTF might not contain bone names...
stringstream ss("");
ss << "Bone_" << i;
bone->name = ss.str();
}
armature->boneCollection[i] = bone;
if (!joint_node.scale.empty())
{
bone->scale_rest = XMFLOAT3((float)joint_node.scale[0], (float)joint_node.scale[1], (float)joint_node.scale[2]);
}
if (!joint_node.rotation.empty())
{
bone->rotation_rest = XMFLOAT4((float)joint_node.rotation[0], (float)joint_node.rotation[1], (float)joint_node.rotation[2], (float)joint_node.rotation[3]);
}
if (!joint_node.translation.empty())
{
bone->translation_rest = XMFLOAT3((float)joint_node.translation[0], (float)joint_node.translation[1], (float)joint_node.translation[2]);
}
XMVECTOR s = XMLoadFloat3(&bone->scale_rest);
XMVECTOR r = XMLoadFloat4(&bone->rotation_rest);
XMVECTOR t = XMLoadFloat3(&bone->translation_rest);
XMMATRIX w =
XMMatrixScalingFromVector(s)*
XMMatrixRotationQuaternion(r)*
XMMatrixTranslationFromVector(t)
;
XMStoreFloat4x4(&bone->world_rest, w);
}
// Create bone name hierarchy:
for (size_t i = 0; i < jointCount; ++i)
{
int jointIndex = skin.joints[i];
const tinygltf::Node& joint_node = gltfModel.nodes[jointIndex];
for (int childJointIndex : joint_node.children)
{
for (size_t j = 0; j < jointCount; ++j)
{
if (skin.joints[j] == childJointIndex)
{
armature->boneCollection[j]->parentName = armature->boneCollection[i]->name;
break;
}
}
}
}
if (transform_to_LH)
{
XMStoreFloat4x4(&armature->skinningRemap, XMMatrixScaling(1, 1, -1));
}
// Final hierarchy and extra matrices created here:
armature->CreateFamily();
}
const tinygltf::Scene &scene = gltfModel.scenes[gltfModel.defaultScene];
for (size_t i = 0; i < scene.nodes.size(); i++)
{
LoadNode(&gltfModel.nodes[scene.nodes[i]], nullptr, model, gltfModel, meshArray, armatureArray);
}
int animID = 0;
for (auto& anim : gltfModel.animations)
{
if (armatureArray.empty())
{
break;
}
Armature* armature = armatureArray[0];
for (Bone* bone : armature->boneCollection)
{
bone->actionFrames.push_back(ActionFrames());
}
Action action;
action.name = anim.name;
if (action.name.empty())
{
stringstream ss("");
ss << "Action_" << animID++;
action.name = ss.str();
}
for (auto& channel : anim.channels)
{
const tinygltf::Node& target_node = gltfModel.nodes[channel.target_node];
const tinygltf::AnimationSampler& sam = anim.samplers[channel.sampler];
Bone* bone = nullptr;
// Search for the armature + bone this animation belongs to:
{
const auto& skin = gltfModel.skins[0];
const size_t jointCount = skin.joints.size();
assert(armature->boneCollection.size() == jointCount);
for (size_t i = 0; i < jointCount; ++i)
{
int jointIndex = skin.joints[i];
if (jointIndex == channel.target_node)
{
bone = armature->boneCollection[i];
break;
}
}
}
if (bone == nullptr)
{
assert(0 && "Corresponding bone not found!");
continue;
}
vector<KeyFrame> keyframes;
// AnimationSampler input = keyframe times
{
const tinygltf::Accessor& accessor = gltfModel.accessors[sam.input];
const tinygltf::BufferView& bufferView = gltfModel.bufferViews[accessor.bufferView];
const tinygltf::Buffer& buffer = gltfModel.buffers[bufferView.buffer];
assert(accessor.componentType == TINYGLTF_COMPONENT_TYPE_FLOAT);
int stride = accessor.ByteStride(bufferView);
size_t count = accessor.count;
keyframes.resize(count);
const unsigned char* data = buffer.data.data() + accessor.byteOffset + bufferView.byteOffset;
int firstFrame = INT_MAX;
assert(stride == 4);
for (size_t i = 0; i < count; ++i)
{
keyframes[i].frameI = (int)(((float*)data)[i] * 60); // !!! converting from time-base to frame-based !!!
action.frameCount = max(action.frameCount, keyframes[i].frameI);
firstFrame = min(firstFrame, keyframes[i].frameI);
}
// Cut out the empty part of the animation at the beginning:
firstFrame = min(firstFrame, action.frameCount);
for (size_t i = 0; i < count; ++i)
{
keyframes[i].frameI -= firstFrame;
}
action.frameCount -= firstFrame;
}
// AnimationSampler output = keyframe data
{
const tinygltf::Accessor& accessor = gltfModel.accessors[sam.output];
const tinygltf::BufferView& bufferView = gltfModel.bufferViews[accessor.bufferView];
const tinygltf::Buffer& buffer = gltfModel.buffers[bufferView.buffer];
int stride = accessor.ByteStride(bufferView);
size_t count = accessor.count;
// Unfortunately, GLTF stores absolute values for animation nodes, but the engine needs relative
// Absolute = animation * rest (so the rest matrix is baked into animation, this can't be blended like we do now)
// Relative = animation (so we can blend all animation tracks however we want, then post multiply with the rest matrix after blending)
const XMMATRIX invRest = XMMatrixInverse(nullptr, XMLoadFloat4x4(&bone->world_rest));
const unsigned char* data = buffer.data.data() + accessor.byteOffset + bufferView.byteOffset;
if (!channel.target_path.compare("scale"))
{
assert(stride == sizeof(XMFLOAT3));
for (size_t i = 0; i < count; ++i)
{
const XMFLOAT3& sca = ((XMFLOAT3*)data)[i];
//keyframes[i].data = XMFLOAT4(sca.x, sca.y, sca.z, 0);
// Remove rest matrix from animation track:
XMMATRIX mat = XMMatrixScalingFromVector(XMLoadFloat3(&sca));
mat = mat * invRest;
XMVECTOR s, r, t;
XMMatrixDecompose(&s, &r, &t, mat);
XMStoreFloat4(&keyframes[i].data, s);
}
bone->actionFrames.back().keyframesSca.insert(bone->actionFrames.back().keyframesSca.end(), keyframes.begin(), keyframes.end());
}
else if (!channel.target_path.compare("rotation"))
{
assert(stride == sizeof(XMFLOAT4));
for (size_t i = 0; i < count; ++i)
{
const XMFLOAT4& rot = ((XMFLOAT4*)data)[i];
//keyframes[i].data = rot;
// Remove rest matrix from animation track:
XMMATRIX mat = XMMatrixRotationQuaternion(XMLoadFloat4(&rot));
mat = mat * invRest;
XMVECTOR s, r, t;
XMMatrixDecompose(&s, &r, &t, mat);
XMStoreFloat4(&keyframes[i].data, r);
}
bone->actionFrames.back().keyframesRot.insert(bone->actionFrames.back().keyframesRot.end(), keyframes.begin(), keyframes.end());
}
else if (!channel.target_path.compare("translation"))
{
assert(stride == sizeof(XMFLOAT3));
for (size_t i = 0; i < count; ++i)
{
const XMFLOAT3& tra = ((XMFLOAT3*)data)[i];
//keyframes[i].data = XMFLOAT4(tra.x, tra.y, tra.z, 1);
// Remove rest matrix from animation track:
XMMATRIX mat = XMMatrixTranslationFromVector(XMLoadFloat3(&tra));
mat = mat * invRest;
XMVECTOR s, r, t;
XMMatrixDecompose(&s, &r, &t, mat);
XMStoreFloat4(&keyframes[i].data, t);
}
bone->actionFrames.back().keyframesPos.insert(bone->actionFrames.back().keyframesPos.end(), keyframes.begin(), keyframes.end());
}
else
{
assert(0);
}
}
}
armature->actions.push_back(action);
}
model->FinishLoading();
return model;
}
| 28.693269 | 161 | 0.635166 | Svengali |
4cdf0d14ea71923220a296c0441327e8dcb5d67d | 1,629 | hpp | C++ | include/std.dialogsearch.hpp | wilsonsouza/stdx.frame.x86 | c9e0cc4c748f161367531990e5795a700f40e5ec | [
"Apache-2.0"
] | null | null | null | include/std.dialogsearch.hpp | wilsonsouza/stdx.frame.x86 | c9e0cc4c748f161367531990e5795a700f40e5ec | [
"Apache-2.0"
] | null | null | null | include/std.dialogsearch.hpp | wilsonsouza/stdx.frame.x86 | c9e0cc4c748f161367531990e5795a700f40e5ec | [
"Apache-2.0"
] | null | null | null | //-----------------------------------------------------------------------------------------------//
// dedaluslib.lib for Windows
//
// Created by Wilson.Souza 2012, 2013
// For Libbs Farma
//
// Dedalus Prime
// (c) 2012, 2013
//-----------------------------------------------------------------------------------------------//
#include <std.dialogex.hpp>
#include <std.lineedit.hpp>
#include <std.groupbox.hpp>
//-----------------------------------------------------------------------------------------------//
namespace std
{
namespace Captions
{
namespace Find
{
static const std::ustring SELECT_MODE = std::ustring("Selecione a chave de pesquisa");
static const std::ustring PESQUISAR = std::ustring("Pesquisar");
static const std::ustring NAME = std::ustring("Pesquisar");
static const std::ustring ITEMS = std::ustring("items");
static const std::ustring DATA = std::ustring("data");
static const std::ustring TIMER = std::ustring("find_dlg_item_timer");
};
};
//----------------------------------------------------------------------------------------------//
class _DYNAMICLINK DialogSearch: public DialogEx
{
Q_OBJECT
public:
DialogSearch(QWidget * pOwner, std::ustring const & strName);
virtual ~DialogSearch();
virtual bool const __fastcall OnCreate(DialogEx * pDlg);
DECLARE_OPERATOR(DialogSearch);
CREATE_PROPERTY_READONLY(LineEdit *, m_ple, FindWhat)
CREATE_PROPERTY_READONLY(GroupBox *, m_pgb, Options)
};
}; | 39.731707 | 102 | 0.473297 | wilsonsouza |
4ce17249544d89cffcfa5e8819773e20857241d0 | 957 | cpp | C++ | Factory Pattern/Simple Factory Pattern/VeggiePizza.cpp | mrlegowatch/HeadFirstDesignPatternsCpp | 436ee8f0344b6a2ccfef6dcfa216a16a6ca7b482 | [
"MIT"
] | 43 | 2018-07-17T21:53:21.000Z | 2022-03-23T13:15:06.000Z | Factory Pattern/Simple Factory Pattern/VeggiePizza.cpp | mrlegowatch/HeadFirstDesignPatternsCpp | 436ee8f0344b6a2ccfef6dcfa216a16a6ca7b482 | [
"MIT"
] | null | null | null | Factory Pattern/Simple Factory Pattern/VeggiePizza.cpp | mrlegowatch/HeadFirstDesignPatternsCpp | 436ee8f0344b6a2ccfef6dcfa216a16a6ca7b482 | [
"MIT"
] | 14 | 2019-04-10T13:01:07.000Z | 2022-03-08T13:19:14.000Z | //
// PepperoniPizza.cpp
// Factory Pattern
//
// Created by Cindy Solomon on 2/13/18.
// Copyright © 2018 Brian Arnold. All rights reserved.
//
#include "VeggiePizza.hpp"
#include <iostream>
VeggiePizza::VeggiePizza()
{
name = "Veggie Pizza";
dough = "Regular crust";
sauce = "Marinara sauce";
toppings.push_back("Shredded mozzarella");
toppings.push_back("Grated Parmesan");
toppings.push_back("Diced onion");
toppings.push_back("Sliced mushrooms");
toppings.push_back("Sliced red pepper");
toppings.push_back("No olives because they're gross");
}
//void VeggiePizza::prepare() override
//{
// std::cout << "Preparing " << std::endl;
//}
//
//void VeggiePizza::bake() override
//{
// std::cout << "Baking " << std::endl;
//}
//
//void VeggiePizza::cut() override
//{
// std::cout << "Cutting " << std::endl;
//}
//
//void VeggiePizza::box() override
//{
// std::cout << "Boxing " << std::endl;
//}
| 20.804348 | 58 | 0.628004 | mrlegowatch |
4ce379d1c701bf7e5c34d2f2eb5fdda3a1e040db | 44,653 | hpp | C++ | cafes/particle/singularity/add_singularity.hpp | Fvergnet/cafes | ac634318980e7b5787ba34a4d6d20eb27be69c9a | [
"BSD-3-Clause"
] | null | null | null | cafes/particle/singularity/add_singularity.hpp | Fvergnet/cafes | ac634318980e7b5787ba34a4d6d20eb27be69c9a | [
"BSD-3-Clause"
] | null | null | null | cafes/particle/singularity/add_singularity.hpp | Fvergnet/cafes | ac634318980e7b5787ba34a4d6d20eb27be69c9a | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2016, Loic Gouarin <loic.gouarin@math.u-psud.fr>
// All rights reserved.
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
// OF SUCH DAMAGE.
#ifndef CAFES_PARTICLE_SINGULARITY_ADD_SINGULARITY_HPP_INCLUDED
#define CAFES_PARTICLE_SINGULARITY_ADD_SINGULARITY_HPP_INCLUDED
#include <particle/particle.hpp>
#include <particle/singularity/singularity.hpp>
#include <particle/singularity/UandPNormal.hpp>
#include <particle/geometry/box.hpp>
#include <particle/geometry/position.hpp>
#include <petsc/vec.hpp>
#include <petsc.h>
#include <iostream>
#include <sstream>
#include <cmath>
#include "vtkDoubleArray.h"
#include "vtkPoints.h"
#include "vtkPointData.h"
#include "vtkStructuredGrid.h"
#include "vtkXMLStructuredGridWriter.h"
namespace cafes
{
namespace singularity
{
#undef __FUNCT__
#define __FUNCT__ "computesingularST"
template<typename Shape>
PetscErrorCode computesingularST(singularity<Shape, 2> sing,
particle<Shape> const& p1, particle<Shape> const& p2,
petsc::petsc_vec<2>& sol,
geometry::box<int, 2> box,
std::array<double, 2> const& h)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
const int Dimensions = 2;
using position_type = geometry::position<double, Dimensions>;
using position_type_i = geometry::position<int, Dimensions>;
std::array<double, Dimensions> hs = {{h[0]/sing.scale, h[1]/sing.scale}};
double coef = 1./(sing.scale*sing.scale);
for(std::size_t j=box.bottom_left[1]; j<box.upper_right[1]; ++j)
{
for(std::size_t i=box.bottom_left[0]; i<box.upper_right[0]; ++i)
{
position_type_i pts_i = {i, j};
auto ielem = fem::get_element(pts_i);
for(std::size_t js=0; js<sing.scale; ++js)
{
for(std::size_t is=0; is<sing.scale; ++is)
{
position_type pts = {i*h[0] + is*hs[0], j*h[1] + js*hs[1]};
if (!p1.contains(pts) && !p2.contains(pts))
{
auto pos_ref_part = sing.get_pos_in_part_ref(pts);
if (std::abs(pos_ref_part[1]) <= sing.cutoff_dist_)
{
position_type pts_loc = {is*hs[0], js*hs[1]};
auto bfunc = fem::P1_integration_grad(pts_loc, h);
auto gradUsing = sing.get_grad_u_sing(pts);
auto psing = sing.get_p_sing(pts);
for (std::size_t je=0; je<bfunc.size(); ++je)
{
auto u = sol.at(ielem[je]);
for (std::size_t d1=0; d1<Dimensions; ++d1)
{
for (std::size_t d2=0; d2<Dimensions; ++d2)
u[d1] -= coef*gradUsing[d1][d2]*bfunc[je][d2];
u[d1] += coef*psing*bfunc[je][d1];
}
}
}
}
}
}
}
}
PetscFunctionReturn(0);
}
// #undef __FUNCT__
// #define __FUNCT__ "computesingularST_pressure"
// template<typename Shape>
// PetscErrorCode computesingularST_pressure(singularity<2, Shape> sing,
// particle<Shape> const& p1, particle<Shape> const& p2,
// petsc::petsc_vec<2>& sol,
// geometry::box<2, int> box,
// std::array<double, 2> const& h)
// {
// PetscErrorCode ierr;
// PetscFunctionBeginUser;
// const int Dimensions = 2;
// using position_type = geometry::position<Dimensions, double>;
// using position_type_i = geometry::position<Dimensions, int>;
// std::array<double, Dimensions> hs = {{h[0]/(2*sing.scale), h[1]/(2*sing.scale)}};
// double coef = 1./(4*sing.scale*sing.scale);
// for(std::size_t j=box.bottom_left[1]; j<box.upper_right[1]; ++j)
// {
// for(std::size_t i=box.bottom_left[0]; i<box.upper_right[0]; ++i)
// {
// position_type_i pts_i = {i, j};
// auto ielem = fem::get_element(pts_i);
// for(std::size_t js=0; js<2*sing.scale; ++js)
// {
// for(std::size_t is=0; is<2*sing.scale; ++is)
// {
// position_type pts = {i*h[0] + is*hs[0], j*h[1] + js*hs[1]};
// if (!p1.contains(pts) && !p2.contains(pts))
// {
// auto pos_ref_part = sing.get_pos_in_part_ref(pts);
// if (std::abs(pos_ref_part[1]) <= sing.cutoff_dist_)
// {
// position_type pts_loc = {is*hs[0], js*hs[1]};
// auto bfunc = fem::P1_integration(pts_loc, h);
// auto divUsing = sing.get_divu_sing(pts);
// for (std::size_t je=0; je<bfunc.size(); ++je)
// {
// auto u = sol.at(ielem[je]);
// u[0] -= coef*divUsing*bfunc[je];
// }
// }
// }
// }
// }
// }
// }
// PetscFunctionReturn(0);
// }
#undef __FUNCT__
#define __FUNCT__ "computesingularST"
template<typename Shape>
PetscErrorCode computesingularST(singularity<Shape, 3> sing,
particle<Shape> const& p1, particle<Shape> const& p2,
petsc::petsc_vec<3>& sol,
geometry::box<int, 3> box,
std::array<double, 3> const& h)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
const int Dimensions = 3;
using position_type = geometry::position<double, Dimensions>;
using position_type_i = geometry::position<int, Dimensions>;
std::array<double, Dimensions> hs = {{ h[0]/sing.scale,
h[1]/sing.scale,
h[2]/sing.scale }};
double coef = 1./(sing.scale*sing.scale*sing.scale);
for(std::size_t k=box.bottom_left[2]; k<box.upper_right[2]; ++k)
{
for(std::size_t j=box.bottom_left[1]; j<box.upper_right[1]; ++j)
{
for(std::size_t i=box.bottom_left[0]; i<box.upper_right[0]; ++i)
{
position_type_i pts_i = {i, j, k};
auto ielem = fem::get_element(pts_i);
for(std::size_t ks=0; ks<sing.scale; ++ks)
{
for(std::size_t js=0; js<sing.scale; ++js)
{
for(std::size_t is=0; is<sing.scale; ++is)
{
position_type pts = {i*h[0] + is*hs[0],
j*h[1] + js*hs[1],
k*h[2] + ks*hs[2] };
if (!p1.contains(pts) && !p2.contains(pts))
{
position_type pts_loc = {is*hs[0],
js*hs[1],
ks*hs[2]};
auto bfunc = fem::P1_integration_grad(pts_loc, h);
auto gradUsing = sing.get_grad_u_sing(pts);
auto psing = sing.get_p_sing(pts);
for (std::size_t je=0; je<bfunc.size(); ++je)
{
auto u = sol.at(ielem[je]);
for (std::size_t d1=0; d1<Dimensions; ++d1)
{
for (std::size_t d2=0; d2<Dimensions; ++d2)
u[d1] -= coef*gradUsing[d1][d2]*bfunc[je][d2];
u[d1] += coef*psing*bfunc[je][d1];
}
}
}
}
}
}
}
}
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "computesingularBC"
template<typename Shape>
PetscErrorCode computesingularBC(singularity<Shape, 2>& sing,
petsc::petsc_vec<2>& sol,
std::array<double, 2> const& h,
geometry::box<int, 2>& box
)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
using position_type = geometry::position<double, 2>;
double theta = std::asin(sing.cutoff_dist_*sing.H1_);
int N = sing.cutoff_dist_/h[0]*sing.scale;
// first particle
for (int i=-N; i<N; ++i)
{
double cos_t = std::cos(i*theta/N);
double sin_t = std::sin(i*theta/N);
position_type pos_ref{(cos_t - 1.)/sing.H1_, sin_t/sing.H1_};
auto pos = sing.get_pos_from_part_ref(pos_ref);
auto pos_i = static_cast<geometry::position<int, 2>>(pos/h);
//std::cout<< "pos_ref"<<pos_ref<<"pos"<<pos<<"\n";
//std::cout<< "pos_i"<<pos_i<<"\n";
if (geometry::point_inside(box, pos_i))
{
auto Using_ref = sing.get_u_sing_ref(pos_ref);
std::array< double, 2 > Using{};
for(std::size_t d1=0; d1<2; ++d1)
{
Using[d1] = 0.;
for(std::size_t d2=0; d2<2; ++d2)
Using[d1] += Using_ref[d2]*sing.base_[d2][d1];
}
position_type spts = pos - pos_i*h;
//std::cout<< "spts"<<spts<<"\n";
auto bfunc = fem::P1_integration(spts, h);
auto ielem = fem::get_element(pos_i);
for (std::size_t je=0; je<bfunc.size(); ++je)
{
auto u = sol.at(ielem[je]);
for (std::size_t d=0; d<2; ++d)
u[d] += Using[d]*bfunc[je]*theta/N/sing.H1_;
}
}
}
theta = std::asin(sing.cutoff_dist_*sing.H2_);
// second particle
for (int i=-N; i<N; ++i)
{
double cos_t = std::cos(i*theta/N);
double sin_t = std::sin(i*theta/N);
position_type pos_ref{sing.contact_length_ + (1. - cos_t)/sing.H2_, sin_t/sing.H2_};
auto pos = sing.get_pos_from_part_ref(pos_ref);
auto pos_i = static_cast<geometry::position<int, 2>>(pos/h);
if (geometry::point_inside(box, pos_i))
{
auto Using_ref = sing.get_u_sing_ref(pos_ref);
std::array< double, 2 > Using{};
for(std::size_t d1=0; d1<2; ++d1)
{
Using[d1] = 0.;
for(std::size_t d2=0; d2<2; ++d2)
Using[d1] += Using_ref[d2]*sing.base_[d2][d1];
}
position_type spts = pos - pos_i*h;
auto bfunc = fem::P1_integration(spts, h);
auto ielem = fem::get_element(pos_i);
for (std::size_t je=0; je<bfunc.size(); ++je)
{
auto u = sol.at(ielem[je]);
for (std::size_t d=0; d<2; ++d)
u[d] += Using[d]*bfunc[je]*theta/N/sing.H2_;
}
}
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "computesingularBC"
template<std::size_t Dimensions, typename Shape, typename Ctx>
PetscErrorCode computesingularBC(Ctx& ctx,
singularity<Shape, Dimensions> sing,
std::size_t ipart_1, std::size_t ipart_2,
geometry::box<double, Dimensions> box,
std::vector<std::vector<std::array<double, Dimensions>>>& g
)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
auto& h = ctx.problem.ctx->h;
for(std::size_t isurf=0; isurf<ctx.surf_points[ipart_1].size(); ++isurf)
{
auto pos = ctx.surf_points[ipart_1][isurf].second + ctx.surf_points[ipart_1][isurf].first*h;
if (geometry::point_inside(box, pos))
{
auto pos_ref_part = sing.get_pos_in_part_ref(pos);
if (std::abs(pos_ref_part[1]) <= sing.cutoff_dist_)
{
auto Using = sing.get_u_sing(pos);
for (std::size_t d=0; d<Dimensions; ++d)
g[ipart_1][isurf][d] += Using[d];
}
}
}
for(std::size_t isurf=0; isurf<ctx.surf_points[ipart_2].size(); ++isurf)
{
auto pos = ctx.surf_points[ipart_2][isurf].second + ctx.surf_points[ipart_2][isurf].first*h;
if (geometry::point_inside(box, pos))
{
auto pos_ref_part = sing.get_pos_in_part_ref(pos);
if (std::abs(pos_ref_part[1]) <= sing.cutoff_dist_)
{
auto Using = sing.get_u_sing(pos);
for (std::size_t d=0; d<Dimensions; ++d)
g[ipart_2][isurf][d] += Using[d];
}
}
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "addsingularity"
template<typename Shape>
PetscErrorCode addsingularity(singularity<Shape, 2> sing,
particle<Shape> const& p1, particle<Shape> const& p2,
petsc::petsc_vec<2>& sol,
geometry::box<int, 2> box,
std::array<double, 2> const& h)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
const int Dimensions = 2;
using position_type = geometry::position<double, Dimensions>;
using position_type_i = geometry::position<int, Dimensions>;
std::array<double, Dimensions> hs = {{h[0]/sing.scale, h[1]/sing.scale}};
double coef = 1./(sing.scale*sing.scale);
for(std::size_t j=box.bottom_left[1]; j<box.upper_right[1]; ++j)
{
for(std::size_t i=box.bottom_left[0]; i<box.upper_right[0]; ++i)
{
position_type_i pts_i = {i, j};
auto ielem = fem::get_element(pts_i);
for(std::size_t js=0; js<sing.scale; ++js)
{
for(std::size_t is=0; is<sing.scale; ++is)
{
position_type pts = {i*h[0] + is*hs[0], j*h[1] + js*hs[1]};
if (!p1.contains(pts) && !p2.contains(pts))
{
auto pos_ref_part = sing.get_pos_in_part_ref(pts);
if (std::abs(pos_ref_part[1]) <= sing.cutoff_dist_)
{
position_type pts_loc = {is*hs[0], js*hs[1]};
auto bfunc = fem::P1_integration(pts_loc, h);
auto Using = sing.get_u_sing(pts);
for (std::size_t je=0; je<bfunc.size(); ++je)
{
auto u = sol.at(ielem[je]);
for (std::size_t d=0; d<Dimensions; ++d)
u[d] += coef*Using[d]*bfunc[je];
}
}
}
}
}
}
}
// const int Dimensions = 2;
// using position_type = geometry::position<Dimensions, double>;
// using position_type_i = geometry::position<Dimensions, int>;
// for(std::size_t j=box.bottom_left[1]; j<box.upper_right[1]; ++j)
// {
// for(std::size_t i=box.bottom_left[0]; i<box.upper_right[0]; ++i)
// {
// std::array<int, 2> pts_i = {{static_cast<int>(i), static_cast<int>(j)}};
// position_type pts{i*h[0], j*h[1]};
// if (!p1.contains(pts) && !p2.contains(pts))
// {
// auto pos_ref_part = sing.get_pos_in_part_ref(pts);
// if (std::abs(pos_ref_part[1]) <= sing.cutoff_dist_)
// {
// auto Using = sing.get_u_sing(pts);
// auto u = sol.at(pts_i);
// for (std::size_t d=0; d<Dimensions; ++d)
// u[d] += Using[d];
// }
// }
// }
// }
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "add_singularity_in_fluid"
template<std::size_t Dimensions, typename Ctx>
PetscErrorCode add_singularity_in_fluid(Ctx& ctx)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
std::cout<<"add singularity in fluid...\n";
auto union_box_func = geometry::union_box<int, Dimensions>;
auto box = fem::get_DM_bounds<Dimensions>(ctx.problem.ctx->dm, 0);
auto& h = ctx.problem.ctx->h;
auto sol = petsc::petsc_vec<Dimensions>(ctx.problem.ctx->dm, ctx.problem.rhs, 0, false);
ierr = sol.fill(0.);CHKERRQ(ierr);
// auto boxp = fem::get_DM_bounds<Dimensions>(ctx.problem.ctx->dm, 1);
// std::array<double, Dimensions> hp;
// for(std::size_t d=0; d<Dimensions; ++d)
// hp[d] = 2*ctx.problem.ctx->h[d];
// auto solp = petsc::petsc_vec<Dimensions>(ctx.problem.ctx->dm, ctx.problem.rhs, 1, false);
// ierr = solp.fill(0.);CHKERRQ(ierr);
//Loop on particles couples
for (std::size_t ipart=0; ipart<ctx.particles.size()-1; ++ipart)
{
auto p1 = ctx.particles[ipart];
for (std::size_t jpart=ipart+1; jpart<ctx.particles.size(); ++jpart)
{
auto p2 = ctx.particles[jpart];
using shape_type = typename decltype(p1)::shape_type;
auto sing = singularity<shape_type, Dimensions>(p1, p2, h[0]);
if (sing.is_singularity_)
{
auto pbox = sing.get_box(h);
if (geometry::intersect(box, pbox))
{
auto new_box = geometry::box_inside(box, pbox);
ierr = computesingularST(sing, p1, p2, sol, new_box, h);CHKERRQ(ierr);
}
// auto pboxp = sing.get_box(hp);
// if (geometry::intersect(boxp, pboxp))
// {
// auto new_box = geometry::box_inside(boxp, pboxp);
// ierr = computesingularST_pressure(sing, p1, p2, solp, new_box, hp);CHKERRQ(ierr);
// }
}
}
}
ierr = sol.local_to_global(ADD_VALUES);CHKERRQ(ierr);
// ierr = solp.local_to_global(ADD_VALUES);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "add_singularity_to_last_sol"
template<std::size_t Dimensions, typename Ctx>
PetscErrorCode add_singularity_to_last_sol(Ctx& ctx, Vec vsol)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
auto union_box_func = geometry::union_box<int, Dimensions>;
auto box = fem::get_DM_bounds<Dimensions>(ctx.problem.ctx->dm, 0);
auto& h = ctx.problem.ctx->h;
auto sol = petsc::petsc_vec<Dimensions>(ctx.problem.ctx->dm, vsol, 0, false);
ierr = sol.global_to_local(INSERT_VALUES);CHKERRQ(ierr);
//Loop on particles couples
for (std::size_t ipart=0; ipart<ctx.particles.size()-1; ++ipart)
{
auto p1 = ctx.particles[ipart];
for (std::size_t jpart=ipart+1; jpart<ctx.particles.size(); ++jpart)
{
auto p2 = ctx.particles[jpart];
using shape_type = typename decltype(p1)::shape_type;
auto sing = singularity<shape_type, Dimensions>(p1, p2, h[0]);
if (sing.is_singularity_)
{
auto pbox = sing.get_box(h);
if (geometry::intersect(box, pbox))
{
auto new_box = geometry::box_inside(box, pbox);
ierr = addsingularity(sing, p1, p2, sol, new_box, h);CHKERRQ(ierr);
}
}
}
}
ierr = sol.local_to_global(INSERT_VALUES);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "compute_singular_forces"
template<typename Shape>
auto compute_singular_forces(singularity<Shape, 2> sing, std::size_t N)
{
using position_type = geometry::position<double, 2>;
double mu = 1.;
double theta = std::asin(sing.cutoff_dist_*sing.H1_);
physics::force<2> force{};
for (std::size_t i=-N; i<N; ++i)
{
double cos_t = std::cos(i*theta/N);
double sin_t = std::sin(i*theta/N);
std::array< std::array<double, 2>, 2> sigma;
position_type pos{(cos_t - 1.)/sing.H1_, sin_t/sing.H1_};
position_type normal{cos_t, sin_t};
auto gradUsing = sing.get_grad_u_sing_ref(pos);
auto psing = sing.get_p_sing(pos);
sigma[0][0] = 2*mu*gradUsing[0][0] - psing;
sigma[0][1] = mu*(gradUsing[0][1] + gradUsing[1][0]);
sigma[1][0] = sigma[0][1];
sigma[1][1] = 2*mu*gradUsing[1][1] - psing;
for(std::size_t d1=0; d1<2; ++d1)
for(std::size_t d2=0; d2<2; ++d2)
force[d1] += theta/N/sing.H1_*sigma[d1][d2]*normal[d2];
}
return force;
}
#undef __FUNCT__
#define __FUNCT__ "compute_singular_forces_on_part1"
template<typename Shape>
auto compute_singular_forces_on_part1(singularity<Shape, 2> sing, std::size_t N)
{
using position_type = geometry::position<double, 2>;
double mu = 1.;
double theta = std::asin(sing.cutoff_dist_*sing.H1_);
physics::force<2> force{};
for (std::size_t i=-N; i<N; ++i)
{
double cos_t = std::cos(i*theta/N);
double sin_t = std::sin(i*theta/N);
std::array< std::array<double, 2>, 2> sigma;
position_type pos{(cos_t - 1.)/sing.H1_, sin_t/sing.H1_};
position_type normal{cos_t, sin_t};
auto gradUsing = sing.get_grad_u_sing_ref(pos);
auto psing = sing.get_p_sing(pos);
sigma[0][0] = 2*mu*gradUsing[0][0] - psing;
sigma[0][1] = mu*(gradUsing[0][1] + gradUsing[1][0]);
sigma[1][0] = sigma[0][1];
sigma[1][1] = 2*mu*gradUsing[1][1] - psing;
for(std::size_t d1=0; d1<2; ++d1)
for(std::size_t d2=0; d2<2; ++d2)
force[d1] += theta/N/sing.H1_*sigma[d1][d2]*normal[d2];
}
return force;
}
#undef __FUNCT__
#define __FUNCT__ "compute_singular_forces_on_part2"
template<typename Shape>
auto compute_singular_forces_on_part2(singularity<Shape, 2> sing, std::size_t N)
{
using position_type = geometry::position<double, 2>;
double mu = 1.;
double theta = std::asin(sing.cutoff_dist_*sing.H1_);
physics::force<2> force{};
for (std::size_t i=-N; i<N; ++i)
{
double cos_t = std::cos(i*theta/N);
double sin_t = std::sin(i*theta/N);
std::array< std::array<double, 2>, 2> sigma;
position_type pos{(cos_t - 1.)/sing.H1_, sin_t/sing.H1_};
position_type normal{cos_t, sin_t};
auto gradUsing = sing.get_grad_u_sing_ref(pos);
auto psing = sing.get_p_sing(pos);
sigma[0][0] = 2*mu*gradUsing[0][0] - psing;
sigma[0][1] = mu*(gradUsing[0][1] + gradUsing[1][0]);
sigma[1][0] = sigma[0][1];
sigma[1][1] = 2*mu*gradUsing[1][1] - psing;
for(std::size_t d1=0; d1<2; ++d1)
for(std::size_t d2=0; d2<2; ++d2)
force[d1] += theta/N/sing.H1_*sigma[d1][d2]*normal[d2];
}
return force;
}
#undef __FUNCT__
#define __FUNCT__ "compute_singular_forces_on_part1"
template<typename Shape>
auto compute_singular_forces_on_part1(singularity<Shape, 3> sing, std::size_t N)
{
using position_type = geometry::position<double, 3>;
double mu = 1.;
double theta = std::asin(sing.cutoff_dist_*sing.H1_);
double A = 2*M_PI*theta/N/N/sing.H1_/sing.H1_;
physics::force<3> force{};
physics::force<3> force_ref{};
for (std::size_t i=1; i<=N; ++i)
{
double cosi_t = std::cos(i*theta/N);
double sini_t = std::sin(i*theta/N);
double coef = A*sini_t;
for (std::size_t j=1; j<=N; ++j)
{
double cosj_t = std::cos(2*M_PI*j/N);
double sinj_t = std::sin(2*M_PI*j/N);
std::array< std::array<double, 3>, 3> sigma;
position_type pos{sini_t*cosj_t/sing.H1_, sini_t*sinj_t/sing.H1_, (cosi_t - 1.)/sing.H1_};
position_type normal{sini_t*cosj_t, sini_t*sinj_t, cosi_t};
auto gradUsing = sing.get_grad_u_sing_ref(pos);
auto psing = sing.get_p_sing_ref(pos);
sigma[0][0] = 2*mu*gradUsing[0][0] - psing;
sigma[0][1] = 2*mu*gradUsing[0][1];
sigma[0][2] = mu*(gradUsing[0][2] + gradUsing[2][0]);
sigma[1][0] = sigma[0][1];
sigma[1][1] = 2*mu*gradUsing[1][1] - psing;
sigma[1][2] = mu*(gradUsing[1][2] + gradUsing[2][1]);
sigma[2][0] = sigma[0][2];
sigma[2][1] = sigma[1][2];
sigma[2][2] = 2*mu*gradUsing[2][2] - psing;
for(std::size_t d1=0; d1<3; ++d1)
for(std::size_t d2=0; d2<3; ++d2)
force_ref[d1] += coef*sigma[d1][d2]*normal[d2];
for(std::size_t d1=0; d1<3; ++d1)
for(std::size_t d2=0; d2<3; ++d2)
force[d1] += sing.base_[d2][d1]*force_ref[d2];
}
}
return force;
}
#undef __FUNCT__
#define __FUNCT__ "compute_singular_forces_on_part2"
template<typename Shape>
auto compute_singular_forces_on_part2(singularity<Shape, 3> sing, std::size_t N)
{
using position_type = geometry::position<double, 3>;
double mu = 1.;
double theta = std::asin(sing.cutoff_dist_*sing.H2_);
double A = 2*M_PI*theta/N/N/sing.H2_/sing.H2_;
physics::force<3> force{};
physics::force<3> force_ref{};
for (std::size_t i=1; i<=N; ++i)
{
double cosi_t = std::cos(i*theta/N);
double sini_t = std::sin(i*theta/N);
double coef = A*sini_t;
for (std::size_t j=1; j<=N; ++j)
{
double cosj_t = std::cos(2*M_PI*j/N);
double sinj_t = std::sin(2*M_PI*j/N);
std::array< std::array<double, 3>, 3> sigma;
position_type pos{sini_t*cosj_t/sing.H2_, sini_t*sinj_t/sing.H2_, sing.contact_length_ + (1. - cosi_t)/sing.H2_};
position_type normal{sini_t*cosj_t, sini_t*sinj_t, -cosi_t};
auto gradUsing = sing.get_grad_u_sing_ref(pos);
auto psing = sing.get_p_sing_ref(pos);
sigma[0][0] = 2*mu*gradUsing[0][0] - psing;
sigma[0][1] = 2*mu*gradUsing[0][1];
sigma[0][2] = mu*(gradUsing[0][2] + gradUsing[2][0]);
sigma[1][0] = sigma[0][1];
sigma[1][1] = 2*mu*gradUsing[1][1] - psing;
sigma[1][2] = mu*(gradUsing[1][2] + gradUsing[2][1]);
sigma[2][0] = sigma[0][2];
sigma[2][1] = sigma[1][2];
sigma[2][2] = 2*mu*gradUsing[2][2] - psing;
for(std::size_t d1=0; d1<3; ++d1)
for(std::size_t d2=0; d2<3; ++d2)
force_ref[d1] += coef*sigma[d1][d2]*normal[d2];
for(std::size_t d1=0; d1<3; ++d1)
for(std::size_t d2=0; d2<3; ++d2)
force[d1] += sing.base_[d2][d1]*force_ref[d2];
}
}
return force;
}
#undef __FUNCT__
#define __FUNCT__ "compute_singular_forces"
template<std::size_t Dimensions, typename Ctx>
PetscErrorCode compute_singular_forces(Ctx& ctx, std::size_t N=100)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
auto& h = ctx.problem.ctx->h;
for (std::size_t ipart=0; ipart<ctx.particles.size(); ++ipart)
ctx.particles[ipart].force_.fill(0.);
//Loop on particles couples
for (std::size_t ipart=0; ipart<ctx.particles.size()-1; ++ipart)
{
auto p1 = ctx.particles[ipart];
for (std::size_t jpart=ipart+1; jpart<ctx.particles.size(); ++jpart)
{
auto p2 = ctx.particles[jpart];
using shape_type = typename decltype(p1)::shape_type;
auto sing = singularity<shape_type, Dimensions>(p1, p2, h[0]);
if (sing.is_singularity_)
{
ctx.particles[ipart].force_ -= compute_singular_forces_on_part1(sing, N);
ctx.particles[jpart].force_ -= compute_singular_forces_on_part2(sing, N);
}
}
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "compute_singular_forces"
template<std::size_t Dimensions, typename Shape>
PetscErrorCode compute_singular_forces(std::vector<particle<Shape>> const& particles,
std::vector<physics::force<Dimensions>>& forces,
std::array<double, Dimensions> const& h,
std::size_t N=100)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
for (std::size_t ipart=0; ipart<particles.size(); ++ipart)
forces[ipart].fill(0.);
//Loop on particles couples
for (std::size_t ipart=0; ipart<particles.size()-1; ++ipart)
{
auto p1 = particles[ipart];
for (std::size_t jpart=ipart+1; jpart<particles.size(); ++jpart)
{
auto p2 = particles[jpart];
//using shape_type = typename decltype(p1)::shape_type;
auto sing = singularity<Shape, Dimensions>(p1, p2, h[0]);
if (sing.is_singularity_)
{
forces[ipart] -= compute_singular_forces_on_part1(sing, N);
forces[jpart] -= compute_singular_forces_on_part2(sing, N);
}
}
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "add_singularity_to_surf"
template<std::size_t Dimensions, typename Ctx>
PetscErrorCode add_singularity_to_surf(Ctx& ctx, std::vector<std::vector<std::array<double, Dimensions>>>& g)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
std::cout<<"add singularity to surf...\n";
auto union_box_func = geometry::union_box<int, Dimensions>;
auto box = fem::get_DM_bounds<Dimensions>(ctx.problem.ctx->dm, 0);
auto& h = ctx.problem.ctx->h;
//Loop on particles couples
for (std::size_t ipart=0; ipart<ctx.particles.size()-1; ++ipart)
{
auto p1 = ctx.particles[ipart];
for (std::size_t jpart=ipart+1; jpart<ctx.particles.size(); ++jpart)
{
auto p2 = ctx.particles[jpart];
using shape_type = typename decltype(p1)::shape_type;
auto sing = singularity<shape_type, Dimensions>(p1, p2, h[0]);
if (sing.is_singularity_)
{
auto pbox = sing.get_box(h);
if (geometry::intersect(box, pbox))
{
auto new_box = geometry::box_inside(box, pbox);
geometry::box<double, Dimensions> new_box_d{new_box.bottom_left, new_box.upper_right};
new_box_d.bottom_left *= h;
new_box_d.upper_right *= h;
ierr = computesingularBC(ctx, sing, ipart, jpart, new_box_d, g);CHKERRQ(ierr);
}
}
}
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "add_singularity_to_surf"
template<std::size_t Dimensions, typename Ctx>
PetscErrorCode add_singularity_to_surf(Ctx& ctx, petsc::petsc_vec<Dimensions>& sol)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
std::cout<<"add singularity to surf new...\n";
auto union_box_func = geometry::union_box<int, Dimensions>;
auto box = fem::get_DM_bounds<Dimensions>(ctx.problem.ctx->dm, 0);
auto& h = ctx.problem.ctx->h;
//Loop on particles couples
for (std::size_t ipart=0; ipart<ctx.particles.size()-1; ++ipart)
{
auto p1 = ctx.particles[ipart];
for (std::size_t jpart=ipart+1; jpart<ctx.particles.size(); ++jpart)
{
auto p2 = ctx.particles[jpart];
using shape_type = typename decltype(p1)::shape_type;
auto sing = singularity<shape_type, Dimensions>(p1, p2, h[0]);
// uncomment for 2D and implement for 3D
// if (sing.is_singularity_)
// {
// ierr = computesingularBC(sing, sol, h, box);CHKERRQ(ierr);
// }
}
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "save_singularity"
template<std::size_t Dimensions, typename Shape>
PetscErrorCode save_singularity(const char* path,
const char* filename,
singularity<Shape, Dimensions> sing,
particle<Shape> const& p1, particle<Shape> const& p2,
geometry::box<int, 2> box,
std::array<double, 2> const& h)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
using position_type = geometry::position<double, Dimensions>;
using position_type_i = geometry::position<int, Dimensions>;
vtkStructuredGrid* singDataSet;
singDataSet = vtkStructuredGrid::New();
singDataSet->SetExtent(0, box.length(0)*sing.scale-1, 0, box.length(1)*sing.scale-1, 0, 0);
vtkPoints* singPoints = vtkPoints::New();
vtkDoubleArray* velocity_sing = vtkDoubleArray::New();
velocity_sing->SetNumberOfComponents(3);
velocity_sing->SetName("velocity_sing");
vtkDoubleArray* gradx_velocity_sing = vtkDoubleArray::New();
gradx_velocity_sing->SetNumberOfComponents(3);
gradx_velocity_sing->SetName("gradx_velocity_sing");
vtkDoubleArray* grady_velocity_sing = vtkDoubleArray::New();
grady_velocity_sing->SetNumberOfComponents(3);
grady_velocity_sing->SetName("grady_velocity_sing");
vtkDoubleArray* pressure_sing = vtkDoubleArray::New();
pressure_sing->SetName("pressure_sing");
std::array<double, Dimensions> hs = {{h[0]/sing.scale, h[1]/sing.scale}};
double coef = 1./(sing.scale*sing.scale);
for(std::size_t j=box.bottom_left[1]; j<box.upper_right[1]; ++j)
{
for(std::size_t js=0; js<sing.scale; ++js)
{
for(std::size_t i=box.bottom_left[0]; i<box.upper_right[0]; ++i)
{
position_type_i pts_i = {i, j};
for(std::size_t is=0; is<sing.scale; ++is){
position_type pts = {i*h[0] + is*hs[0], j*h[1] + js*hs[1]};
singPoints->InsertNextPoint(pts[0], pts[1], 0.);
bool add_sing = false;
if (!p1.contains(pts) && !p2.contains(pts))
{
auto pos_ref_part = sing.get_pos_in_part_ref(pts);
if (std::abs(pos_ref_part[1]) <= sing.cutoff_dist_)
{
add_sing = true;
//position_type pts_loc = {is*hs[0], js*hs[1]};
auto Using = sing.get_u_sing(pts);
auto gradUsing = sing.get_grad_u_sing(pts);
auto psing = sing.get_p_sing(pts);
// Add points to vtk + singular value to vtk
velocity_sing->InsertNextTuple3(Using[0], Using[1], 0.);
gradx_velocity_sing->InsertNextTuple3(gradUsing[0][0], gradUsing[1][0], 0.);
grady_velocity_sing->InsertNextTuple3(gradUsing[0][1], gradUsing[1][1], 0.);
pressure_sing->InsertNextValue(psing);
}
}
if (!add_sing)
{
velocity_sing->InsertNextTuple3(0., 0., 0.);
gradx_velocity_sing->InsertNextTuple3(0., 0., 0.);
grady_velocity_sing->InsertNextTuple3(0., 0., 0.);
pressure_sing->InsertNextValue(0.);
}
}
}
}
}
singDataSet->SetPoints(singPoints);
singDataSet->GetPointData()->AddArray(velocity_sing);
singDataSet->GetPointData()->AddArray(gradx_velocity_sing);
singDataSet->GetPointData()->AddArray(grady_velocity_sing);
singDataSet->GetPointData()->SetScalars(pressure_sing);
vtkXMLStructuredGridWriter* singDataWriter = vtkXMLStructuredGridWriter::New();
std::stringstream oc;
oc << path << "/" << filename << "_sing_" << 0 << "_" << 1 << ".vts";//a changer
singDataWriter->SetFileName(oc.str().data());
//dataWriter->SetDataModeToAscii();
#if VTK_MAJOR_VERSION <= 5
singDataWriter->SetInput(singDataSet);
#else
singDataWriter->SetInputData(singDataSet);
#endif
singDataWriter->Write();
singPoints->Delete();
velocity_sing->Delete();
gradx_velocity_sing->Delete();
grady_velocity_sing->Delete();
singDataSet->Delete();
singDataWriter->Delete();
pressure_sing->Delete();
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "save_singularity"
template<typename Shape, std::size_t Dimensions>
PetscErrorCode save_singularity(const char* path,
const char* filename,
singularity<Shape, Dimensions> sing,
particle<Shape> const& p1, particle<Shape> const& p2,
geometry::box<int, 3> box,
std::array<double, 3> const& h)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
using position_type = geometry::position<double, Dimensions>;
using position_type_i = geometry::position<int, Dimensions>;
vtkStructuredGrid* singDataSet;
singDataSet = vtkStructuredGrid::New();
singDataSet->SetExtent(0, box.length(0)*sing.scale-1, 0, box.length(1)*sing.scale-1, 0, box.length(2)*sing.scale-1);
vtkPoints* singPoints = vtkPoints::New();
vtkDoubleArray* velocity_sing = vtkDoubleArray::New();
velocity_sing->SetNumberOfComponents(3);
velocity_sing->SetName("velocity_sing");
vtkDoubleArray* gradx_velocity_sing = vtkDoubleArray::New();
gradx_velocity_sing->SetNumberOfComponents(3);
gradx_velocity_sing->SetName("gradx_velocity_sing");
vtkDoubleArray* grady_velocity_sing = vtkDoubleArray::New();
grady_velocity_sing->SetNumberOfComponents(3);
grady_velocity_sing->SetName("grady_velocity_sing");
vtkDoubleArray* pressure_sing = vtkDoubleArray::New();
pressure_sing->SetName("pressure_sing");
std::array<double, Dimensions> hs = {{h[0]/sing.scale, h[1]/sing.scale, h[2]/sing.scale}};
double coef = 1./(sing.scale*sing.scale*sing.scale);
for(std::size_t k=box.bottom_left[2]; k<box.upper_right[2]; ++k)
{
for(std::size_t ks=0; ks<sing.scale; ++ks)
{
for(std::size_t j=box.bottom_left[1]; j<box.upper_right[1]; ++j)
{
for(std::size_t js=0; js<sing.scale; ++js)
{
for(std::size_t i=box.bottom_left[0]; i<box.upper_right[0]; ++i)
{
position_type_i pts_i = {i, j, k};
for(std::size_t is=0; is<sing.scale; ++is){
position_type pts = {i*h[0] + is*hs[0], j*h[1] + js*hs[1], k*h[2] + ks*hs[2]};
singPoints->InsertNextPoint(pts[0], pts[1], pts[2]);
bool add_sing = false;
if (!p1.contains(pts) && !p2.contains(pts))
{
auto pos_ref_part = sing.get_pos_in_part_ref(pts);
if (std::abs(pos_ref_part[1]) <= sing.cutoff_dist_)
{
add_sing = true;
//position_type pts_loc = {is*hs[0], js*hs[1], ks*hs[2]};
auto Using = sing.get_u_sing(pts);
auto gradUsing = sing.get_grad_u_sing(pts);
auto psing = sing.get_p_sing(pts);
// Add points to vtk + singular value to vtk
velocity_sing->InsertNextTuple3(Using[0], Using[1], Using[2]);
gradx_velocity_sing->InsertNextTuple3(gradUsing[0][0], gradUsing[0][1], gradUsing[0][2]);
grady_velocity_sing->InsertNextTuple3(gradUsing[1][0], gradUsing[1][1], gradUsing[1][2]);
pressure_sing->InsertNextValue(psing);
}
}
if (!add_sing)
{
velocity_sing->InsertNextTuple3(0., 0., 0.);
gradx_velocity_sing->InsertNextTuple3(0., 0., 0.);
grady_velocity_sing->InsertNextTuple3(0., 0., 0.);
pressure_sing->InsertNextValue(0.);
}
}
}
}
}
}
}
singDataSet->SetPoints(singPoints);
singDataSet->GetPointData()->AddArray(velocity_sing);
singDataSet->GetPointData()->AddArray(gradx_velocity_sing);
singDataSet->GetPointData()->AddArray(grady_velocity_sing);
singDataSet->GetPointData()->SetScalars(pressure_sing);
vtkXMLStructuredGridWriter* singDataWriter = vtkXMLStructuredGridWriter::New();
std::stringstream oc;
oc << path << "/" << filename << "_sing_" << 0 << "_" << 1 << ".vts";//a changer
singDataWriter->SetFileName(oc.str().data());
//dataWriter->SetDataModeToAscii();
#if VTK_MAJOR_VERSION <= 5
singDataWriter->SetInput(singDataSet);
#else
singDataWriter->SetInputData(singDataSet);
#endif
singDataWriter->Write();
singPoints->Delete();
velocity_sing->Delete();
gradx_velocity_sing->Delete();
grady_velocity_sing->Delete();
singDataSet->Delete();
singDataWriter->Delete();
pressure_sing->Delete();
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "save_singularity"
template<std::size_t Dimensions, typename Ctx>
PetscErrorCode save_singularity(const char* path,
const char* filename,
Ctx& ctx)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
auto union_box_func = geometry::union_box<int, Dimensions>;
auto box = fem::get_DM_bounds<Dimensions>(ctx.problem.ctx->dm, 0);
auto& h = ctx.problem.ctx->h;
//Loop on particles couples
for (std::size_t ipart=0; ipart<ctx.particles.size()-1; ++ipart)
{
auto p1 = ctx.particles[ipart];
for (std::size_t jpart=ipart+1; jpart<ctx.particles.size(); ++jpart)
{
auto p2 = ctx.particles[jpart];
using shape_type = typename decltype(p1)::shape_type;
auto sing = singularity<shape_type, Dimensions>(p1, p2, h[0]);
if (sing.is_singularity_)
{
// auto pbox = union_box_func({geometry::floor((p1.center_ - sing.cutoff_dist_)/h),
// geometry::ceil((p1.center_ + sing.cutoff_dist_)/h)},
// {geometry::floor((p2.center_ - sing.cutoff_dist_)/h),
// geometry::ceil((p2.center_ + sing.cutoff_dist_)/h)});
auto pbox = sing.get_box(h);
if (geometry::intersect(box, pbox))
{
auto new_box = geometry::box_inside(box, pbox);
ierr = save_singularity(path, filename, sing, p1, p2, new_box, h);CHKERRQ(ierr);
}
}
}
}
PetscFunctionReturn(0);
}
}
}
#endif
| 35.693845 | 123 | 0.547936 | Fvergnet |
4ce60873693b4ff941ad954cbe01d4380b7c87bb | 5,516 | hpp | C++ | cpp-projects/base/geometry/shapes/aabb3.hpp | FlorianLance/toolbox | 87882a14ec86852d90527c81475b451b9f6e12cf | [
"MIT"
] | null | null | null | cpp-projects/base/geometry/shapes/aabb3.hpp | FlorianLance/toolbox | 87882a14ec86852d90527c81475b451b9f6e12cf | [
"MIT"
] | null | null | null | cpp-projects/base/geometry/shapes/aabb3.hpp | FlorianLance/toolbox | 87882a14ec86852d90527c81475b451b9f6e12cf | [
"MIT"
] | 1 | 2021-07-06T14:47:41.000Z | 2021-07-06T14:47:41.000Z |
///*******************************************************************************
//** Toolbox-base **
//** MIT License **
//** Copyright (c) [2018] [Florian Lance] **
//** **
//** 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
//// local
//#include "geometry/shapes/line3.hpp"
//#include "geometry/interval.hpp"
//#include "utility/maths_utility.hpp"
//namespace tool::geo {
//template<typename acc>
//struct AABB3{
// AABB3() = default;
// constexpr AABB3(const Pt3<acc> &o, const Vec3<acc> &s) noexcept : origin(o), size(s){
// }
// constexpr Vec3<acc> min() const noexcept{
// const Vec3<acc> p1 = origin + size;
// const Vec3<acc> p2 = origin - size;
// return Vec3<acc>(std::min(p1.x(), p2.x()), std::min(p1.y(), p2.y()),std::min(p1.z(), p2.z()));
// }
// constexpr Vec3<acc> max() const noexcept{
// const Vec3<acc> p1 = origin + size;
// const Vec3<acc> p2 = origin - size;
// return Vec3<acc>(std::max(p1.x(), p2.x()), std::max(p1.y(), p2.y()),std::max(p1.z(), p2.z()));
// }
// Pt3<acc> origin = {0,0,0};
// Vec3<acc> size = {1,1,1};
//};
//template<typename acc>
//constexpr AABB3<acc> aabb_from_points(const Vec3<acc> &min, const Vec3<acc> &max) noexcept{
// return AABB3<acc>((min + max) * acc{0.5}, (max - min) * acc{0.5});
//}
//template <typename acc>
//constexpr bool point_in_aabb(const Pt3<acc> &p, const AABB3<acc> &aabb) noexcept{
// const Pt3<acc> pMin = aabb.min();
// const Pt3<acc> pMax = aabb.max();
// const bool xMinE = tool::almost_equal<acc>(p.x(),pMin.x());
// const bool yMinE = tool::almost_equal<acc>(p.y(),pMin.y());
// const bool zMinE = tool::almost_equal<acc>(p.z(),pMin.z());
// if((p.x() > pMin.x() || xMinE) && (p.y() > pMin.y() || yMinE) && (p.z() > pMin.z() || zMinE)){
// const bool xMaxE = tool::almost_equal<acc>(p.x(),pMax.x());
// const bool yMaxE = tool::almost_equal<acc>(p.y(),pMax.y());
// const bool zMaxE = tool::almost_equal<acc>(p.z(),pMax.z());
// if((p.x() < pMax.x() || xMaxE) && (p.y() < pMax.y() || yMaxE) && (p.z() < pMax.z() || zMaxE)){
// return true;
// }
// }
// return false;
//}
//template <typename acc>
//constexpr Pt3<acc> closest_point(const AABB3<acc> &aabb, const Pt3<acc> &p) noexcept{
// Pt3<acc> res = p;
// const Pt3<acc> pMin = aabb.min();
// const Pt3<acc> pMax = aabb.max();
// res.x() = (res.x() < pMin.x()) ? pMin.x() : res.x();
// res.y() = (res.y() < pMin.y()) ? pMin.y() : res.y();
// res.z() = (res.z() < pMin.z()) ? pMin.z() : res.z();
// res.x() = (res.x() > pMax.x()) ? pMax.x() : res.x();
// res.y() = (res.y() > pMax.y()) ? pMax.y() : res.y();
// res.z() = (res.z() > pMax.z()) ? pMax.z() : res.z();
// return res;
//}
//template<typename acc>
//constexpr Interval<acc> interval(const AABB3<acc> &aabb, const Vec3<acc> &axis) noexcept{
// const Pt3<acc> i = aabb.min();
// const Pt3<acc> a = aabb.max();
// const std_a1<Vec3<acc>,8> vertices = {
// Pt3<acc>(i.x(), a.y(), a.z()),
// Pt3<acc>(i.x(), a.y(), i.z()),
// Pt3<acc>(i.x(), i.y(), a.z()),
// Pt3<acc>(i.x(), i.y(), i.z()),
// Pt3<acc>(a.x(), a.y(), a.z()),
// Pt3<acc>(a.x(), a.y(), i.z()),
// Pt3<acc>(a.x(), i.y(), a.z()),
// Pt3<acc>(a.x(), i.y(), i.z())
// };
// const acc dotV = dot(axis, vertices[0]);
// Interval<acc> res{dotV,dotV};
// for(const auto &pt : vertices){
// const acc projection = dot(axis,pt);
// res.min() = (projection < res.min()) ? projection : res.min();
// res.max() = (projection > res.max()) ? projection : res.max();
// }
// return res;
//}
//}
| 39.683453 | 104 | 0.485497 | FlorianLance |
4ce9dc142492ee37a38dabbb1ba2a2379f06912c | 12,270 | cxx | C++ | src/common/PokemonSpecies.cxx | Archaemic/tachyon | 46b6684a5d8c71c84641050f0453d6a6d1d6d1a5 | [
"BSD-2-Clause-FreeBSD"
] | 2 | 2015-09-11T19:22:58.000Z | 2017-06-09T20:40:11.000Z | src/common/PokemonSpecies.cxx | Archaemic/tachyon | 46b6684a5d8c71c84641050f0453d6a6d1d6d1a5 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | src/common/PokemonSpecies.cxx | Archaemic/tachyon | 46b6684a5d8c71c84641050f0453d6a6d1d6d1a5 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | #include "common/PokemonSpecies.h"
const static char* speciesNames[] = {
u8"MissingNo.",
u8"Bulbasaur",
u8"Ivysaur",
u8"Venusaur",
u8"Charmander",
u8"Charmeleon",
u8"Charizard",
u8"Squirtle",
u8"Wartortle",
u8"Blastoise",
u8"Caterpie",
u8"Metapod",
u8"Butterfree",
u8"Weedle",
u8"Kakuna",
u8"Beedrill",
u8"Pidgey",
u8"Pidgeotto",
u8"Pidgeot",
u8"Rattata",
u8"Raticate",
u8"Spearow",
u8"Fearow",
u8"Ekans",
u8"Arbok",
u8"Pikachu",
u8"Raichu",
u8"Sandshrew",
u8"Sandslash",
u8"Nidoran♀",
u8"Nidorina",
u8"Nidoqueen",
u8"Nidoran♂",
u8"Nidorino",
u8"Nidoking",
u8"Clefairy",
u8"Clefable",
u8"Vulpix",
u8"Ninetales",
u8"Jigglypuff",
u8"Wigglytuff",
u8"Zubat",
u8"Golbat",
u8"Oddish",
u8"Gloom",
u8"Vileplume",
u8"Paras",
u8"Parasect",
u8"Venonat",
u8"Venomoth",
u8"Diglett",
u8"Dugtrio",
u8"Meowth",
u8"Persian",
u8"Psyduck",
u8"Golduck",
u8"Mankey",
u8"Primeape",
u8"Growlithe",
u8"Arcanine",
u8"Poliwag",
u8"Poliwhirl",
u8"Poliwrath",
u8"Abra",
u8"Kadabra",
u8"Alakazam",
u8"Machop",
u8"Machoke",
u8"Machamp",
u8"Bellsprout",
u8"Weepinbell",
u8"Victreebel",
u8"Tentacool",
u8"Tentacruel",
u8"Geodude",
u8"Graveler",
u8"Golem",
u8"Ponyta",
u8"Rapidash",
u8"Slowpoke",
u8"Slowbro",
u8"Magnemite",
u8"Magneton",
u8"Farfetch'd",
u8"Doduo",
u8"Dodrio",
u8"Seel",
u8"Dewgong",
u8"Grimer",
u8"Muk",
u8"Shellder",
u8"Cloyster",
u8"Gastly",
u8"Haunter",
u8"Gengar",
u8"Onix",
u8"Drowzee",
u8"Hypno",
u8"Krabby",
u8"Kingler",
u8"Voltorb",
u8"Electrode",
u8"Exeggcute",
u8"Exeggutor",
u8"Cubone",
u8"Marowak",
u8"Hitmonlee",
u8"Hitmonchan",
u8"Lickitung",
u8"Koffing",
u8"Weezing",
u8"Rhyhorn",
u8"Rhydon",
u8"Chansey",
u8"Tangela",
u8"Kangaskhan",
u8"Horsea",
u8"Seadra",
u8"Goldeen",
u8"Seaking",
u8"Staryu",
u8"Starmie",
u8"Mr. Mime",
u8"Scyther",
u8"Jynx",
u8"Electabuzz",
u8"Magmar",
u8"Pinsir",
u8"Tauros",
u8"Magikarp",
u8"Gyarados",
u8"Lapras",
u8"Ditto",
u8"Eevee",
u8"Vaporeon",
u8"Jolteon",
u8"Flareon",
u8"Porygon",
u8"Omanyte",
u8"Omastar",
u8"Kabuto",
u8"Kabutops",
u8"Aerodactyl",
u8"Snorlax",
u8"Articuno",
u8"Zapdos",
u8"Moltres",
u8"Dratini",
u8"Dragonair",
u8"Dragonite",
u8"Mewtwo",
u8"Mew",
u8"Chikorita",
u8"Bayleef",
u8"Meganium",
u8"Cyndaquil",
u8"Quilava",
u8"Typhlosion",
u8"Totodile",
u8"Croconaw",
u8"Feraligatr",
u8"Sentret",
u8"Furret",
u8"Hoothoot",
u8"Noctowl",
u8"Ledyba",
u8"Ledian",
u8"Spinarak",
u8"Ariados",
u8"Crobat",
u8"Chinchou",
u8"Lanturn",
u8"Pichu",
u8"Cleffa",
u8"Igglybuff",
u8"Togepi",
u8"Togetic",
u8"Natu",
u8"Xatu",
u8"Mareep",
u8"Flaaffy",
u8"Ampharos",
u8"Bellossom",
u8"Marill",
u8"Azumarill",
u8"Sudowoodo",
u8"Politoed",
u8"Hoppip",
u8"Skiploom",
u8"Jumpluff",
u8"Aipom",
u8"Sunkern",
u8"Sunflora",
u8"Yanma",
u8"Wooper",
u8"Quagsire",
u8"Espeon",
u8"Umbreon",
u8"Murkrow",
u8"Slowking",
u8"Misdreavus",
u8"Unown",
u8"Wobbuffet",
u8"Girafarig",
u8"Pineco",
u8"Forretress",
u8"Dunsparce",
u8"Gligar",
u8"Steelix",
u8"Snubbull",
u8"Granbull",
u8"Qwilfish",
u8"Scizor",
u8"Shuckle",
u8"Heracross",
u8"Sneasel",
u8"Teddiursa",
u8"Ursaring",
u8"Slugma",
u8"Magcargo",
u8"Swinub",
u8"Piloswine",
u8"Corsola",
u8"Remoraid",
u8"Octillery",
u8"Delibird",
u8"Mantine",
u8"Skarmory",
u8"Houndour",
u8"Houndoom",
u8"Kingdra",
u8"Phanpy",
u8"Donphan",
u8"Porygon2",
u8"Stantler",
u8"Smeargle",
u8"Tyrogue",
u8"Hitmontop",
u8"Smoochum",
u8"Elekid",
u8"Magby",
u8"Miltank",
u8"Blissey",
u8"Raikou",
u8"Entei",
u8"Suicune",
u8"Larvitar",
u8"Pupitar",
u8"Tyranitar",
u8"Lugia",
u8"Ho-oh",
u8"Celebi",
u8"Treecko",
u8"Grovyle",
u8"Sceptile",
u8"Torchic",
u8"Combusken",
u8"Blaziken",
u8"Mudkip",
u8"Marshtomp",
u8"Swampert",
u8"Poochyena",
u8"Mightyena",
u8"Zigzagoon",
u8"Linoone",
u8"Wurmple",
u8"Silcoon",
u8"Beautifly",
u8"Cascoon",
u8"Dustox",
u8"Lotad",
u8"Lombre",
u8"Ludicolo",
u8"Seedot",
u8"Nuzleaf",
u8"Shiftry",
u8"Taillow",
u8"Swellow",
u8"Wingull",
u8"Pelipper",
u8"Ralts",
u8"Kirlia",
u8"Gardevoir",
u8"Surskit",
u8"Masquerain",
u8"Shroomish",
u8"Breloom",
u8"Slakoth",
u8"Vigoroth",
u8"Slaking",
u8"Nincada",
u8"Ninjask",
u8"Shedinja",
u8"Whismur",
u8"Loudred",
u8"Exploud",
u8"Makuhita",
u8"Hariyama",
u8"Azurill",
u8"Nosepass",
u8"Skitty",
u8"Delcatty",
u8"Sableye",
u8"Mawile",
u8"Aron",
u8"Lairon",
u8"Aggron",
u8"Meditite",
u8"Medicham",
u8"Electrike",
u8"Manectric",
u8"Plusle",
u8"Minun",
u8"Volbeat",
u8"Illumise",
u8"Roselia",
u8"Gulpin",
u8"Swalot",
u8"Carvanha",
u8"Sharpedo",
u8"Wailmer",
u8"Wailord",
u8"Numel",
u8"Camerupt",
u8"Torkoal",
u8"Spoink",
u8"Grumpig",
u8"Spinda",
u8"Trapinch",
u8"Vibrava",
u8"Flygon",
u8"Cacnea",
u8"Cacturne",
u8"Swablu",
u8"Altaria",
u8"Zangoose",
u8"Seviper",
u8"Lunatone",
u8"Solrock",
u8"Barboach",
u8"Whiscash",
u8"Corphish",
u8"Crawdaunt",
u8"Baltoy",
u8"Claydol",
u8"Lileep",
u8"Cradily",
u8"Anorith",
u8"Armaldo",
u8"Feebas",
u8"Milotic",
u8"Castform",
u8"Kecleon",
u8"Shuppet",
u8"Banette",
u8"Duskull",
u8"Dusclops",
u8"Tropius",
u8"Chimecho",
u8"Absol",
u8"Wynaut",
u8"Snorunt",
u8"Glalie",
u8"Spheal",
u8"Sealeo",
u8"Walrein",
u8"Clamperl",
u8"Huntail",
u8"Gorebyss",
u8"Relicanth",
u8"Luvdisc",
u8"Bagon",
u8"Shelgon",
u8"Salamence",
u8"Beldum",
u8"Metang",
u8"Metagross",
u8"Regirock",
u8"Regice",
u8"Registeel",
u8"Latias",
u8"Latios",
u8"Kyogre",
u8"Groudon",
u8"Rayquaza",
u8"Jirachi",
u8"Deoxys",
u8"Turtwig",
u8"Grotle",
u8"Torterra",
u8"Chimchar",
u8"Monferno",
u8"Infernape",
u8"Piplup",
u8"Prinplup",
u8"Empoleon",
u8"Starly",
u8"Staravia",
u8"Staraptor",
u8"Bidoof",
u8"Bibarel",
u8"Kricketot",
u8"Kricketune",
u8"Shinx",
u8"Luxio",
u8"Luxray",
u8"Budew",
u8"Roserade",
u8"Cranidos",
u8"Rampardos",
u8"Shieldon",
u8"Bastiodon",
u8"Burmy",
u8"Wormadam",
u8"Mothim",
u8"Combee",
u8"Vespiquen",
u8"Pachirisu",
u8"Buizel",
u8"Floatzel",
u8"Cherubi",
u8"Cherrim",
u8"Shellos",
u8"Gastrodon",
u8"Ambipom",
u8"Drifloon",
u8"Drifblim",
u8"Buneary",
u8"Lopunny",
u8"Mismagius",
u8"Honchkrow",
u8"Glameow",
u8"Purugly",
u8"Chingling",
u8"Stunky",
u8"Skuntank",
u8"Bronzor",
u8"Bronzong",
u8"Bonsly",
u8"Mime Jr.",
u8"Happiny",
u8"Chatot",
u8"Spiritomb",
u8"Gible",
u8"Gabite",
u8"Garchomp",
u8"Munchlax",
u8"Riolu",
u8"Lucario",
u8"Hippopotas",
u8"Hippowdon",
u8"Skorupi",
u8"Drapion",
u8"Croagunk",
u8"Toxicroak",
u8"Carnivine",
u8"Finneon",
u8"Lumineon",
u8"Mantyke",
u8"Snover",
u8"Abomasnow",
u8"Weavile",
u8"Magnezone",
u8"Lickilicky",
u8"Rhyperior",
u8"Tangrowth",
u8"Electivire",
u8"Magmortar",
u8"Togekiss",
u8"Yanmega",
u8"Leafeon",
u8"Glaceon",
u8"Gliscor",
u8"Mamoswine",
u8"Porygon-Z",
u8"Gallade",
u8"Probopass",
u8"Dusknoir",
u8"Froslass",
u8"Rotom",
u8"Uxie",
u8"Mesprit",
u8"Azelf",
u8"Dialga",
u8"Palkia",
u8"Heatran",
u8"Regigigas",
u8"Giratina",
u8"Cresselia",
u8"Phione",
u8"Manaphy",
u8"Darkrai",
u8"Shaymin",
u8"Arceus",
u8"Victini",
u8"Snivy",
u8"Servine",
u8"Serperior",
u8"Tepig",
u8"Pignite",
u8"Emboar",
u8"Oshawott",
u8"Dewott",
u8"Samurott",
u8"Patrat",
u8"Watchog",
u8"Lillipup",
u8"Herdier",
u8"Stoutland",
u8"Purrloin",
u8"Liepard",
u8"Pansage",
u8"Simisage",
u8"Pansear",
u8"Simisear",
u8"Panpour",
u8"Simipour",
u8"Munna",
u8"Musharna",
u8"Pidove",
u8"Tranquill",
u8"Unfezant",
u8"Blitzle",
u8"Zebstrika",
u8"Roggenrola",
u8"Boldore",
u8"Gigalith",
u8"Woobat",
u8"Swoobat",
u8"Drilbur",
u8"Excadrill",
u8"Audino",
u8"Timburr",
u8"Gurdurr",
u8"Conkeldurr",
u8"Tympole",
u8"Palpitoad",
u8"Seismitoad",
u8"Throh",
u8"Sawk",
u8"Sewaddle",
u8"Swadloon",
u8"Leavanny",
u8"Venipede",
u8"Whirlipede",
u8"Scolipede",
u8"Cottonee",
u8"Whimsicott",
u8"Petilil",
u8"Lilligant",
u8"Basculin",
u8"Sandile",
u8"Krokorok",
u8"Krookodile",
u8"Darumaka",
u8"Darmanitan",
u8"Maractus",
u8"Dwebble",
u8"Crustle",
u8"Scraggy",
u8"Scrafty",
u8"Sigilyph",
u8"Yamask",
u8"Cofagrigus",
u8"Tirtouga",
u8"Carracosta",
u8"Archen",
u8"Archeops",
u8"Trubbish",
u8"Garbodor",
u8"Zorua",
u8"Zoroark",
u8"Minccino",
u8"Cinccino",
u8"Gothita",
u8"Gothorita",
u8"Gothitelle",
u8"Solosis",
u8"Duosion",
u8"Reuniclus",
u8"Ducklett",
u8"Swanna",
u8"Vanillite",
u8"Vanillish",
u8"Vanilluxe",
u8"Deerling",
u8"Sawsbuck",
u8"Emolga",
u8"Karrablast",
u8"Escavalier",
u8"Foongus",
u8"Amoonguss",
u8"Frillish",
u8"Jellicent",
u8"Alomomola",
u8"Joltik",
u8"Galvantula",
u8"Ferroseed",
u8"Ferrothorn",
u8"Klink",
u8"Klang",
u8"Klinklang",
u8"Tynamo",
u8"Eelektrik",
u8"Eelektross",
u8"Elgyem",
u8"Beheeyem",
u8"Litwick",
u8"Lampent",
u8"Chandelure",
u8"Axew",
u8"Fraxure",
u8"Haxorus",
u8"Cubchoo",
u8"Beartic",
u8"Cryogonal",
u8"Shelmet",
u8"Accelgor",
u8"Stunfisk",
u8"Mienfoo",
u8"Mienshao",
u8"Druddigon",
u8"Golett",
u8"Golurk",
u8"Pawniard",
u8"Bisharp",
u8"Bouffalant",
u8"Rufflet",
u8"Braviary",
u8"Vullaby",
u8"Mandibuzz",
u8"Heatmor",
u8"Durant",
u8"Deino",
u8"Zweilous",
u8"Hydreigon",
u8"Larvesta",
u8"Volcarona",
u8"Cobalion",
u8"Terrakion",
u8"Virizion",
u8"Tornadus",
u8"Thundurus",
u8"Reshiram",
u8"Zekrom",
u8"Landorus",
u8"Kyurem",
u8"Keldeo",
u8"Meloetta",
u8"Genesect",
u8"Chespin",
u8"Quilladin",
u8"Chesnaught",
u8"Fennekin",
u8"Braixen",
u8"Delphox",
u8"Froakie",
u8"Frogadier",
u8"Greninja",
u8"Bunnelby",
u8"Diggersby",
u8"Fletchling",
u8"Fletchinder",
u8"Talonflame",
u8"Scatterbug",
u8"Spewpa",
u8"Vivillon",
u8"Litleo",
u8"Pyroar",
u8"Flabébé",
u8"Floette",
u8"Florges",
u8"Skiddo",
u8"Gogoat",
u8"Pancham",
u8"Pangoro",
u8"Furfrou",
u8"Espurr",
u8"Meowstic",
u8"Honedge",
u8"Doublade",
u8"Aegislash",
u8"Spritzee",
u8"Aromatisse",
u8"Swirlix",
u8"Slurpuff",
u8"Inkay",
u8"Malamar",
u8"Binacle",
u8"Barbaracle",
u8"Skrelp",
u8"Dragalge",
u8"Clauncher",
u8"Clawitzer",
u8"Helioptile",
u8"Heliolisk",
u8"Tyrunt",
u8"Tyrantrum",
u8"Amaura",
u8"Aurorus",
u8"Sylveon",
u8"Hawlucha",
u8"Dedenne",
u8"Carbink",
u8"Goomy",
u8"Sliggoo",
u8"Goodra",
u8"Klefki",
u8"Phantump",
u8"Trevenant",
u8"Pumpkaboo",
u8"Gourgeist",
u8"Bergmite",
u8"Avalugg",
u8"Noibat",
u8"Noivern",
u8"Xerneas",
u8"Yveltal",
u8"Zygarde",
u8"Diancie",
};
unsigned PokemonSpecies::expToLevel(unsigned level) const {
switch (growthRate()) {
case PokemonSpecies::LEVEL_FAST:
return 4 * level * level * level / 5;
case PokemonSpecies::LEVEL_MEDIUM_FAST:
return level * level * level;
case PokemonSpecies::LEVEL_MEDIUM_SLOW:
return 6 * level * level * level / 5 - 15 * level * level + 100 * level - 140;
case PokemonSpecies::LEVEL_SLOW:
return 5 * level * level * level / 4;
case PokemonSpecies::LEVEL_ERRATIC:
if (level <= 50) {
return (level * level * level * (100 - level)) / 50;
}
if (level <= 68) {
return (level * level * level * (150 - level)) / 100;
}
if (level <= 98) {
return (level * level * level * (1911 - 10 * level) / 3) / 500;
}
return (level * level * level * (160 - level)) / 100;
case PokemonSpecies::LEVEL_FLUCTUATING:
if (level <= 15) {
return level * level * level * ((level + 1) / 3 + 24) / 50;
}
if (level <= 36) {
return (level * level * level * (level + 14)) / 50;
}
return level * level * level * (level / 2 + 32) / 50;
break;
}
return 0;
}
const MultipaletteSprite* PokemonSpecies::frontSprite() const {
return m_frontSprite.get();
}
void PokemonSpecies::setFrontSprite(MultipaletteSprite* sprite) {
m_frontSprite = std::unique_ptr<MultipaletteSprite>(sprite);
}
const MultipaletteSprite* PokemonSpecies::backSprite() const {
return m_backSprite.get();
}
void PokemonSpecies::setBackSprite(MultipaletteSprite* sprite) {
m_backSprite = std::unique_ptr<MultipaletteSprite>(sprite);
}
const MultipaletteSprite* PokemonSpecies::menuSprite() const {
return m_menuSprite.get();
}
void PokemonSpecies::setMenuSprite(MultipaletteSprite* sprite) {
m_menuSprite = std::unique_ptr<MultipaletteSprite>(sprite);
}
const char* PokemonSpecies::readable() const {
return speciesNames[id()];
}
| 15.590851 | 80 | 0.657131 | Archaemic |
4ceccc2eefba8128f4b6d69b4376328af3ceafd9 | 1,972 | cpp | C++ | src/client/client_renderer_object_factory.cpp | jdmclark/gorc | a03d6a38ab7684860c418dd3d2e77cbe6a6d9fc8 | [
"Apache-2.0"
] | 97 | 2015-02-24T05:09:24.000Z | 2022-01-23T12:08:22.000Z | src/client/client_renderer_object_factory.cpp | annnoo/gorc | 1889b4de6380c30af6c58a8af60ecd9c816db91d | [
"Apache-2.0"
] | 8 | 2015-03-27T23:03:23.000Z | 2020-12-21T02:34:33.000Z | src/client/client_renderer_object_factory.cpp | annnoo/gorc | 1889b4de6380c30af6c58a8af60ecd9c816db91d | [
"Apache-2.0"
] | 10 | 2016-03-24T14:32:50.000Z | 2021-11-13T02:38:53.000Z | #include "client_renderer_object_factory.hpp"
gorc::client_renderer_object_factory::~client_renderer_object_factory()
{
for(auto &material_image : material_images) {
glDeleteTextures(1, &material_image.second);
}
}
void gorc::client_renderer_object_factory::set_material_image(material_id id,
int cel,
int channel,
grid<color_rgba8> const &img)
{
GLuint texture_id;
glGenTextures(1, &texture_id);
glBindTexture(GL_TEXTURE_2D, texture_id);
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
GLfloat largest_supported_anisotropy;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &largest_supported_anisotropy);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, largest_supported_anisotropy);
glTexImage2D(GL_TEXTURE_2D,
/* level */ 0,
GL_RGBA,
static_cast<GLsizei>(get<0>(img.size)),
static_cast<GLsizei>(get<1>(img.size)),
/* border */ 0,
GL_RGBA,
GL_UNSIGNED_BYTE,
reinterpret_cast<char const *>(img.data()));
material_images.emplace(std::make_tuple(id, cel, channel), texture_id);
}
GLuint gorc::client_renderer_object_factory::get_material_image(material_id id,
int cel,
int channel)
{
return material_images.at(std::make_tuple(id, cel, channel));
}
| 40.244898 | 96 | 0.605477 | jdmclark |
4ced8c44139dfaf1017ec68c7e713006ac02bb14 | 1,196 | hpp | C++ | include/utility/trait/type/categories/is_scalar.hpp | SakuraLife/utility | b9bf26198917b6dc415520f74eb3eebf8aa8195e | [
"Unlicense"
] | 2 | 2017-12-10T10:59:48.000Z | 2017-12-13T04:11:14.000Z | include/utility/trait/type/categories/is_scalar.hpp | SakuraLife/utility | b9bf26198917b6dc415520f74eb3eebf8aa8195e | [
"Unlicense"
] | null | null | null | include/utility/trait/type/categories/is_scalar.hpp | SakuraLife/utility | b9bf26198917b6dc415520f74eb3eebf8aa8195e | [
"Unlicense"
] | null | null | null |
#ifndef __UTILITY_TRAIT_TYPE_CATEGORIES_IS_SCALAR__
#define __UTILITY_TRAIT_TYPE_CATEGORIES_IS_SCALAR__
#include<utility/trait/trait_helper.hpp>
#include<utility/trait/type/categories/is_arithmetic.hpp>
#include<utility/trait/type/categories/is_member_pointer.hpp>
#include<utility/trait/type/categories/is_pointer.hpp>
#include<utility/trait/type/categories/is_null_pointer.hpp>
#include<utility/trait/type/categories/is_enum.hpp>
namespace utility
{
namespace trait
{
namespace type
{
namespace categories
{
// is_scalar
template<typename _T>
struct is_scalar :
public trait::integral_constant<bool,
is_arithmetic<_T>::value ||
is_member_pointer<_T>::value ||
is_pointer<_T>::value ||
is_null_pointer<_T>::value ||
is_enum<_T>::value>
{ };
template<>
struct is_scalar<nullptr_t> :
public trait::true_type
{ };
#if !defined(__UTILITY_NO_CPP14__)
template<typename _T>
constexpr bool is_scalar_v = is_scalar<_T>::value;
#endif
}
}
}
}
#endif // __UTILITY_TRAIT_TYPE_CATEGORIES_IS_SCALAR__
| 26 | 61 | 0.66806 | SakuraLife |
4cedfb360743c3a3bae59a44468fe070b397421f | 52 | hpp | C++ | api/meta/ToSave.hpp | phisko/kengine_editor | cd11f067b1339c418acf8e568e73eb00c9340722 | [
"MIT"
] | null | null | null | api/meta/ToSave.hpp | phisko/kengine_editor | cd11f067b1339c418acf8e568e73eb00c9340722 | [
"MIT"
] | null | null | null | api/meta/ToSave.hpp | phisko/kengine_editor | cd11f067b1339c418acf8e568e73eb00c9340722 | [
"MIT"
] | null | null | null | #pragma once
namespace meta {
struct ToSave {};
}
| 8.666667 | 18 | 0.673077 | phisko |
4cf2c3d730586c93bc776e937f5586fcdd92ed13 | 1,664 | cpp | C++ | SceneLoadOverlay.cpp | Sgw32/R3E | 8a55dd137d9e102cf4c9c2fee3d89901bdefa3cd | [
"MIT"
] | 7 | 2017-11-27T15:15:08.000Z | 2021-03-29T16:53:22.000Z | SceneLoadOverlay.cpp | Sgw32/R3E | 8a55dd137d9e102cf4c9c2fee3d89901bdefa3cd | [
"MIT"
] | null | null | null | SceneLoadOverlay.cpp | Sgw32/R3E | 8a55dd137d9e102cf4c9c2fee3d89901bdefa3cd | [
"MIT"
] | 4 | 2017-11-28T02:53:19.000Z | 2021-01-29T10:37:52.000Z | #include "SceneLoadOverlay.h"
template<> SceneLoadOverlay *Singleton<SceneLoadOverlay>::ms_Singleton=0;
SceneLoadOverlay::SceneLoadOverlay()
{
}
SceneLoadOverlay::~SceneLoadOverlay()
{
}
void SceneLoadOverlay::init(Root* mRoot)
{
srand(time(NULL));
cf.load("run3/game/loadingscrs/loadingscrs.cfg");
ConfigFile::SettingsMultiMap *settings = cf.getSectionIterator().getNext();
ConfigFile::SettingsMultiMap::iterator b;
settings = cf.getSectionIterator().getNext();
String curLab;
overlay = OverlayManager::getSingleton().getByName("Run3/TD01");
lCont = overlay->getChild("Run3/TD01Panel");
for (b = settings->begin(); b != settings->end(); ++b)
{
curLab = b->first;
Add(cf.getSetting(curLab));
}
root=mRoot;
}
void SceneLoadOverlay::Add(String overlay)
{
// overlays.push_back(OverlayManager::getSingleton().getByName(overlay));
overlays.push_back(overlay);
}
void SceneLoadOverlay::Show(String over)
{
LogManager::getSingleton().logMessage("11");
lCont->setMaterialName(over);
LogManager::getSingleton().logMessage("12");
overlay->show();
LogManager::getSingleton().logMessage("13");
root->renderOneFrame();
LogManager::getSingleton().logMessage("14");
}
void SceneLoadOverlay::Show()
{
overlay->show();
root->renderOneFrame();
}
void SceneLoadOverlay::Show(int iter)
{
lCont->setMaterialName(overlays.at(iter));
overlay->show();
root->renderOneFrame();
}
void SceneLoadOverlay::Hide(String over)
{
overlay->hide();
}
void SceneLoadOverlay::Hide_all()
{
overlay->hide();
}
void SceneLoadOverlay::SetRandom()
{
random_iter = rand() % overlays.size() + 1;
Hide_all();
Show(random_iter);
}
| 20.8 | 76 | 0.71274 | Sgw32 |
4cf354c4fca5d3604b6979f6013bcf136d492de2 | 1,236 | cpp | C++ | qikkDB/GpuSqlParser/MemoryStream.cpp | veselyja/qikkdb-community | 680f62632ba85e468beee672624b80a61ed40f55 | [
"Apache-2.0"
] | 15 | 2020-06-30T13:43:42.000Z | 2022-02-02T12:52:33.000Z | qikkDB/GpuSqlParser/MemoryStream.cpp | veselyja/qikkdb-community | 680f62632ba85e468beee672624b80a61ed40f55 | [
"Apache-2.0"
] | 1 | 2020-11-28T22:29:35.000Z | 2020-12-22T10:28:25.000Z | qikkDB/GpuSqlParser/MemoryStream.cpp | qikkDB/qikkdb | 4ee657c7d2bfccd460d2f0d2c84a0bbe72d9a80a | [
"Apache-2.0"
] | 1 | 2020-06-30T12:41:37.000Z | 2020-06-30T12:41:37.000Z | //
// Created by Martin Staňo on 2019-01-15.
//
#include "MemoryStream.h"
#include "../PointFactory.h"
#include "../Types/Point.pb.h"
// template<>
// void MemoryStream::insert(const char *value)
//{
// int len = static_cast<int>(strlen(value));
// insert<int>(len);
// std::copy(value, value + len * sizeof(char), buffer.end());
//}
template <>
void MemoryStream::Insert(const std::string& value)
{
int len = static_cast<int>(value.length());
Insert<int32_t>(len);
std::copy(value.begin(), value.end(), std::back_inserter(buffer_));
}
template <>
std::string MemoryStream::Read()
{
int32_t len = Read<int32_t>();
std::string str(buffer_.begin() + readOffset_, buffer_.begin() + readOffset_ + len);
readOffset_ += len;
return str;
}
template <>
NativeGeoPoint MemoryStream::Read()
{
std::string pointWkt = Read<std::string>();
QikkDB::Types::Point pointConst = PointFactory::FromWkt(pointWkt);
return {pointConst.geopoint().latitude(), pointConst.geopoint().longitude()};
}
MemoryStream::MemoryStream()
{
readOffset_ = 0;
buffer_.reserve(8192);
}
void MemoryStream::Reset()
{
readOffset_ = 0;
}
void MemoryStream::Clear()
{
buffer_.clear();
readOffset_ = 0;
} | 21.684211 | 88 | 0.65534 | veselyja |
4cf42240eab6c6d32cc17232b0c0303611077499 | 5,235 | cpp | C++ | SDK/Extras/Rayshade/Sources/Rayshade/LibLight/spot.cpp | h-haris/Quesa | a438ab824291ce6936a88dfae4fd0482dcba1247 | [
"BSD-3-Clause"
] | 24 | 2019-10-28T07:01:48.000Z | 2022-03-04T16:10:39.000Z | SDK/Extras/Rayshade/Sources/Rayshade/LibLight/spot.cpp | h-haris/Quesa | a438ab824291ce6936a88dfae4fd0482dcba1247 | [
"BSD-3-Clause"
] | 8 | 2020-04-22T19:42:45.000Z | 2021-04-30T16:28:32.000Z | SDK/Extras/Rayshade/Sources/Rayshade/LibLight/spot.cpp | h-haris/Quesa | a438ab824291ce6936a88dfae4fd0482dcba1247 | [
"BSD-3-Clause"
] | 6 | 2019-09-22T14:44:15.000Z | 2021-04-01T20:04:29.000Z | /*
* spot.c
*
* Copyright (C) 1989, 1991, Craig E. Kolb
* All rights reserved.
*
* This software may be freely copied, modified, and redistributed
* provided that this copyright notice is preserved on all copies.
*
* You may not distribute this software, in whole or in part, as part of
* any commercial product without the express consent of the authors.
*
* There is no warranty or other guarantee of fitness of this software
* for any purpose. It is provided solely "as is".
*
* $Id: spot.cpp,v 1.2 2008-12-21 02:04:26 jwwalker Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.1 2002/12/18 18:36:42 pepe
* First upload
*
* Revision 4.0 91/07/17 14:35:42 kolb
* Initial version.
*
*/
#include "light.h"
#include "spot.h"
static LightMethods *iSpotMethods = NULL;
static int SpotIntens(LightRef lr, Color *lcolor,ShadowCache *cache,
Ray *ray, Float dist,int noshadow, Color *color);
static void SpotDirection(LightRef lr, Vector *pos,Vector* dir,Float* dist);
static Float SpotAtten(Spotlight *lp, Vector *dir);
Spotlight *
SpotCreate(
Vector *from,
Vector *dir,
Float hotAngle,
Float outerAngle ,
int attenuation ,
int fallOff )
{
Spotlight *spot;
spot = (Spotlight *)share_malloc(sizeof(Spotlight));
spot->pos = *from;
spot->dir.x = dir->x ;
spot->dir.y = dir->y ;
spot->dir.z = dir->z ;
if (VecNormalize(&spot->dir) == 0. || hotAngle > outerAngle ) {
RLerror(RL_ABORT,"Invalid spotlight specification.\n");
return (Spotlight *)NULL;
}
spot->hotAngle = hotAngle ;
spot->outerAngle = outerAngle ;
spot->cosHotAngle = cos ( hotAngle ) ;
spot->cosOuterAngle = cos ( outerAngle ) ;
spot->attenuation = attenuation ;
spot->fallOff = fallOff ;
return spot;
}
LightMethods *
SpotMethods(void)
{
if (iSpotMethods == (LightMethods *)NULL) {
iSpotMethods = LightMethodsCreate();
iSpotMethods->intens = SpotIntens;
iSpotMethods->dir = SpotDirection;
}
return iSpotMethods;
}
/*
* Calculate intensity ('color') of light reaching 'pos' from light 'lp'.
* The spotlight is 'dist' units from 'pos' along 'dir'.
*
* Returns TRUE if non-zero illumination, FALSE otherwise.
*/
int
SpotIntens(
LightRef lr,
Color *lcolor,
ShadowCache *cache,
Ray *ray,
Float dist,
int noshadow,
Color *color)
{
Spotlight *spot = (Spotlight*)lr;
Float atten;
extern Float SpotAtten(Spotlight*,Vector*);
/*
* Compute spotlight color
*/
atten = SpotAtten(spot, &ray->dir);
/*
* If outside of spot, return FALSE.
*/
if (atten == 0.)
return FALSE;
if (Shadowed(color, lcolor, cache, ray, dist, noshadow))
return FALSE;
ColorScale(atten, *color, color);
return TRUE;
}
#define kQ3PiOver2 ((Float) (3.1415926535898 / 2.0))
static const float eMinus1 = exp ( 1.0f ) - 1.0f ;
/*
* Compute intensity of spotlight along 'dir'.
*/
static Float
SpotAtten(
Spotlight *lp,
Vector *dir)
{
Float costheta, atten;
costheta = -dotp(dir, &lp->dir);
/*
* Behind spotlight.
*/
if (costheta <= 0.)
return 0.;
if ( costheta < lp->cosOuterAngle )
return 0.0 ;
atten = costheta ;
if (lp->cosHotAngle > 0.) // What is this all about ?
{
Float fallOffMultiplier = 1.0 ;
if ( lp->fallOff == 1 /*kQ3FallOffTypeLinear*/ )
{
if ( costheta < lp->cosHotAngle )
{
Float angle = acos ( costheta ) ;
fallOffMultiplier = ( lp->outerAngle - angle ) /
( lp->outerAngle - lp->hotAngle ) ;
}
}
else
if ( lp->fallOff == 2/*kQ3FallOffTypeExponential*/ )
{
if ( costheta < lp->cosHotAngle )
{
Float angle = acos ( costheta ) ;
fallOffMultiplier = ( exp ( ( lp->outerAngle - angle ) /
( lp->outerAngle - lp->hotAngle ) ) - 1 ) / eMinus1 ;
}
}
else
if ( lp->fallOff == 3/*kQ3FallOffTypeCosine*/ )
{
if ( costheta < lp->cosHotAngle )
{
Float angle = acos ( costheta ) ;
fallOffMultiplier = cos ( ( angle - lp->hotAngle ) * kQ3PiOver2 /
( lp->outerAngle - lp->hotAngle ) ) ;
}
}
/*
This may be required some time but presently neither the attenuation
nor the world pixel position are available. Maybe it should go
somewhere else in the calculations
if ( lp->attenuation != kQ3AttenuationTypeNone )
{
switch ( lp->attenuation )
{
case kQ3AttenuationTypeInverseDistance :
{
fallOffMultiplier *= 1.0f / Distance ( pixelWorldPos - lp-
pos ) ;
break ;
}
case kQ3AttenuationTypeInverseDistanceSquared :
{
fallOffMultiplier *= 1.0f / DistanceSquared ( pixelWorldPos -
lp->pos ) ;
break ;
}
}
}
*/
atten *= fallOffMultiplier ;
}
return atten;
}
static void
SpotDirection(LightRef lr, Vector *pos,Vector* dir,Float* dist)
{
Spotlight *lp = (Spotlight*)lr;
/*
* Calculate dir from position to center of light source.
*/
VecSub(lp->pos, *pos, dir);
*dist = VecNormalize(dir);
}
static void
SpotMethodRegister(UserMethodType meth)
{
if (iSpotMethods)
iSpotMethods->user = meth;
}
| 24.013761 | 76 | 0.61872 | h-haris |
e07e1388af1db09fa2aa5de5d94f8acd4298b0ac | 1,390 | cpp | C++ | DynamicProgramming/coinchange2.cpp | thisisnitish/cp-dsa | 6a00f1d60712115f70c346cee238ad1730e6c39e | [
"MIT"
] | 4 | 2020-12-29T09:27:10.000Z | 2022-02-12T14:20:23.000Z | DynamicProgramming/coinchange2.cpp | thisisnitish/cp-dsa | 6a00f1d60712115f70c346cee238ad1730e6c39e | [
"MIT"
] | 1 | 2021-11-27T06:15:28.000Z | 2021-11-27T06:15:28.000Z | DynamicProgramming/coinchange2.cpp | thisisnitish/cp-dsa | 6a00f1d60712115f70c346cee238ad1730e6c39e | [
"MIT"
] | 1 | 2021-11-17T21:42:57.000Z | 2021-11-17T21:42:57.000Z | /*
Leetcode Question 518. Coin Change 2
https://leetcode.com/problems/coin-change-2/
*/
class Solution
{
public:
/*the basic idea is that it is based on the unbounded knapsack problem
so before doing this understand the concept of unbounded knapsack problem
then only do this preblem. Everything is same, only the thing we have to
change is to add the choices because we have been asked for find the number
of combinations. We are using Bottom Up approach
Time: O(n*amount), Space: O(n*amount)*/
int change(int amount, vector<int> &coins)
{
int n = coins.size();
vector<vector<int> > dp(n + 1, vector<int>(amount + 1));
//initializing
for (int i = 0; i < n + 1; i++)
{
for (int j = 0; j < amount + 1; j++)
{
if (i == 0)
dp[i][j] = 0;
if (j == 0)
dp[i][j] = 1;
}
}
//solving the small problems to find the bigger one
for (int i = 1; i < n + 1; i++)
{
for (int j = 1; j < amount + 1; j++)
{
if (coins[i - 1] <= j)
dp[i][j] = dp[i][j - coins[i - 1]] + dp[i - 1][j]; //adding the choices
else
dp[i][j] = dp[i - 1][j];
}
}
return dp[n][amount];
}
}; | 30.888889 | 93 | 0.481295 | thisisnitish |
e080ed4756bc88f9ccf7b56d52a96dfc2d4bf955 | 2,873 | hpp | C++ | src/routines/routines.hpp | vbkaisetsu/CLBlast | 441373c8fd1442cc4c024e59e7778b4811eb210c | [
"Apache-2.0"
] | null | null | null | src/routines/routines.hpp | vbkaisetsu/CLBlast | 441373c8fd1442cc4c024e59e7778b4811eb210c | [
"Apache-2.0"
] | null | null | null | src/routines/routines.hpp | vbkaisetsu/CLBlast | 441373c8fd1442cc4c024e59e7778b4811eb210c | [
"Apache-2.0"
] | null | null | null |
// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
// Cedric Nugteren <www.cedricnugteren.nl>
//
// This file contains all the includes of all the routines in CLBlast.
//
// =================================================================================================
#ifndef CLBLAST_ROUTINES_ROUTINES_H_
#define CLBLAST_ROUTINES_ROUTINES_H_
// BLAS level-1 includes
#include "routines/level1/xswap.hpp"
#include "routines/level1/xscal.hpp"
#include "routines/level1/xcopy.hpp"
#include "routines/level1/xaxpy.hpp"
#include "routines/level1/xdot.hpp"
#include "routines/level1/xdotu.hpp"
#include "routines/level1/xdotc.hpp"
#include "routines/level1/xnrm2.hpp"
#include "routines/level1/xasum.hpp"
#include "routines/level1/xsum.hpp" // non-BLAS routine
#include "routines/level1/xamax.hpp"
#include "routines/level1/xamin.hpp" // non-BLAS routine
#include "routines/level1/xmax.hpp" // non-BLAS routine
#include "routines/level1/xmin.hpp" // non-BLAS routine
// BLAS level-2 includes
#include "routines/level2/xgemv.hpp"
#include "routines/level2/xgbmv.hpp"
#include "routines/level2/xhemv.hpp"
#include "routines/level2/xhbmv.hpp"
#include "routines/level2/xhpmv.hpp"
#include "routines/level2/xsymv.hpp"
#include "routines/level2/xsbmv.hpp"
#include "routines/level2/xspmv.hpp"
#include "routines/level2/xtrmv.hpp"
#include "routines/level2/xtbmv.hpp"
#include "routines/level2/xtpmv.hpp"
#include "routines/level2/xtrsv.hpp"
#include "routines/level2/xger.hpp"
#include "routines/level2/xgeru.hpp"
#include "routines/level2/xgerc.hpp"
#include "routines/level2/xher.hpp"
#include "routines/level2/xhpr.hpp"
#include "routines/level2/xher2.hpp"
#include "routines/level2/xhpr2.hpp"
#include "routines/level2/xsyr.hpp"
#include "routines/level2/xspr.hpp"
#include "routines/level2/xsyr2.hpp"
#include "routines/level2/xspr2.hpp"
// BLAS level-3 includes
#include "routines/level3/xgemm.hpp"
#include "routines/level3/xsymm.hpp"
#include "routines/level3/xhemm.hpp"
#include "routines/level3/xsyrk.hpp"
#include "routines/level3/xherk.hpp"
#include "routines/level3/xsyr2k.hpp"
#include "routines/level3/xher2k.hpp"
#include "routines/level3/xtrmm.hpp"
#include "routines/level3/xtrsm.hpp"
// Level-x includes (non-BLAS)
#include "routines/levelx/xhad.hpp"
#include "routines/levelx/xomatcopy.hpp"
#include "routines/levelx/xim2col.hpp"
#include "routines/levelx/xconvgemm.hpp"
#include "routines/levelx/xaxpybatched.hpp"
#include "routines/levelx/xgemmbatched.hpp"
#include "routines/levelx/xgemmstridedbatched.hpp"
// CLBLAST_ROUTINES_ROUTINES_H_
#endif
| 35.9125 | 100 | 0.721197 | vbkaisetsu |
e084550098c2c017471d4f636cf2d7ae7c1f8038 | 13,788 | hpp | C++ | CmnCS/module/computationalgeometry2/inc/computationalgeometry2/ConvexHull2.hpp | Khoronus/CmnUniverse | 9cf9b4297f2fcb49330126aa1047b422144045e1 | [
"MIT"
] | null | null | null | CmnCS/module/computationalgeometry2/inc/computationalgeometry2/ConvexHull2.hpp | Khoronus/CmnUniverse | 9cf9b4297f2fcb49330126aa1047b422144045e1 | [
"MIT"
] | null | null | null | CmnCS/module/computationalgeometry2/inc/computationalgeometry2/ConvexHull2.hpp | Khoronus/CmnUniverse | 9cf9b4297f2fcb49330126aa1047b422144045e1 | [
"MIT"
] | null | null | null | // Geometric Tools LLC, Redmond WA 98052
// Copyright (c) 1998-2015
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 1.0.3 (2014/12/13)
#ifndef CMNCS_COMPUTATIONALGEOMETRY2_CONVEXHULL2_HPP__
#define CMNCS_COMPUTATIONALGEOMETRY2_CONVEXHULL2_HPP__
// Compute the convex hull of 2D points using a divide-and-conquer algorithm.
// This is an O(N log N) algorithm for N input points. The only way to ensure
// a correct result for the input vertices (assumed to be exact) is to choose
// ComputeType for exact rational arithmetic. You may use BSNumber. No
// divisions are performed in this computation, so you do not have to use
// BSRational.
//
// Choice of N for Real of type BSNumber or BSRational with integer storage
// UIntegerFP32<N>. The numerical computations are encapsulated in
// PrimalQuery3<Real>::ToPlane. (We recommend using only BSNumber, because
// no divisions are performed in the computations.)
//
// input type | compute type | N
// -----------+--------------+------
// float | BSNumber | 27
// double | BSNumber | 197
// float | BSRational | 2882
// double | BSRational | 21688
#include "GteLine.h"
#include "GtePrimalQuery2.h"
#include "GteLogger.h"
#include <algorithm>
#include <vector>
namespace CmnCS
{
namespace computationalgeometry2
{
template <typename InputType, typename ComputeType>
class ConvexHull2
{
public:
// The class is a functor to support computing the convex hull of multiple
// data sets using the same class object.
ConvexHull2();
// The input is the array of points whose convex hull is required. The
// epsilon value is used to determine the intrinsic dimensionality of the
// vertices (d = 0, 1, or 2). When epsilon is positive, the determination
// is fuzzy--points approximately the same point, approximately on a
// line, or planar. The return value is 'true' if and only if the hull
// construction is successful.
bool operator()(int numPoints, Vector2<InputType> const* points,
InputType epsilon);
// Dimensional information. If GetDimension() returns 1, the points lie
// on a line P+t*D (fuzzy comparison when epsilon > 0). You can sort
// these if you need a polyline output by projecting onto the line each
// vertex X = P+t*D, where t = Dot(D,X-P).
inline InputType GetEpsilon() const;
inline int GetDimension() const;
inline Line2<InputType> const& GetLine() const;
// Member access.
inline int GetNumPoints() const;
inline int GetNumUniquePoints() const;
inline Vector2<InputType> const* GetPoints() const;
inline PrimalQuery2<ComputeType> const& GetQuery() const;
// The convex hull is a convex polygon whose vertices are listed in
// counterclockwise order.
inline std::vector<int> const& GetHull() const;
private:
// Support for divide-and-conquer.
void GetHull(int& i0, int& i1);
void Merge(int j0, int j1, int j2, int j3, int& i0, int& i1);
void GetTangent(int j0, int j1, int j2, int j3, int& i0, int& i1);
// The epsilon value is used for fuzzy determination of intrinsic
// dimensionality. If the dimension is 0 or 1, the constructor returns
// early. The caller is responsible for retrieving the dimension and
// taking an alternate path should the dimension be smaller than 2. If
// the dimension is 0, the caller may as well treat all points[] as a
// single point, say, points[0]. If the dimension is 1, the caller can
// query for the approximating line and project points[] onto it for
// further processing.
InputType mEpsilon;
int mDimension;
Line2<InputType> mLine;
// The array of points used for geometric queries. If you want to be
// certain of a correct result, choose ComputeType to be BSNumber.
std::vector<Vector2<ComputeType>> mComputePoints;
PrimalQuery2<ComputeType> mQuery;
int mNumPoints;
int mNumUniquePoints;
Vector2<InputType> const* mPoints;
std::vector<int> mMerged, mHull;
};
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType>
ConvexHull2<InputType, ComputeType>::ConvexHull2()
:
mEpsilon((InputType)0),
mDimension(0),
mLine(Vector2<InputType>::Zero(), Vector2<InputType>::Zero()),
mNumPoints(0),
mNumUniquePoints(0),
mPoints(nullptr)
{
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType>
bool ConvexHull2<InputType, ComputeType>::operator()(int numPoints,
Vector2<InputType> const* points, InputType epsilon)
{
mEpsilon = std::max(epsilon, (InputType)0);
mDimension = 0;
mLine.origin = Vector2<InputType>::Zero();
mLine.direction = Vector2<InputType>::Zero();
mNumPoints = numPoints;
mNumUniquePoints = 0;
mPoints = points;
mMerged.clear();
mHull.clear();
int i, j;
if (mNumPoints < 3)
{
// ConvexHull2 should be called with at least three points.
return false;
}
IntrinsicsVector2<InputType> info(mNumPoints, mPoints, mEpsilon);
if (info.dimension == 0)
{
// mDimension is 0
return false;
}
if (info.dimension == 1)
{
// The set is (nearly) collinear.
mDimension = 1;
mLine = Line2<InputType>(info.origin, info.direction[0]);
return false;
}
mDimension = 2;
// Compute the points for the queries.
mComputePoints.resize(mNumPoints);
mQuery.Set(mNumPoints, &mComputePoints[0]);
for (i = 0; i < mNumPoints; ++i)
{
for (j = 0; j < 2; ++j)
{
mComputePoints[i][j] = points[i][j];
}
}
// Sort the points.
mHull.resize(mNumPoints);
for (int i = 0; i < mNumPoints; ++i)
{
mHull[i] = i;
}
std::sort(mHull.begin(), mHull.end(),
[points](int i0, int i1)
{
if (points[i0][0] < points[i1][0]) { return true; }
if (points[i0][0] > points[i1][0]) { return false; }
return points[i0][1] < points[i1][1];
}
);
// Remove duplicates.
auto newEnd = std::unique(mHull.begin(), mHull.end(),
[points](int i0, int i1)
{
return points[i0] == points[i1];
}
);
mHull.erase(newEnd, mHull.end());
mNumUniquePoints = static_cast<int>(mHull.size());
// Use a divide-and-conquer algorithm. The merge step computes the
// convex hull of two convex polygons.
mMerged.resize(mNumUniquePoints);
int i0 = 0, i1 = mNumUniquePoints - 1;
GetHull(i0, i1);
mHull.resize(i1 - i0 + 1);
return true;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
InputType ConvexHull2<InputType, ComputeType>::GetEpsilon() const
{
return mEpsilon;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
int ConvexHull2<InputType, ComputeType>::GetDimension() const
{
return mDimension;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
Line2<InputType> const& ConvexHull2<InputType, ComputeType>::GetLine() const
{
return mLine;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
int ConvexHull2<InputType, ComputeType>::GetNumPoints() const
{
return mNumPoints;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
int ConvexHull2<InputType, ComputeType>::GetNumUniquePoints() const
{
return mNumUniquePoints;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
Vector2<InputType> const* ConvexHull2<InputType, ComputeType>::GetPoints()
const
{
return mPoints;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
PrimalQuery2<ComputeType> const&
ConvexHull2<InputType, ComputeType>::GetQuery() const
{
return mQuery;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
std::vector<int> const& ConvexHull2<InputType, ComputeType>::GetHull() const
{
return mHull;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
void ConvexHull2<InputType, ComputeType>::GetHull(int& i0, int& i1)
{
int numVertices = i1 - i0 + 1;
if (numVertices > 1)
{
// Compute the middle index of input range.
int mid = (i0 + i1) / 2;
// Compute the hull of subsets (mid-i0+1 >= i1-mid).
int j0 = i0, j1 = mid, j2 = mid + 1, j3 = i1;
GetHull(j0, j1);
GetHull(j2, j3);
// Merge the convex hulls into a single convex hull.
Merge(j0, j1, j2, j3, i0, i1);
}
// else: The convex hull is a single point.
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
void ConvexHull2<InputType, ComputeType>::Merge(int j0, int j1, int j2,
int j3, int& i0, int& i1)
{
// Subhull0 is to the left of subhull1 because of the initial sorting of
// the points by x-components. We need to find two mutually visible
// points, one on the left subhull and one on the right subhull.
int size0 = j1 - j0 + 1;
int size1 = j3 - j2 + 1;
int i;
Vector2<ComputeType> p;
// Find the right-most point of the left subhull.
Vector2<ComputeType> pmax0 = mComputePoints[mHull[j0]];
int imax0 = j0;
for (i = j0 + 1; i <= j1; ++i)
{
p = mComputePoints[mHull[i]];
if (pmax0 < p)
{
pmax0 = p;
imax0 = i;
}
}
// Find the left-most point of the right subhull.
Vector2<ComputeType> pmin1 = mComputePoints[mHull[j2]];
int imin1 = j2;
for (i = j2 + 1; i <= j3; ++i)
{
p = mComputePoints[mHull[i]];
if (p < pmin1)
{
pmin1 = p;
imin1 = i;
}
}
// Get the lower tangent to hulls (LL = lower-left, LR = lower-right).
int iLL = imax0, iLR = imin1;
GetTangent(j0, j1, j2, j3, iLL, iLR);
// Get the upper tangent to hulls (UL = upper-left, UR = upper-right).
int iUL = imax0, iUR = imin1;
GetTangent(j2, j3, j0, j1, iUR, iUL);
// Construct the counterclockwise-ordered merged-hull vertices.
int k;
int numMerged = 0;
i = iUL;
for (k = 0; k < size0; ++k)
{
mMerged[numMerged++] = mHull[i];
if (i == iLL)
{
break;
}
i = (i < j1 ? i + 1 : j0);
}
LogAssert(k < size0, "Unexpected condition.");
i = iLR;
for (k = 0; k < size1; ++k)
{
mMerged[numMerged++] = mHull[i];
if (i == iUR)
{
break;
}
i = (i < j3 ? i + 1 : j2);
}
LogAssert(k < size1, "Unexpected condition.");
int next = j0;
for (k = 0; k < numMerged; ++k)
{
mHull[next] = mMerged[k];
++next;
}
i0 = j0;
i1 = next - 1;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
void ConvexHull2<InputType, ComputeType>::GetTangent(int j0, int j1, int j2,
int j3, int& i0, int& i1)
{
// In theory the loop terminates in a finite number of steps, but the
// upper bound for the loop variable is used to trap problems caused by
// floating point roundoff errors that might lead to an infinite loop.
int size0 = j1 - j0 + 1;
int size1 = j3 - j2 + 1;
int const imax = size0 + size1;
int i, iLm1, iRp1;
Vector2<ComputeType> L0, L1, R0, R1;
for (i = 0; i < imax; i++)
{
// Get the endpoints of the potential tangent.
L1 = mComputePoints[mHull[i0]];
R0 = mComputePoints[mHull[i1]];
// Walk along the left hull to find the point of tangency.
if (size0 > 1)
{
iLm1 = (i0 > j0 ? i0 - 1 : j1);
L0 = mComputePoints[mHull[iLm1]];
auto order = mQuery.ToLineExtended(R0, L0, L1);
if (order == PrimalQuery2<ComputeType>::ORDER_NEGATIVE
|| order == PrimalQuery2<ComputeType>::ORDER_COLLINEAR_RIGHT)
{
i0 = iLm1;
continue;
}
}
// Walk along right hull to find the point of tangency.
if (size1 > 1)
{
iRp1 = (i1 < j3 ? i1 + 1 : j2);
R1 = mComputePoints[mHull[iRp1]];
auto order = mQuery.ToLineExtended(L1, R0, R1);
if (order == PrimalQuery2<ComputeType>::ORDER_NEGATIVE
|| order == PrimalQuery2<ComputeType>::ORDER_COLLINEAR_LEFT)
{
i1 = iRp1;
continue;
}
}
// The tangent segment has been found.
break;
}
// Detect an "infinite loop" caused by floating point round-off errors.
LogAssert(i < imax, "Unexpected condition.");
}
//----------------------------------------------------------------------------
} // namespace computationalgeometry2
} // namespace CmnCS
#endif /* CMNCS_COMPUTATIONALGEOMETRY2_CONVEXHULL2_HPP__ */ | 33.064748 | 78 | 0.578982 | Khoronus |
e086b37cbc311ddd5c5589a0e1e9cd2f3328db77 | 16,192 | cpp | C++ | Code/lib/AspenSIM800/src/atcmds/simcom.cpp | johannes51/Telefon | 751ff691b184f5fc456e5b978ebe39aecb1d3961 | [
"MIT"
] | null | null | null | Code/lib/AspenSIM800/src/atcmds/simcom.cpp | johannes51/Telefon | 751ff691b184f5fc456e5b978ebe39aecb1d3961 | [
"MIT"
] | null | null | null | Code/lib/AspenSIM800/src/atcmds/simcom.cpp | johannes51/Telefon | 751ff691b184f5fc456e5b978ebe39aecb1d3961 | [
"MIT"
] | null | null | null |
// "Aspen SIM800" is a comprehensive SIM800 library for simplified and in-depth chip access.
// Copyright (C) 2016 Mattias Aabmets (https://github.com/aspenforest)
//
// This API library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This API 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this API library. If not, see <http://www.gnu.org/licenses/>.
#include <SIM800.h>
// ============================================================
void SIM800::sideToneGain(CmdType type, const char* str) {
outBuilder(type, str, P("SIDET"));
print(ioBuffer);
}
// ============================================================
void SIM800::powerOff(const char* str) {
outBuilder(SET, str, P("CPOWD"));
print(ioBuffer);
}
// ============================================================
void SIM800::pinCodeTriesLeft() {
outBuilder(EXE, "", P("SPIC"));
print(ioBuffer);
}
// ============================================================
void SIM800::micGain(CmdType type, const char* str) {
outBuilder(type, str, P("CMIC"));
print(ioBuffer);
}
// ============================================================
void SIM800::alarmTime(CmdType type, const char* str) {
outBuilder(type, str, P("CALA"));
print(ioBuffer);
}
// ============================================================
void SIM800::delAlarm(CmdType type, const char* str) {
outBuilder(type, str, P("CALD"));
print(ioBuffer);
}
// ============================================================
void SIM800::readAdc(CmdType type) {
outBuilder(type, "", P("CADC"));
print(ioBuffer);
}
// ============================================================
void SIM800::singleNumScheme(CmdType type, const char* str) {
outBuilder(type, str, P("CSNS"));
print(ioBuffer);
}
// ============================================================
void SIM800::resetCellCast() {
outBuilder(EXE, "", P("CDSCB"));
print(ioBuffer);
}
// ============================================================
void SIM800::cfgAltModeCalls(CmdType type, const char* str) {
outBuilder(type, str, P("CMOD"));
print(ioBuffer);
}
// ============================================================
void SIM800::riPinUrc(CmdType type, const char* str) {
outBuilder(type, str, P("CFGRI"));
print(ioBuffer);
}
// ============================================================
void SIM800::timeStamp(CmdType type, const char* str) {
outBuilder(type, str, P("CLTS"));
print(ioBuffer);
}
// ============================================================
void SIM800::dtmfLocalTone(CmdType type, const char* str) {
outBuilder(type, str, P("CLDTMF"));
print(ioBuffer);
}
// ============================================================
void SIM800::indicateCallEnd(CmdType type, const char* str) {
outBuilder(type, str, P("CDRIND"));
print(ioBuffer);
}
// ============================================================
void SIM800::serviceProvider() {
outBuilder(GET, "", P("CSPN"));
print(ioBuffer);
}
// ============================================================
void SIM800::voiceMail(CmdType type, const char* str) {
outBuilder(type, str, P("CCVM"));
print(ioBuffer);
}
// ============================================================
void SIM800::opBand(CmdType type, const char* str) {
outBuilder(type, str, P("CBAND"));
print(ioBuffer);
}
// ============================================================
void SIM800::handsFree(CmdType type, const char* str) {
outBuilder(type, str, P("CHF"));
print(ioBuffer);
}
// ============================================================
void SIM800::swapAudio(CmdType type, const char* str) {
outBuilder(type, str, P("CHFA"));
print(ioBuffer);
}
// ============================================================
void SIM800::slowClock(CmdType type, const char* str) {
outBuilder(type, str, P("CSCLK"));
print(ioBuffer);
}
// ============================================================
void SIM800::engMode(CmdType type, const char* str) {
outBuilder(type, str, P("CENG"));
print(ioBuffer);
}
// ============================================================
void SIM800::smsZeroToSIM(CmdType type, const char* str) {
outBuilder(type, str, P("SCLASS0"));
print(ioBuffer);
}
// ============================================================
void SIM800::simCardID(CmdType type) {
outBuilder(type, "", P("CCID"));
print(ioBuffer);
}
// ============================================================
void SIM800::temperature(CmdType type, const char* str) {
outBuilder(type, str, P("CMTE"));
print(ioBuffer);
}
// ============================================================
void SIM800::delAllMsg(CmdType type, const char* str) {
outBuilder(type, str, P("CMGDA"));
print(ioBuffer);
}
// ============================================================
void SIM800::stkPlayTone(CmdType type, const char* str) {
outBuilder(type, str, P("STTONE"));
print(ioBuffer);
}
// ============================================================
void SIM800::toneGen(CmdType type, const char* str) {
outBuilder(type, str, P("SIMTONE"));
print(ioBuffer);
}
// ============================================================
void SIM800::alphaString(CmdType type, const char* str) {
outBuilder(type, str, P("CCPD"));
print(ioBuffer);
}
// ============================================================
void SIM800::simGroupID() {
outBuilder(EXE, "", P("CGID"));
print(ioBuffer);
}
// ============================================================
void SIM800::originCallState(CmdType type, const char* str) {
outBuilder(type, str, P("MORING"));
print(ioBuffer);
}
// ============================================================
void SIM800::smsHexMode(CmdType type, const char* str) {
outBuilder(type, str, P("CMGHEX"));
print(ioBuffer);
}
// ============================================================
void SIM800::smsDeviceCompat(CmdType type, const char* str) {
outBuilder(type, str, P("CCODE"));
print(ioBuffer);
}
// ============================================================
void SIM800::cfgInitUrc(CmdType type, const char* str) {
outBuilder(type, str, P("CIURC"));
print(ioBuffer);
}
// ============================================================
void SIM800::setSuperPwd(const char* str) {
outBuilder(SET, str, P("CPSPWD"));
print(ioBuffer);
}
// ============================================================
void SIM800::signalQualityURC(CmdType type, const char* str) {
outBuilder(type, str, P("EXUNSOL"));
print(ioBuffer);
}
// ============================================================
void SIM800::gprsMultiClass(CmdType type, const char* str) {
outBuilder(type, str, P("CGMSCLASS"));
print(ioBuffer);
}
// ============================================================
void SIM800::getFlashMem() {
outBuilder(GET, "", P("CDEVICE"));
print(ioBuffer);
}
// ============================================================
void SIM800::queryCallReady(CmdType type) {
outBuilder(type, "", P("CCALR"));
print(ioBuffer);
}
// ============================================================
void SIM800::getPII() {
outBuilder(EXE, "", P("GSV"));
print(ioBuffer);
}
// ============================================================
void SIM800::gpioCtrl(CmdType type, const char* str) {
outBuilder(type, str, P("SGPIO"));
print(ioBuffer);
}
// ============================================================
void SIM800::pwmGen(CmdType type, const char* str) {
outBuilder(type, str, P("SPWM"));
print(ioBuffer);
}
// ============================================================
void SIM800::echoCtrl(CmdType type, const char* str) {
outBuilder(type, str, P("ECHO"));
print(ioBuffer);
}
// ============================================================
void SIM800::autoAudioSwitch(CmdType type, const char* str) {
outBuilder(type, str, P("CAAS"));
print(ioBuffer);
}
// ============================================================
void SIM800::voiceEncoderCtrl(CmdType type, const char* str) {
outBuilder(type, str, P("SVR"));
print(ioBuffer);
}
// ============================================================
void SIM800::gsmBusy(CmdType type, const char* str) {
outBuilder(type, str, P("GSMBUSY"));
print(ioBuffer);
}
// ============================================================
void SIM800::emergencyNumList(CmdType type, const char* str) {
outBuilder(type, str, P("CEMNL"));
print(ioBuffer);
}
// ============================================================
void SIM800::arfcnLock(CmdType type, const char* str) {
outBuilder(type, str, P("AT*CELLLOCK"), false);
print(ioBuffer);
}
// ============================================================
void SIM800::netLightPeriod(CmdType type, const char* str) {
outBuilder(type, str, P("SLEDS"));
print(ioBuffer);
}
// ============================================================
void SIM800::buzzerRingtone(CmdType type, const char* str) {
outBuilder(type, str, P("CBUZZERRING"));
print(ioBuffer);
}
// ============================================================
void SIM800::micCtrl(CmdType type, const char* str) {
outBuilder(type, str, P("CEXTERNTONE"));
print(ioBuffer);
}
// ============================================================
void SIM800::netLight(CmdType type, const char* str) {
outBuilder(type, str, P("CNETLIGHT"));
print(ioBuffer);
}
// ============================================================
void SIM800::whiteList(CmdType type, const char* str) {
outBuilder(type, str, P("CWHITELIST"));
print(ioBuffer);
}
// ============================================================
void SIM800::detectSimCard(CmdType type, const char* str) {
outBuilder(type, str, P("CSDT"));
print(ioBuffer);
}
// ============================================================
void SIM800::simPresent(CmdType type, const char* str) {
outBuilder(type, str, P("CSMINS"));
print(ioBuffer);
}
// ============================================================
void SIM800::gprsNetLight(CmdType type, const char* str) {
outBuilder(type, str, P("CSGS"));
print(ioBuffer);
}
// ============================================================
void SIM800::micBias(CmdType type, const char* str) {
outBuilder(type, str, P("CMICBIAS"));
print(ioBuffer);
}
// ============================================================
void SIM800::playAudioIntoCall(CmdType type, const char* str) {
outBuilder(type, str, P("DTAM"));
print(ioBuffer);
}
// ============================================================
void SIM800::detectJamming(CmdType type, const char* str) {
outBuilder(type, str, P("SJDR"));
print(ioBuffer);
}
// ============================================================
void SIM800::pcmCfg(CmdType type, const char* str) {
outBuilder(type, str, P("CPCMCFG"));
print(ioBuffer);
}
// ============================================================
void SIM800::pcmSyncParam(CmdType type, const char* str) {
outBuilder(type, str, P("CPCMSYNC"));
print(ioBuffer);
}
// ============================================================
void SIM800::detectAntenna(CmdType type, const char* str) {
outBuilder(type, str, P("CANT"));
print(ioBuffer);
}
// ============================================================
void SIM800::agcCfg(CmdType type, const char* str) {
outBuilder(type, str, P("CAGCSET"));
print(ioBuffer);
}
// ============================================================
void SIM800::pcmSwitchSD(CmdType type, const char* str) {
outBuilder(type, str, P("SD2PCM"));
print(ioBuffer);
}
// ============================================================
void SIM800::detectKeypad(CmdType type, const char* str) {
outBuilder(type, str, P("SKPD"));
print(ioBuffer);
}
// ============================================================
void SIM800::toneStringGen(CmdType type, const char* str) {
outBuilder(type, str, P("SIMTONEX"));
print(ioBuffer);
}
// ============================================================
void SIM800::roamingState() {
outBuilder(EXE, "", P("CROAMING"));
print(ioBuffer);
}
// ============================================================
void SIM800::netScan(CmdType type, const char* str) {
outBuilder(type, str, P("CNETSCAN"));
print(ioBuffer);
}
// ============================================================
void SIM800::dualSerialPort(CmdType type, const char* str) {
outBuilder(type, str, P("CMNRP"));
print(ioBuffer);
}
// ============================================================
void SIM800::edgeCfg(CmdType type, const char* str) {
outBuilder(type, str, P("CEGPRS"));
print(ioBuffer);
}
// ============================================================
void SIM800::gpioIndex(CmdType type, const char* str) {
outBuilder(type, str, P("CGPIO"));
print(ioBuffer);
}
// ============================================================
void SIM800::playAudio(CmdType type, const char* str) {
outBuilder(type, str, P("CMEDPLAY"));
print(ioBuffer);
}
// ============================================================
void SIM800::audioVolume(CmdType type, const char* str) {
outBuilder(type, str, P("CMEDIAVOL"));
print(ioBuffer);
}
// ============================================================
void SIM800::atcmdSoundLevel(CmdType type, const char* str) {
outBuilder(type, str, P("SNDLEVEL"));
print(ioBuffer);
}
// ============================================================
void SIM800::chargeCtrl(CmdType type, const char* str) {
outBuilder(type, str, P("ECHARGE"));
print(ioBuffer);
}
// ============================================================
void SIM800::simPollInterval(CmdType type, const char* str) {
outBuilder(type, str, P("SIMTIMER"));
print(ioBuffer);
}
// ============================================================
void SIM800::enhanceSpeech(CmdType type, const char* str) {
outBuilder(type, str, P("SPE"));
print(ioBuffer);
}
// ============================================================
void SIM800::getConcatMsgIndex(CmdType type) {
outBuilder(type, "", P("CCONCINDEX"));
print(ioBuffer);
}
// ============================================================
void SIM800::sdModeSwitch(CmdType type, const char* str) {
outBuilder(type, str, P("SDMODE"));
print(ioBuffer);
}
// ============================================================
void SIM800::smsResendCtrl(CmdType type, const char* str) {
outBuilder(type, str, P("SRSPT"));
print(ioBuffer);
}
// ============================================================
void SIM800::record(CmdType type, const char* str) {
outBuilder(type, str, P("CREC"));
print(ioBuffer);
}
// ============================================================
void SIM800::recordToUart(CmdType type, const char* str) {
outBuilder(type, str, P("CRECORD"));
print(ioBuffer);
}
// ============================================================
void SIM800::textToSpeech(CmdType type, const char* str) {
outBuilder(type, str, P("CTTS"));
print(ioBuffer);
}
// ============================================================
void SIM800::textToSpeechCfg(CmdType type, const char* str) {
outBuilder(type, str, P("CTTSPARAM"));
print(ioBuffer);
}
// ============================================================
void SIM800::textToSpeechRing(CmdType type, const char* str) {
outBuilder(type, str, P("CTTSRING"));
print(ioBuffer);
} | 30.841905 | 94 | 0.442935 | johannes51 |
e089501b4347642ef9b8ffa2d27044aa6f46265a | 872 | cpp | C++ | gcc_main.cpp | tenk-a/mayu | 3689329757f07c40e898db7cea2ff4adf4089211 | [
"BSD-3-Clause"
] | null | null | null | gcc_main.cpp | tenk-a/mayu | 3689329757f07c40e898db7cea2ff4adf4089211 | [
"BSD-3-Clause"
] | 1 | 2021-02-06T12:38:30.000Z | 2021-02-06T12:38:30.000Z | gcc_main.cpp | tenk-a/mayu | 3689329757f07c40e898db7cea2ff4adf4089211 | [
"BSD-3-Clause"
] | null | null | null | // Linux,Darwin用のmaine
#define APSTUDIO_INVOKED
#include "misc.h"
#include "compiler_specific_func.h"
#include "engine.h"
#include "errormessage.h"
#include "function.h"
#include "mayu.h"
#if 0 //defined(WIN32)
# include "mayurc.h"
#endif
#include "msgstream.h"
#include "multithread.h"
#include "setting.h"
#include <time.h>
#include "gcc_main.h"
#if defined(__linux__) || defined(__APPLE__)
// TODO:
int main(int argc, char *argv[])
{
__argc = argc;
__targv = argv;
//TODO: 多重起動 check
try
{
Mayu mayu;
// 設定ファイルのロード.
if (mayu.load())
{
//コマンド実行時のEnterが残る可能性があるため、ちょっとだけ待つ.
sleep(2);
// キー置き換えの実行.
mayu.taskLoop();
}
}
catch (ErrorMessage e)
{
fprintf( stderr, "%s\n", e.getMessage().c_str() );
}
return 0;
}
#endif
| 16.45283 | 58 | 0.575688 | tenk-a |
e08cb7249af14064798f9ae08012b72fe80f1cea | 3,503 | cpp | C++ | TWatch_2021_Library/src/libraries/Cst816s/CST816S.cpp | Xinyuan-LilyGO/T-Watch-2021 | 4b604c39e143deb7b268889114cb81fb420cf65c | [
"MIT"
] | 34 | 2021-08-10T11:12:15.000Z | 2022-03-30T11:57:15.000Z | TWatch_2021_Library/src/libraries/Cst816s/CST816S.cpp | Xinyuan-LilyGO/T-Watch-2021 | 4b604c39e143deb7b268889114cb81fb420cf65c | [
"MIT"
] | 2 | 2021-10-03T23:58:16.000Z | 2022-01-11T02:01:58.000Z | TWatch_2021_Library/src/libraries/Cst816s/CST816S.cpp | Xinyuan-LilyGO/T-Watch-2021 | 4b604c39e143deb7b268889114cb81fb420cf65c | [
"MIT"
] | 11 | 2021-10-02T05:17:39.000Z | 2022-03-30T11:59:41.000Z | #include <Wire.h>
#include "CST816S.h"
void CST816S_Class::_writeReg(uint8_t reg, uint8_t data)
{
_i2cPort->beginTransmission(_address);
_i2cPort->write(reg);
_i2cPort->write(data);
_i2cPort->endTransmission();
}
// Write register values to chip
void CST816S_Class::_writeReg(uint8_t reg, uint8_t *data, uint8_t len)
{
_i2cPort->beginTransmission(_address);
_i2cPort->write(reg);
for (uint8_t i = 0; i < len; i++)
{
_i2cPort->write(data[i]);
}
_i2cPort->endTransmission();
}
// read register values to chip
uint8_t CST816S_Class::_readReg(uint8_t reg, uint8_t *data, uint8_t len)
{
_i2cPort->beginTransmission(_address);
_i2cPort->write(reg);
_i2cPort->endTransmission();
_i2cPort->requestFrom(_address, len);
uint8_t index = 0;
while (_i2cPort->available())
data[index++] = _i2cPort->read();
return 0;
}
bool CST816S_Class::begin(TwoWire &port, uint8_t res, uint8_t _int, uint8_t addr)
{
_i2cPort = &port;
_address = addr;
_res = res;
_int = _int;
pinMode(_int, INPUT_PULLUP);
/* attachInterrupt(_INT, []{ isTouch = true },LOW); */
setReset();
_i2cPort->beginTransmission(_address);
if (_i2cPort->endTransmission() != 0)
{
printf("CST816S NO Found!\n");
return false;
}
_writeReg(DisAutoSleep, 0x00); //默认为0,使能自动进入低功耗模式
_writeReg(NorScanPer, 0x01); //设置报点率
//报点:0x60 手势:0X11 报点加手势:0X71
_writeReg(IrqCtl, 0x60); //设置模式 报点/手势
//单位1S 为0时不启用功能 默认5
_writeReg(AutoReset, 0x05); //设置自动复位时间 X秒内有触摸但无手势时,自动复位
//单位1S 为0时不启用功能 默认10
_writeReg(LongPressTime, 0x10); //设置自动复位时间 长按X秒自动复位
//单位0.1mS
_writeReg(IrqPluseWidth, 0x02); //设置中断低脉冲输出宽度
/* data = 0x30;
_writeReg(LpScanTH, &data, 1); //设置低功耗扫描唤醒门限
data = 0x01;
_writeReg(LpScanWin, &data, 1); //设置低功耗扫描量程*/
/* data = 0x50;
_writeReg(LpScanFreq, &data, 1); //设置低功耗扫描频率 */
/* data = 0x80;
_writeReg(LpScanIdac, &data, 1); //设置低功耗扫描电流
data = 0x01;
_writeReg(AutoSleepTime, &data, 1); //设置1S进入低功耗 */
_readReg(0x00, Touch_Data, 7);
return true;
}
// Reset the chip
void CST816S_Class::setReset()
{
if (_res != -1)
{
pinMode(_res, OUTPUT);
digitalWrite(_res, LOW);
delay(10);
digitalWrite(_res, HIGH);
delay(50);
}
else
{
_writeReg(IOCtl, _BV(2));
delay(50);
}
}
// Set I2C Address if different then default.
void CST816S_Class::setADDR(uint8_t b)
{
_address = b;
}
bool CST816S_Class::read(void)
{
_readReg(0x00, Touch_Data, 7);
if (Touch_Data[3] >> 7)
return true;
else
return false;
}
void CST816S_Class::TouchInt(void)
{
_readReg(0x00, Touch_Data, 7);
}
uint8_t CST816S_Class::CheckID(void)
{
uint8_t data;
_readReg(ChipID, &data, 1);
return data;
}
uint8_t CST816S_Class::getTouchType(void)
{
return Touch_Data[1] >> 7;
}
uint16_t CST816S_Class::getX(void)
{
return ((uint16_t)(Touch_Data[3] & 0x0F) << 8) + (uint16_t)Touch_Data[4];
}
uint16_t CST816S_Class::getY(void)
{
return ((uint16_t)(Touch_Data[5] & 0x0F) << 8) + (uint16_t)Touch_Data[6];
}
void CST816S_Class::setAutoLowPower(bool en)
{
_writeReg(DisAutoSleep, en); //默认为0,使能自动进入低功耗模式
}
// Does not generate a pull-down signal
void CST816S_Class::setTouchInt(bool en)
{
_writeReg(IrqCtl, en ? 0x60 : 0x00); //设置模式 报点/手势
}
void CST816S_Class::setGesture(bool en)
{
_writeReg(MotionMask, en ? (EnConLR | EnConUD | EnDClick) : 0x00);
}
//Gesture detection sliding zone angle control. Angle=tan(c)*10 c is the angle based on the positive x-axis direction.
void CST816S_Class::setGestureCalibration(uint8_t data)
{
_writeReg(MotionSlAngle, data);
} | 20.976048 | 118 | 0.695404 | Xinyuan-LilyGO |
e08e716baf07e3860a97103aa165d3d4fcec76ff | 81 | hpp | C++ | src/Utility/Timer.hpp | ariabonczek/NewLumina | f35cf7f449cfbe191e03e1d5f1c9973cc0b44a8e | [
"MIT"
] | 2 | 2017-01-08T21:30:45.000Z | 2017-01-16T10:10:12.000Z | src/Utility/Timer.hpp | ariabonczek/NewLumina | f35cf7f449cfbe191e03e1d5f1c9973cc0b44a8e | [
"MIT"
] | null | null | null | src/Utility/Timer.hpp | ariabonczek/NewLumina | f35cf7f449cfbe191e03e1d5f1c9973cc0b44a8e | [
"MIT"
] | null | null | null | #ifndef TIMER_HPP
#define TIMER_HPP
class Timer
{
public:
private:
};
#endif | 6.230769 | 17 | 0.716049 | ariabonczek |
e0921421e0d2f59c2e2de568a6210c184aa55e85 | 2,003 | cpp | C++ | Linux/src/Code_highlighting.cpp | SongZihui-sudo/easyhtmleditor | 6ac122e0f6cff16da98adb74da2e3a2dba153748 | [
"MIT"
] | 1 | 2022-01-23T14:49:51.000Z | 2022-01-23T14:49:51.000Z | Linux/src/Code_highlighting.cpp | SongZihui-sudo/easyhtmleditor | 6ac122e0f6cff16da98adb74da2e3a2dba153748 | [
"MIT"
] | 9 | 2022-02-11T13:09:29.000Z | 2022-03-14T12:13:39.000Z | Linux/src/Code_highlighting.cpp | SongZihui-sudo/easyhtmleditor | 6ac122e0f6cff16da98adb74da2e3a2dba153748 | [
"MIT"
] | null | null | null | #include "../include/Code_highlighting.h"
#include "../include/EasyCodingEditor.h"
#include <curses.h>
#include<string>
using namespace cht;
using namespace edt;
edt::easyhtmleditor e1;
//设置颜色
void Code_highlighting::Set_color(int color){
int i;
initscr();
if(!has_colors()){
endwin();
fprintf(stderr,"Error - no color support on this terminal \n");
exit(1);
}
if(start_color() != OK){
endwin();
fprintf(stderr,"Error -could not initialize colors\n");
exit(2);
}
//erase();
//refresh();
init_pair(1,COLOR_RED,COLOR_BLACK);
init_pair(2,COLOR_BLUE,COLOR_BLACK);
init_pair(3,COLOR_GREEN,COLOR_BLACK);
init_pair(4,COLOR_YELLOW,COLOR_BLACK);
init_pair(5,COLOR_BLACK,COLOR_BLACK);
init_pair(6,COLOR_MAGENTA,COLOR_BLACK);
init_pair(7,COLOR_CYAN,COLOR_BLACK);
init_pair(8,COLOR_WHITE,COLOR_BLACK);
attroff(A_BOLD);
attrset(COLOR_PAIR(color));
}
void Code_highlighting::ReSetColor(){
Set_color(WB);
}
//词法分析
bool Code_highlighting::Lexical_analysis(deque <string> ready_highlight,deque <string>file_data,int pos_y){
key_words2 = file_data;
vector <cht::pos> postion;
vector <int> state;
initscr();
for (int i = 0; i < ready_highlight.size(); i++){
int bit = -1;
int num_tab = 0;
for (int k = 0; k < ready_highlight[i].size(); k++){
if (ready_highlight[i][k] == '\t'){
num_tab++;
}
else{
break;
}
}
for (int j = 0; j <key_words2.size(); j++){
bit = ready_highlight[i].find(key_words2[j]);
if (bit!=-1){
state.push_back(j);
cht::pos p1;
p1.x = bit+(num_tab*8);
p1.y = i+1;
postion.push_back(p1);
bit = 1;
}
else{
;
}
}
}
for (int i = 0; i < state.size(); i++){
if (state[i]){
Set_color(BLB);
mvprintw(postion[i].y,postion[i].x,"%s",key_words2[state[i]].c_str());
ReSetColor();
refresh();
}
else;
}
postion.clear();
state.clear();
ready_highlight.clear();
move(0,0);
return false;
} | 20.864583 | 107 | 0.621568 | SongZihui-sudo |
e092b1da6b544baa6bda12451b53814ab5d8000c | 734 | cpp | C++ | ProgramStudy/Source/Scenes/IScene.cpp | trinhlehainam/ASO_3rd_year_StudyProject | 89c54e42e97cc47af175f61b26a5871bc2a718a0 | [
"MIT"
] | null | null | null | ProgramStudy/Source/Scenes/IScene.cpp | trinhlehainam/ASO_3rd_year_StudyProject | 89c54e42e97cc47af175f61b26a5871bc2a718a0 | [
"MIT"
] | null | null | null | ProgramStudy/Source/Scenes/IScene.cpp | trinhlehainam/ASO_3rd_year_StudyProject | 89c54e42e97cc47af175f61b26a5871bc2a718a0 | [
"MIT"
] | null | null | null | #include "IScene.h"
#include <cassert>
#include <DxLib.h>
#include "../Systems/EntityMng.h"
IScene::IScene() :
EnableChangeScene(false),
m_screenOffsetX(0.0f), m_screenOffsetY(0.0f), m_entityMng(std::make_shared<EntityMng>())
{
m_entityMng->m_self = m_entityMng;
SetDrawScreen(DX_SCREEN_BACK);
GetDrawScreenSize(&m_screenWidth, &m_screenHeight);
m_screenID = DxLib::MakeScreen(m_screenWidth, m_screenHeight, 1);
if (m_screenID == -1)
assert(0);
}
IScene::~IScene()
{
DeleteGraph(m_screenID);
}
void IScene::SetName(std::string name)
{
m_name = std::move(name);
}
std::string IScene::GetName() const
{
return m_name;
}
void IScene::Render()
{
DxLib::DrawGraphF(m_screenOffsetX, m_screenOffsetY, m_screenID, 0);
}
| 17.902439 | 89 | 0.724796 | trinhlehainam |
e0a48149241741762f951e36d252d8cee716cb38 | 24,143 | cpp | C++ | RenderSystems/Vulkan/src/OgreVulkanRenderPassDescriptor.cpp | dawlane/ogre | 7bae21738c99b117ef2eab3fcb1412891b8c2025 | [
"MIT"
] | 1 | 2019-10-29T23:36:28.000Z | 2019-10-29T23:36:28.000Z | RenderSystems/Vulkan/src/OgreVulkanRenderPassDescriptor.cpp | dawlane/ogre | 7bae21738c99b117ef2eab3fcb1412891b8c2025 | [
"MIT"
] | null | null | null | RenderSystems/Vulkan/src/OgreVulkanRenderPassDescriptor.cpp | dawlane/ogre | 7bae21738c99b117ef2eab3fcb1412891b8c2025 | [
"MIT"
] | null | null | null | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-present Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreVulkanRenderPassDescriptor.h"
#include "OgreVulkanDevice.h"
#include "OgreVulkanRenderSystem.h"
#include "OgreVulkanTextureGpu.h"
#include "OgreVulkanTextureGpuWindow.h"
#include "OgreVulkanWindow.h"
#include "OgreVulkanMappings.h"
#include "OgreVulkanUtils.h"
namespace Ogre
{
VulkanRenderPassDescriptor::VulkanRenderPassDescriptor( VulkanQueue *graphicsQueue,
VulkanRenderSystem *renderSystem ) :
mSharedFboItor( renderSystem->_getFrameBufferDescMap().end() ),
mTargetWidth( 0u ),
mTargetHeight( 0u ),
mQueue( graphicsQueue ),
mRenderSystem( renderSystem )
{
}
//-----------------------------------------------------------------------------------
VulkanRenderPassDescriptor::~VulkanRenderPassDescriptor() { releaseFbo(); }
//-----------------------------------------------------------------------------------
void VulkanRenderPassDescriptor::calculateSharedKey( void )
{
uint32 hash = FastHash((const char*)mColour, mNumColourEntries * sizeof(mColour[0]));
hash = HashCombine(hash, mDepth);
VulkanFrameBufferDescMap &frameBufferDescMap = mRenderSystem->_getFrameBufferDescMap();
VulkanFrameBufferDescMap::iterator newItor = frameBufferDescMap.find( hash );
if( newItor == frameBufferDescMap.end() )
{
VulkanFrameBufferDescValue value;
value.refCount = 0;
frameBufferDescMap[hash] = value;
newItor = frameBufferDescMap.find(hash);
}
++newItor->second.refCount;
releaseFbo();
mSharedFboItor = newItor;
}
//-----------------------------------------------------------------------------------
VkClearColorValue VulkanRenderPassDescriptor::getClearColour( const ColourValue &clearColour,
PixelFormatGpu pixelFormat )
{
const bool isInteger = PixelUtil::isInteger( pixelFormat );
const bool isSigned = false;//PixelUtil::isSigned( pixelFormat );
VkClearColorValue retVal;
if( !isInteger )
{
for( size_t i = 0u; i < 4u; ++i )
retVal.float32[i] = static_cast<float>( clearColour[i] );
}
else
{
if( !isSigned )
{
for( size_t i = 0u; i < 4u; ++i )
retVal.uint32[i] = static_cast<uint32>( clearColour[i] );
}
else
{
for( size_t i = 0u; i < 4u; ++i )
retVal.int32[i] = static_cast<int32>( clearColour[i] );
}
}
return retVal;
}
//-----------------------------------------------------------------------------------
/**
@brief VulkanRenderPassDescriptor::setupColourAttachment
This will setup:
attachments[currAttachmIdx]
colourAttachRefs[vkIdx]
resolveAttachRefs[vkIdx]
fboDesc.mImageViews[currAttachmIdx]
fboDesc.mWindowImageViews
Except mWindowImageViews, all the other variables are *always* written to.
@param idx [in]
idx to mColour[idx]
@param fboDesc [in/out]
@param attachments [out]
A pointer to setup VkAttachmentDescription
@param currAttachmIdx [in/out]
A value to index attachments[currAttachmIdx]
@param colourAttachRefs [out]
A pointer to setup VkAttachmentReference
@param resolveAttachRefs [out]
A pointer to setup VkAttachmentReference
@param vkIdx [in]
A value to index both colourAttachRefs[vkIdx] & resolveAttachRefs[vkIdx]
Very often idx == vkIdx except when we skip a colour entry due to being PFG_NULL
@param resolveTex
False if we're setting up the main target
True if we're setting up the resolve target
*/
void VulkanRenderPassDescriptor::setupColourAttachment(
const size_t idx, VulkanFrameBufferDescValue &fboDesc, VkAttachmentDescription *attachments,
uint32 &currAttachmIdx, VkAttachmentReference *colourAttachRefs,
VkAttachmentReference *resolveAttachRefs, const size_t vkIdx, const bool bResolveTex )
{
VulkanTextureGpu* colour = mColour[idx];
if (!colour->getMsaaTextureName() && bResolveTex)
{
// There's no resolve texture to setup
resolveAttachRefs[vkIdx].attachment = VK_ATTACHMENT_UNUSED;
resolveAttachRefs[vkIdx].layout = VK_IMAGE_LAYOUT_UNDEFINED;
return;
}
VkImage texName = 0;
VulkanTextureGpu *texture = colour;
if( !bResolveTex && texture->getMsaaTextureName())
{
texName = texture->getMsaaTextureName();
}
else
{
texName = texture->getFinalTextureName();
}
VkAttachmentDescription &attachment = attachments[currAttachmIdx];
attachment.format = VulkanMappings::get( texture->getFormat() );
attachment.samples = bResolveTex ? VK_SAMPLE_COUNT_1_BIT : VkSampleCountFlagBits(colour->getFSAA());
attachment.loadOp = bResolveTex ? VK_ATTACHMENT_LOAD_OP_DONT_CARE : VK_ATTACHMENT_LOAD_OP_CLEAR;// TODO colour.loadAction );
attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; // TODO colour.storeAction
attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
if( !bResolveTex )
{
attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // TODO VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
if (texture->isRenderWindowSpecific() && !texture->isMultisample())
{
attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
}
else if(!texture->isMultisample())
{
attachment.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
}
else
{
attachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
}
}
else
{
attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
if (texture->isRenderWindowSpecific())
attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
else
attachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
}
const uint8 mipLevel = 0;//bResolveTex ? colour.resolveMipLevel : colour.mipLevel;
//mSlice = bResolveTex ? colour.resolveSlice : colour.slice;
if( !texture->isRenderWindowSpecific() || ( texture->isMultisample() && !bResolveTex ) )
{
fboDesc.mImageViews[currAttachmIdx] = texture->_createView(mipLevel, 1, mSlice, 1u, texName);
}
else
{
fboDesc.mImageViews[currAttachmIdx] = 0; // Set to null (will be set later, 1 for each FBO)
auto textureVulkan = dynamic_cast<VulkanTextureGpuWindow*>(texture);
OGRE_ASSERT_LOW(fboDesc.mWindowImageViews.empty() && "Only one window can be used as target");
fboDesc.mWindowImageViews = textureVulkan->getWindow()->getSwapchainImageViews();
}
if( bResolveTex )
{
resolveAttachRefs[vkIdx].attachment = currAttachmIdx;
resolveAttachRefs[vkIdx].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
++currAttachmIdx;
}
else
{
colourAttachRefs[vkIdx].attachment = currAttachmIdx;
colourAttachRefs[vkIdx].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
++currAttachmIdx;
// Now repeat with the resolve texture (if applies)
setupColourAttachment( idx, fboDesc, attachments, currAttachmIdx, colourAttachRefs,
resolveAttachRefs, vkIdx, true );
}
}
//-----------------------------------------------------------------------------------
VkImageView VulkanRenderPassDescriptor::setupDepthAttachment( VkAttachmentDescription &attachment )
{
attachment.format = VulkanMappings::get( mDepth->getFormat() );
attachment.samples = VkSampleCountFlagBits(std::max(mDepth->getFSAA(), 1u));
attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
if( 0 )
{
attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
}
else
{
attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
}
attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
if(mNumColourEntries == 0)
{
// assume depth will be read
attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachment.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
}
else
{
attachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
}
VulkanTextureGpu *texture = mDepth;
VkImage texName =
texture->getMsaaTextureName() ? texture->getMsaaTextureName() : texture->getFinalTextureName();
return texture->_createView(0, 1, 0, 1u, texName);
}
//-----------------------------------------------------------------------------------
void VulkanRenderPassDescriptor::setupFbo( VulkanFrameBufferDescValue &fboDesc )
{
if( fboDesc.mRenderPass )
return; // Already initialized
bool hasRenderWindow = false;
uint32 attachmentIdx = 0u;
uint32 numColourAttachments = 0u;
uint32 windowAttachmentIdx = std::numeric_limits<uint32>::max();
bool usesResolveAttachments = false;
// 1 per MRT
// 1 per MRT MSAA resolve
// 1 for Depth buffer
// 1 for Stencil buffer
VkAttachmentDescription attachments[OGRE_MAX_MULTIPLE_RENDER_TARGETS * 2u + 2u] = {};
VkAttachmentReference colourAttachRefs[OGRE_MAX_MULTIPLE_RENDER_TARGETS];
VkAttachmentReference resolveAttachRefs[OGRE_MAX_MULTIPLE_RENDER_TARGETS];
VkAttachmentReference depthAttachRef;
for( size_t i = 0; i < mNumColourEntries; ++i )
{
hasRenderWindow |= mColour[i]->isRenderWindowSpecific();
if( mColour[i]->getFormat() == PF_UNKNOWN )
continue;
OGRE_ASSERT_HIGH( dynamic_cast<VulkanTextureGpu *>( mColour[i] ) );
VulkanTextureGpu *textureVulkan = static_cast<VulkanTextureGpu *>( mColour[i] );
if( textureVulkan->isRenderWindowSpecific() )
{
windowAttachmentIdx = attachmentIdx;
// use the resolve texture idx
if (textureVulkan->getMsaaTextureName())
windowAttachmentIdx++;
}
setupColourAttachment( i, fboDesc, attachments, attachmentIdx, colourAttachRefs,
resolveAttachRefs, numColourAttachments, false );
if( resolveAttachRefs[numColourAttachments].attachment != VK_ATTACHMENT_UNUSED )
usesResolveAttachments = true;
++numColourAttachments;
}
if( mDepth )
{
fboDesc.mImageViews[attachmentIdx] = setupDepthAttachment( attachments[attachmentIdx] );
depthAttachRef.attachment = attachmentIdx;
if(0)// mDepth.readOnly )
depthAttachRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
else
depthAttachRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
++attachmentIdx;
}
VkSubpassDescription subpass = {VK_PIPELINE_BIND_POINT_GRAPHICS};
subpass.inputAttachmentCount = 0u;
subpass.colorAttachmentCount = numColourAttachments;
subpass.pColorAttachments = colourAttachRefs;
subpass.pResolveAttachments = usesResolveAttachments ? resolveAttachRefs : 0;
subpass.pDepthStencilAttachment = mDepth ? &depthAttachRef : 0;
fboDesc.mNumImageViews = attachmentIdx;
// Use subpass dependencies for layout transitions for RenderTextures
auto accessMask =
mNumColourEntries ? VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT : VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
std::array<VkSubpassDependency, 2> dependencies;
dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL;
dependencies[0].dstSubpass = 0;
dependencies[0].srcStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[0].srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
dependencies[0].dstAccessMask = accessMask;
dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
dependencies[1].srcSubpass = 0;
dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL;
dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[1].dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
dependencies[1].srcAccessMask = accessMask;
dependencies[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
VkRenderPassCreateInfo renderPassCreateInfo = {VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO};
renderPassCreateInfo.attachmentCount = attachmentIdx;
renderPassCreateInfo.pAttachments = attachments;
renderPassCreateInfo.subpassCount = 1u;
renderPassCreateInfo.pSubpasses = &subpass;
if(!hasRenderWindow)
{
renderPassCreateInfo.dependencyCount = dependencies.size();
renderPassCreateInfo.pDependencies = dependencies.data();
}
OGRE_VK_CHECK(vkCreateRenderPass( mQueue->mDevice, &renderPassCreateInfo, 0, &fboDesc.mRenderPass ));
VkFramebufferCreateInfo fbCreateInfo = {VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO};
fbCreateInfo.renderPass = fboDesc.mRenderPass;
fbCreateInfo.attachmentCount = attachmentIdx;
fbCreateInfo.pAttachments = fboDesc.mImageViews;
fbCreateInfo.width = mTargetWidth;
fbCreateInfo.height = mTargetHeight;
fbCreateInfo.layers = 1u;
const size_t numFramebuffers = std::max<size_t>( fboDesc.mWindowImageViews.size(), 1u );
fboDesc.mFramebuffers.resize( numFramebuffers );
for( size_t i = 0u; i < numFramebuffers; ++i )
{
if( !fboDesc.mWindowImageViews.empty() )
fboDesc.mImageViews[windowAttachmentIdx] = fboDesc.mWindowImageViews[i];
OGRE_VK_CHECK(vkCreateFramebuffer(mQueue->mDevice, &fbCreateInfo, 0, &fboDesc.mFramebuffers[i]));
if( !fboDesc.mWindowImageViews.empty() )
fboDesc.mImageViews[windowAttachmentIdx] = 0;
}
}
//-----------------------------------------------------------------------------------
void VulkanRenderPassDescriptor::releaseFbo( void )
{
VulkanFrameBufferDescMap &frameBufferDescMap = mRenderSystem->_getFrameBufferDescMap();
if( mSharedFboItor != frameBufferDescMap.end() )
{
--mSharedFboItor->second.refCount;
if( !mSharedFboItor->second.refCount )
{
destroyFbo( mQueue, mSharedFboItor->second );
frameBufferDescMap.erase( mSharedFboItor );
}
mSharedFboItor = frameBufferDescMap.end();
}
}
//-----------------------------------------------------------------------------------
void VulkanRenderPassDescriptor::destroyFbo( VulkanQueue *queue,
VulkanFrameBufferDescValue &fboDesc )
{
//VaoManager *vaoManager = queue->getVaoManager();
{
FastArray<VkFramebuffer>::const_iterator itor = fboDesc.mFramebuffers.begin();
FastArray<VkFramebuffer>::const_iterator endt = fboDesc.mFramebuffers.end();
while( itor != endt )
vkDestroyFramebuffer( queue->mDevice, *itor++, 0 );
fboDesc.mFramebuffers.clear();
}
for( size_t i = 0u; i < fboDesc.mNumImageViews; ++i )
{
if( fboDesc.mImageViews[i] )
{
vkDestroyImageView( queue->mDevice, fboDesc.mImageViews[i], 0 );
fboDesc.mImageViews[i] = 0;
}
}
fboDesc.mNumImageViews = 0u;
vkDestroyRenderPass( queue->mDevice, fboDesc.mRenderPass, 0 );
fboDesc.mRenderPass = 0;
}
//-----------------------------------------------------------------------------------
void VulkanRenderPassDescriptor::entriesModified( bool createFbo )
{
calculateSharedKey();
TextureGpu *anyTargetTexture = 0;
const uint8 numColourEntries = mNumColourEntries;
for( int i = 0; i < numColourEntries && !anyTargetTexture; ++i )
anyTargetTexture = mColour[i];
if( !anyTargetTexture )
anyTargetTexture = mDepth;
mTargetWidth = 0u;
mTargetHeight = 0u;
if( anyTargetTexture )
{
mTargetWidth = anyTargetTexture->getWidth();
mTargetHeight = anyTargetTexture->getHeight();
}
if( createFbo )
setupFbo( mSharedFboItor->second );
}
//-----------------------------------------------------------------------------------
void VulkanRenderPassDescriptor::setClearColour( uint8 idx, const ColourValue &clearColour )
{
//RenderPassDescriptor::setClearColour( idx, clearColour );
size_t attachmentIdx = 0u;
for( size_t i = 0u; i < idx; ++i )
{
++attachmentIdx;
if (mColour[i]->getMsaaTextureName())
++attachmentIdx;
}
mClearValues[attachmentIdx].color =
getClearColour( clearColour, mColour[idx]->getFormat() );
}
//-----------------------------------------------------------------------------------
void VulkanRenderPassDescriptor::setClearDepth( Real clearDepth )
{
//RenderPassDescriptor::setClearDepth( clearDepth );
if( mDepth && mSharedFboItor != mRenderSystem->_getFrameBufferDescMap().end() )
{
size_t attachmentIdx = mSharedFboItor->second.mNumImageViews - 1u;
if( !mRenderSystem->isReverseDepthBufferEnabled() )
mClearValues[attachmentIdx].depthStencil.depth = static_cast<float>(clearDepth);
else
{
mClearValues[attachmentIdx].depthStencil.depth = static_cast<float>(Real(1.0) - clearDepth);
}
}
}
//-----------------------------------------------------------------------------------
void VulkanRenderPassDescriptor::setClearStencil( uint32 clearStencil )
{
//RenderPassDescriptor::setClearStencil( clearStencil );
if (mDepth && mSharedFboItor != mRenderSystem->_getFrameBufferDescMap().end())
{
size_t attachmentIdx = mSharedFboItor->second.mNumImageViews - 1u;
mClearValues[attachmentIdx].depthStencil.stencil = clearStencil;
}
}
//-----------------------------------------------------------------------------------
void VulkanRenderPassDescriptor::setClearColour( const ColourValue &clearColour )
{
const size_t numColourEntries = mNumColourEntries;
size_t attachmentIdx = 0u;
for( size_t i = 0u; i < numColourEntries; ++i )
{
mClearValues[attachmentIdx].color = getClearColour(clearColour, mColour[i]->getFormat());
++attachmentIdx;
if (mColour[i]->getMsaaTextureName())
++attachmentIdx;
}
}
VkRenderPass VulkanRenderPassDescriptor::getRenderPass() const
{
return mSharedFboItor->second.mRenderPass;
}
//-----------------------------------------------------------------------------------
void VulkanRenderPassDescriptor::performLoadActions()
{
VkCommandBuffer cmdBuffer = mQueue->mCurrentCmdBuffer;
const VulkanFrameBufferDescValue &fboDesc = mSharedFboItor->second;
size_t fboIdx = 0u;
if( !fboDesc.mWindowImageViews.empty() )
{
VulkanTextureGpuWindow* textureVulkan = static_cast<VulkanTextureGpuWindow*>(mColour[0]);
fboIdx = textureVulkan->getCurrentImageIdx();
VkSemaphore semaphore = textureVulkan->getImageAcquiredSemaphore();
if( semaphore )
{
// We cannot start executing color attachment commands until the semaphore says so
mQueue->addWindowToWaitFor( semaphore );
}
}
VkRenderPassBeginInfo passBeginInfo = {VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
passBeginInfo.renderPass = fboDesc.mRenderPass;
passBeginInfo.framebuffer = fboDesc.mFramebuffers[fboIdx];
passBeginInfo.renderArea.offset.x = 0;
passBeginInfo.renderArea.offset.y = 0;
passBeginInfo.renderArea.extent.width = mTargetWidth;
passBeginInfo.renderArea.extent.height = mTargetHeight;
passBeginInfo.clearValueCount = sizeof( mClearValues ) / sizeof( mClearValues[0] );
passBeginInfo.pClearValues = mClearValues;
vkCmdBeginRenderPass( cmdBuffer, &passBeginInfo, VK_SUBPASS_CONTENTS_INLINE );
}
//-----------------------------------------------------------------------------------
void VulkanRenderPassDescriptor::performStoreActions()
{
if( mQueue->getEncoderState() != VulkanQueue::EncoderGraphicsOpen )
return;
vkCmdEndRenderPass( mQueue->mCurrentCmdBuffer );
// End (if exists) the render command encoder tied to this RenderPassDesc.
// Another encoder will have to be created, and don't let ours linger
// since mCurrentRenderPassDescriptor probably doesn't even point to 'this'
mQueue->endAllEncoders( false );
}
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
VulkanFrameBufferDescValue::VulkanFrameBufferDescValue() :
refCount( 0u ),
mNumImageViews( 0u ),
mRenderPass( 0 )
{
memset( mImageViews, 0, sizeof( mImageViews ) );
}
} // namespace Ogre
| 43.1125 | 132 | 0.602783 | dawlane |
e0a522806d4243f3cdc967a041fa37e19c0b4e89 | 16,911 | cpp | C++ | widgets/FancyTabBar/fancytabbar.cpp | polovik/asa | f791fec3036b679748e7ad3a8c8da351ed438fc4 | [
"MIT"
] | null | null | null | widgets/FancyTabBar/fancytabbar.cpp | polovik/asa | f791fec3036b679748e7ad3a8c8da351ed438fc4 | [
"MIT"
] | 28 | 2016-10-01T15:36:58.000Z | 2021-01-31T07:58:47.000Z | widgets/FancyTabBar/fancytabbar.cpp | polovik/asa | f791fec3036b679748e7ad3a8c8da351ed438fc4 | [
"MIT"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** 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 "fancytabbar.h"
#include "stylehelper.h"
#include <QMouseEvent>
#include <QPainter>
#include <QColor>
#include <QStackedLayout>
#include <QToolTip>
#include <QtDebug>
const int FancyTabBar::m_rounding = 22;
const int FancyTabBar::m_textPadding = 4;
FancyTabBar::FancyTabBar(const TabBarPosition position, QWidget *parent)
: QWidget(parent), mPosition(position)
{
mHoverIndex = -1;
mCurrentIndex = -1;
if(mPosition == TabBarPosition::Above || mPosition == TabBarPosition::Below)
{
setMinimumHeight(qMax(2 * m_rounding, 40));
setMaximumHeight(tabSizeHint(false).height());
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
}
else
{
setMinimumWidth(tabSizeHint(false).width());
setMaximumWidth(tabSizeHint(false).width());
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
}
setAttribute(Qt::WA_Hover, true);
setFocusPolicy(Qt::NoFocus);
setMouseTracking(true); // Needed for hover events
mTimerTriggerChangedSignal.setSingleShot(true);
// We use a zerotimer to keep the sidebar responsive
connect(&mTimerTriggerChangedSignal, SIGNAL(timeout()), this, SLOT(emitCurrentIndex()));
}
FancyTabBar::~FancyTabBar()
{
}
QSize FancyTabBar::tabSizeHint(bool minimum) const
{
QFont boldFont(font());
boldFont.setPointSizeF(StyleHelper::sidebarFontSize());
boldFont.setBold(true);
QFontMetrics fm(boldFont);
int spacing = 8;
int width = 80 + spacing + 2;
int maxLabelwidth = 0;
for (int tab = 0; tab < count(); ++tab) {
int labelWidth = fm.width(tabText(tab));
if (labelWidth > maxLabelwidth)
maxLabelwidth = labelWidth;
}
int iconHeight = minimum ? 0 : 40;
return QSize(qMax(width, maxLabelwidth + 4), iconHeight + spacing + fm.height());
}
QPoint FancyTabBar::getCorner(const QRect& rect, const Corner corner) const
{
if(mPosition == TabBarPosition::Above)
{
if(corner == Corner::OutsideBeginning) return rect.topLeft();
if(corner == Corner::OutsideEnd) return rect.topRight();
if(corner == Corner::InsideBeginning) return rect.bottomLeft();
if(corner == Corner::InsideEnd) return rect.bottomRight();
}
else if(mPosition == TabBarPosition::Below)
{
if(corner == Corner::OutsideBeginning) return rect.bottomLeft();
if(corner == Corner::OutsideEnd) return rect.bottomRight();
if(corner == Corner::InsideBeginning) return rect.topLeft();
if(corner == Corner::InsideEnd) return rect.topRight();
}
else if(mPosition == TabBarPosition::Left)
{
if(corner == Corner::OutsideBeginning) return rect.topLeft();
if(corner == Corner::OutsideEnd) return rect.bottomLeft();
if(corner == Corner::InsideBeginning) return rect.topRight();
if(corner == Corner::InsideEnd) return rect.bottomRight();
}
else if(mPosition == TabBarPosition::Right)
{
if(corner == Corner::OutsideBeginning) return rect.topRight();
if(corner == Corner::OutsideEnd) return rect.bottomRight();
if(corner == Corner::InsideBeginning) return rect.topLeft();
if(corner == Corner::InsideEnd) return rect.bottomLeft();
}
qFatal("that's impossible!");
return QPoint();
}
QRect FancyTabBar::adjustRect(const QRect& rect, const qint8 offsetOutside, const qint8 offsetInside, const qint8 offsetBeginning, const qint8 offsetEnd) const
{
if(mPosition == TabBarPosition::Above) return rect.adjusted(-offsetBeginning, -offsetOutside, offsetEnd, offsetInside);
else if(mPosition == TabBarPosition::Below) return rect.adjusted(-offsetBeginning, -offsetInside, -offsetBeginning, offsetOutside);
else if(mPosition == TabBarPosition::Left) return rect.adjusted(-offsetOutside, -offsetBeginning, offsetInside, offsetEnd);
else if(mPosition == TabBarPosition::Right) return rect.adjusted(-offsetInside, -offsetBeginning, offsetOutside, offsetEnd);
qFatal("that's impossible!");
return QRect();
}
// Same with a point: + means towards Outside/End, - means towards Inside/Beginning
QPoint FancyTabBar::adjustPoint(const QPoint& point, const qint8 offsetInsideOutside, const qint8 offsetBeginningEnd) const
{
if(mPosition == TabBarPosition::Above) return point + QPoint(offsetBeginningEnd, -offsetInsideOutside);
else if(mPosition == TabBarPosition::Below) return point + QPoint(offsetBeginningEnd, offsetInsideOutside);
else if(mPosition == TabBarPosition::Left) return point + QPoint(-offsetInsideOutside, offsetBeginningEnd);
else if(mPosition == TabBarPosition::Right) return point + QPoint(offsetInsideOutside, offsetBeginningEnd);
qFatal("that's impossible!");
return QPoint();
}
void FancyTabBar::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter painter(this);
// paint background
QRect rectangle = adjustRect(rect(), 0, -1, 0, 0);
QLinearGradient lg;
lg.setStart(getCorner(rectangle, Corner::OutsideBeginning));
lg.setFinalStop(getCorner(rectangle, Corner::InsideBeginning));
lg.setColorAt(0.0, QColor(64, 64, 64, 255));
lg.setColorAt(1.0, QColor(130, 130, 130, 255));
painter.fillRect(rectangle, lg);
// draw dark widget bordert on inner inside (e.g. bottom if the widget position is top)
painter.setPen(StyleHelper::borderColor());
painter.drawLine(adjustPoint(getCorner(rectangle, Corner::InsideBeginning), -1, 0), adjustPoint(getCorner(rectangle, Corner::InsideEnd), -1, 0));
// draw bright widget border on outer inside (e.g. bottom if the widget position is top)
painter.setPen(StyleHelper::sidebarHighlight());
painter.drawLine(getCorner(rectangle, Corner::InsideBeginning), getCorner(rectangle, Corner::InsideEnd));
// paint inactive tabs
for (int i = 0; i < count(); ++i)
if (i != currentIndex())
paintTab(&painter, i);
// paint active tab last, since it overlaps the neighbors
if (currentIndex() != -1)
paintTab(&painter, currentIndex());
}
// Handle hover events for mouse fade ins
void FancyTabBar::mouseMoveEvent(QMouseEvent *e)
{
int newHover = -1;
for (int i = 0; i < count(); ++i)
{
QRect area = tabRect(i);
if (area.contains(e->pos())) {
newHover = i;
break;
}
}
if (newHover == mHoverIndex)
return;
if (validIndex(mHoverIndex))
mAttachedTabs[mHoverIndex]->fadeOut();
mHoverIndex = newHover;
if (validIndex(mHoverIndex)) {
mAttachedTabs[mHoverIndex]->fadeIn();
mHoverRect = tabRect(mHoverIndex);
}
}
bool FancyTabBar::event(QEvent *event)
{
if (event->type() == QEvent::ToolTip) {
if (validIndex(mHoverIndex)) {
QString tt = tabToolTip(mHoverIndex);
if (!tt.isEmpty()) {
QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), tt, this);
return true;
}
}
}
return QWidget::event(event);
}
// Resets hover animation on mouse enter
void FancyTabBar::enterEvent(QEvent *e)
{
Q_UNUSED(e)
mHoverRect = QRect();
mHoverIndex = -1;
}
// Resets hover animation on mouse leave
void FancyTabBar::leaveEvent(QEvent *e)
{
Q_UNUSED(e)
mHoverIndex = -1;
mHoverRect = QRect();
for (int i = 0 ; i < mAttachedTabs.count() ; ++i) {
mAttachedTabs[i]->fadeOut();
}
}
QSize FancyTabBar::sizeHint() const
{
QSize sh = tabSizeHint();
// return QSize(sh.width(), sh.height() * mAttachedTabs.count());
if(mPosition == TabBarPosition::Above || mPosition == TabBarPosition::Below)
return QSize(sh.width() * mAttachedTabs.count(), sh.height());
else
return QSize(sh.width(), sh.height() * mAttachedTabs.count());
}
QSize FancyTabBar::minimumSizeHint() const
{
QSize sh = tabSizeHint(true);
// return QSize(sh.width(), sh.height() * mAttachedTabs.count());
if(mPosition == TabBarPosition::Above || mPosition == TabBarPosition::Below)
return QSize(sh.width() * mAttachedTabs.count(), sh.height());
else
return QSize(sh.width(), sh.height() * mAttachedTabs.count());
}
QRect FancyTabBar::tabRect(int index) const
{
QSize sh = tabSizeHint();
if(mPosition == TabBarPosition::Above || mPosition == TabBarPosition::Below)
{
if (sh.width() * mAttachedTabs.count() > width())
sh.setWidth(width() / mAttachedTabs.count());
return QRect(index * sh.width(), 0, sh.width(), sh.height());
}
else
{
if (sh.height() * mAttachedTabs.count() > height())
sh.setHeight(height() / mAttachedTabs.count());
return QRect(0, index * sh.height(), sh.width(), sh.height());
}
}
// This keeps the sidebar responsive since
// we get a repaint before loading the
// mode itself
void FancyTabBar::emitCurrentIndex()
{
emit currentChanged(mCurrentIndex);
}
void FancyTabBar::mousePressEvent(QMouseEvent *e)
{
e->accept();
for (int index = 0; index < mAttachedTabs.count(); ++index)
{
if (tabRect(index).contains(e->pos()))
{
if (isTabEnabled(index))
{
mCurrentIndex = index;
update();
mTimerTriggerChangedSignal.start(0);
}
break;
}
}
}
void FancyTabBar::paintTab(QPainter *painter, int tabIndex) const
{
if (!validIndex(tabIndex))
{
qWarning("invalid index");
return;
}
painter->save();
QRect rect = tabRect(tabIndex);
bool selected = (tabIndex == mCurrentIndex);
bool enabled = isTabEnabled(tabIndex);
if(selected)
{
// background
painter->save();
QLinearGradient grad(getCorner(rect, Corner::OutsideBeginning), getCorner(rect, Corner::InsideBeginning));
grad.setColorAt(0, QColor(255, 255, 255, 140));
grad.setColorAt(1, QColor(255, 255, 255, 210));
painter->fillRect(adjustRect(rect, 0, 0, 0, -1), grad);
painter->restore();
// shadows (the black lines immediately before/after (active && selected)-backgrounds)
painter->setPen(QColor(0, 0, 0, 110));
painter->drawLine(adjustPoint(getCorner(rect, Corner::OutsideBeginning), 0, -1), adjustPoint(getCorner(rect, Corner::InsideBeginning), 0, -1));
painter->drawLine(getCorner(rect, Corner::OutsideEnd), getCorner(rect, Corner::InsideEnd));
// thin shadow on the outside of active tab
painter->setPen(QColor(0, 0, 0, 40));
painter->drawLine(getCorner(rect, Corner::OutsideBeginning), getCorner(rect, Corner::OutsideEnd));
// highlights
painter->setPen(QColor(255, 255, 255, 50));
painter->drawLine(adjustPoint(getCorner(rect, Corner::OutsideBeginning), 0, -2), adjustPoint(getCorner(rect, Corner::InsideBeginning), 0, -2));
painter->drawLine(adjustPoint(getCorner(rect, Corner::OutsideEnd), 0, 1), adjustPoint(getCorner(rect, Corner::InsideEnd), 0, 1));
painter->setPen(QColor(255, 255, 255, 40));
// thin white line towards beginning
painter->drawLine(adjustPoint(getCorner(rect, Corner::OutsideBeginning), 0, 0), adjustPoint(getCorner(rect, Corner::InsideBeginning), 0, 0));
// thin white line on inside border
painter->drawLine(adjustPoint(getCorner(rect, Corner::InsideBeginning), 0, 1), adjustPoint(getCorner(rect, Corner::InsideEnd), 0, -1));
// thin white line towards end
painter->drawLine(adjustPoint(getCorner(rect, Corner::OutsideEnd), 0, -1), adjustPoint(getCorner(rect, Corner::InsideEnd), 0, -1));
}
QString tabText(this->tabText(tabIndex));
QRect tabTextRect(rect);
const bool drawIcon = rect.height() > 36;
QRect tabIconRect(tabTextRect);
tabTextRect.translate(0, drawIcon ? -2 : 1);
QFont boldFont(painter->font());
boldFont.setPointSizeF(StyleHelper::sidebarFontSize());
boldFont.setBold(true);
painter->setFont(boldFont);
painter->setPen(selected ? QColor(255, 255, 255, 160) : QColor(0, 0, 0, 110));
const int textFlags = Qt::AlignCenter | (drawIcon ? Qt::AlignBottom : Qt::AlignVCenter) | Qt::TextWordWrap;
if (enabled) {
painter->drawText(tabTextRect, textFlags, tabText);
painter->setPen(selected ? QColor(60, 60, 60) : StyleHelper::panelTextColor());
} else {
painter->setPen(selected ? StyleHelper::panelTextColor() : QColor(255, 255, 255, 120));
}
#if defined(Q_OS_MAC)
bool isMac=true;
#else
bool isMac = false;
#endif
// hover
if(!isMac && !selected && enabled)
{
painter->save();
int fader = int(mAttachedTabs[tabIndex]->fader());
QLinearGradient grad(getCorner(rect, Corner::OutsideBeginning), getCorner(rect, Corner::InsideBeginning));
grad.setColorAt(0, Qt::transparent);
grad.setColorAt(0.5, QColor(255, 255, 255, fader));
grad.setColorAt(1, Qt::transparent);
painter->fillRect(rect, grad);
painter->setPen(QPen(grad, 1.0));
if(mPosition == TabBarPosition::Above || mPosition == TabBarPosition::Below)
{
painter->drawLine(rect.topLeft(), rect.bottomLeft());
painter->drawLine(rect.topRight(), rect.bottomRight());
}
else
{
painter->drawLine(rect.topLeft(), rect.topRight());
painter->drawLine(rect.bottomLeft(), rect.bottomRight());
}
painter->restore();
}
if (!enabled)
painter->setOpacity(0.7);
if (drawIcon) {
int textHeight = painter->fontMetrics().boundingRect(QRect(0, 0, width(), height()), Qt::TextWordWrap, tabText).height();
tabIconRect.adjust(0, 4, 0, -textHeight);
StyleHelper::drawIconWithShadow(tabIcon(tabIndex), tabIconRect, painter, enabled ? QIcon::Normal : QIcon::Disabled);
}
painter->translate(0, -1);
painter->drawText(tabTextRect, textFlags, tabText);
painter->restore();
}
void FancyTabBar::setCurrentIndex(int index) {
if (isTabEnabled(index)) {
mCurrentIndex = index;
update();
emit currentChanged(mCurrentIndex);
}
}
void FancyTabBar::setTabEnabled(int index, bool enable)
{
Q_ASSERT(index < mAttachedTabs.size());
Q_ASSERT(index >= 0);
if (index < mAttachedTabs.size() && index >= 0) {
mAttachedTabs[index]->enabled = enable;
/* During constructor there was no tabs attached which caused a limit in tab dimensions by the call
to setMaximumHeight and setMaximumWidth.
when attached tabs have texts demanding more space than the previous limit setup in constructor,
this caused the text to be truncated.
By updating setMaximumWidth and setMaximumHeight during setTabEnabled calls will keep space
allocation dynamic enough to grow an shrink tabbar as needed.
And beware that QFontMetrics doesn't take into account \n characters inside the strings. */
if(mPosition == TabBarPosition::Above || mPosition == TabBarPosition::Below)
{
setMaximumHeight(tabSizeHint(false).height());
}
else
{
setMaximumWidth(tabSizeHint(false).width());
}
update(tabRect(index));
}
}
bool FancyTabBar::isTabEnabled(int index) const
{
Q_ASSERT(index < mAttachedTabs.size());
Q_ASSERT(index >= 0);
if (index < mAttachedTabs.size() && index >= 0)
return mAttachedTabs[index]->enabled;
return false;
}
| 36.057569 | 159 | 0.659098 | polovik |
e0a8532769fee93aeda24fe3ae374b15a84ee9fd | 4,757 | cpp | C++ | src/coherence/component/util/RunnableCacheEvent.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-01T21:38:30.000Z | 2021-11-03T01:35:11.000Z | src/coherence/component/util/RunnableCacheEvent.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 1 | 2020-07-24T17:29:22.000Z | 2020-07-24T18:29:04.000Z | src/coherence/component/util/RunnableCacheEvent.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-10T18:40:58.000Z | 2022-02-18T01:23:40.000Z | /*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#include "private/coherence/component/util/RunnableCacheEvent.hpp"
#include "coherence/net/NamedCache.hpp"
#include "private/coherence/util/logging/Logger.hpp"
COH_OPEN_NAMESPACE3(coherence,component,util)
using coherence::net::NamedCache;
using coherence::util::logging::Logger;
// ----- constructors -------------------------------------------------------
RunnableCacheEvent::RunnableCacheEvent(MapEvent::Handle hMapEvent,
Listeners::View vListeners)
: f_vListeners(self(), vListeners),
f_hListenerSupport(self()),
f_hMapEvent(self(), hMapEvent),
f_hMapListener(self())
{
COH_ENSURE_PARAM(hMapEvent);
COH_ENSURE_PARAM(vListeners);
}
RunnableCacheEvent::RunnableCacheEvent(MapEvent::Handle hMapEvent,
MapListener::Handle hListener)
: f_vListeners(self()),
f_hListenerSupport(self()),
f_hMapEvent(self(), hMapEvent),
f_hMapListener(self(), hListener)
{
COH_ENSURE_PARAM(hMapEvent);
COH_ENSURE_PARAM(hListener);
}
RunnableCacheEvent::RunnableCacheEvent(MapEvent::Handle hMapEvent,
MapListenerSupport::Handle hListenerSupport)
: f_vListeners(self()),
f_hListenerSupport(self(), hListenerSupport),
f_hMapEvent(self(), hMapEvent),
f_hMapListener(self())
{
COH_ENSURE_PARAM(hMapEvent);
COH_ENSURE_PARAM(hListenerSupport);
}
// ----- Runnable interface -------------------------------------------------
void RunnableCacheEvent::run()
{
MapEvent::Handle hEvent = getMapEvent();
if (cast<NamedCache::View>(hEvent->getSource())->isActive())
{
MapListenerSupport::Handle hSupport = getListenerSupport();
if (NULL == hSupport)
{
Listeners::View vListeners = getListeners();
if (NULL == vListeners)
{
hEvent->dispatch(getMapListener());
}
else
{
hEvent->dispatch(vListeners, true);
}
}
else
{
hSupport->fireEvent(hEvent, true);
}
}
}
// ----- Object interface ---------------------------------------------------
TypedHandle<const String> RunnableCacheEvent::toString() const
{
return COH_TO_STRING(Class::getClassName(this) << ": " << getMapEvent());
}
// ----- static functions ---------------------------------------------------
void RunnableCacheEvent::dispatchSafe(MapEvent::Handle hEvent,
Listeners::View vListeners, Queue::Handle hQueue)
{
if (vListeners != NULL)
{
ObjectArray::View vaListener = vListeners->listeners();
for (size32_t i = 0, c = vaListener->length; i < c; i++)
{
MapListener::Handle hListener = cast<MapListener::Handle>
(vaListener[i]);
if (instanceof<MapListenerSupport::SynchronousListener::Handle>(hListener))
{
try
{
hEvent->dispatch(hListener);
}
catch (Exception::View vEx)
{
COH_LOG(COH_TO_STRING(
"An exception occured while dispatching synchronous event:" <<
hEvent), Logger::level_error);
COH_LOGEX(vEx, Logger::level_error);
COH_LOG("(The exception has been logged and execution is continuing.)",
Logger::level_error);
}
}
else
{
hQueue->add(RunnableCacheEvent::create(hEvent, hListener));
}
}
}
}
// ----- accessors ----------------------------------------------------------
Listeners::View RunnableCacheEvent::getListeners() const
{
return f_vListeners;
}
MapListenerSupport::Handle RunnableCacheEvent::getListenerSupport()
{
return f_hListenerSupport;
}
MapListenerSupport::View RunnableCacheEvent::getListenerSupport() const
{
return f_hListenerSupport;
}
MapEvent::Handle RunnableCacheEvent::getMapEvent()
{
return f_hMapEvent;
}
MapEvent::View RunnableCacheEvent::getMapEvent() const
{
return f_hMapEvent;
}
MapListener::Handle RunnableCacheEvent::getMapListener()
{
return f_hMapListener;
}
MapListener::View RunnableCacheEvent::getMapListener() const
{
return f_hMapListener;
}
COH_CLOSE_NAMESPACE3
| 28.147929 | 91 | 0.557915 | chpatel3 |
e0aab439f54a64328470dd6aabb7f34d2a338dc5 | 6,117 | hxx | C++ | generated/include/vnx/addons/HttpServerBase.hxx | MMX-World/vnx-addons | 93dbf8d8cece4e127131fcaf2f15f92e74ed81e6 | [
"MIT"
] | null | null | null | generated/include/vnx/addons/HttpServerBase.hxx | MMX-World/vnx-addons | 93dbf8d8cece4e127131fcaf2f15f92e74ed81e6 | [
"MIT"
] | null | null | null | generated/include/vnx/addons/HttpServerBase.hxx | MMX-World/vnx-addons | 93dbf8d8cece4e127131fcaf2f15f92e74ed81e6 | [
"MIT"
] | null | null | null |
// AUTO GENERATED by vnxcppcodegen
#ifndef INCLUDE_vnx_addons_HttpServerBase_HXX_
#define INCLUDE_vnx_addons_HttpServerBase_HXX_
#include <vnx/addons/package.hxx>
#include <vnx/Module.h>
#include <vnx/TopicPtr.hpp>
#include <vnx/addons/HttpChunk.hxx>
#include <vnx/addons/HttpData.hxx>
#include <vnx/addons/HttpRequest.hxx>
#include <vnx/addons/HttpResponse.hxx>
namespace vnx {
namespace addons {
class HttpServerBase : public ::vnx::Module {
public:
::vnx::TopicPtr output_request;
::vnx::TopicPtr output_response;
int32_t port = 8080;
std::string host = "localhost";
vnx::bool_t non_blocking = true;
vnx::bool_t show_info = false;
vnx::bool_t show_warnings = false;
vnx::bool_t error_payload = true;
vnx::bool_t auto_session = false;
vnx::bool_t enable_deflate = true;
int32_t num_threads = 4;
int32_t session_size = 3;
int32_t listen_queue_size = 1000;
int32_t stats_interval_ms = 10000;
int32_t connection_timeout_ms = 30000;
int64_t session_timeout = 86400;
int64_t max_payload_size = 16777216;
int64_t max_chunk_size = 1048576;
int64_t min_compress_size = 4096;
std::set<std::string> do_compress;
std::map<std::string, std::string> components;
std::map<std::string, std::string> charset;
std::vector<std::pair<std::string, std::string>> add_headers;
std::string default_access = "VIEWER";
std::string cookie_policy = "SameSite=Strict;";
std::string session_coookie_name = "hsid";
std::string login_path = "/login";
std::string logout_path = "/logout";
std::string session_path = "/session";
typedef ::vnx::Module Super;
static const vnx::Hash64 VNX_TYPE_HASH;
static const vnx::Hash64 VNX_CODE_HASH;
static constexpr uint64_t VNX_TYPE_ID = 0xf05b2d0ac45a8a7bull;
HttpServerBase(const std::string& _vnx_name);
vnx::Hash64 get_type_hash() const override;
std::string get_type_name() const override;
const vnx::TypeCode* get_type_code() const override;
void read(std::istream& _in) override;
void write(std::ostream& _out) const override;
template<typename T>
void accept_generic(T& _visitor) const;
void accept(vnx::Visitor& _visitor) const override;
vnx::Object to_object() const override;
void from_object(const vnx::Object& object) override;
vnx::Variant get_field(const std::string& name) const override;
void set_field(const std::string& name, const vnx::Variant& value) override;
friend std::ostream& operator<<(std::ostream& _out, const HttpServerBase& _value);
friend std::istream& operator>>(std::istream& _in, HttpServerBase& _value);
static const vnx::TypeCode* static_get_type_code();
static std::shared_ptr<vnx::TypeCode> static_create_type_code();
protected:
using Super::handle;
virtual void handle(std::shared_ptr<const ::vnx::addons::HttpChunk> _value) {}
virtual void http_request_async(std::shared_ptr<const ::vnx::addons::HttpRequest> request, const std::string& sub_path, const vnx::request_id_t& _request_id) const = 0;
void http_request_async_return(const vnx::request_id_t& _request_id, const std::shared_ptr<const ::vnx::addons::HttpResponse>& _ret_0) const;
virtual void http_request_chunk_async(std::shared_ptr<const ::vnx::addons::HttpRequest> request, const std::string& sub_path, const int64_t& offset, const int64_t& max_bytes, const vnx::request_id_t& _request_id) const = 0;
void http_request_chunk_async_return(const vnx::request_id_t& _request_id, const std::shared_ptr<const ::vnx::addons::HttpData>& _ret_0) const;
void vnx_handle_switch(std::shared_ptr<const vnx::Value> _value) override;
std::shared_ptr<vnx::Value> vnx_call_switch(std::shared_ptr<const vnx::Value> _method, const vnx::request_id_t& _request_id) override;
};
template<typename T>
void HttpServerBase::accept_generic(T& _visitor) const {
_visitor.template type_begin<HttpServerBase>(29);
_visitor.type_field("output_request", 0); _visitor.accept(output_request);
_visitor.type_field("output_response", 1); _visitor.accept(output_response);
_visitor.type_field("port", 2); _visitor.accept(port);
_visitor.type_field("host", 3); _visitor.accept(host);
_visitor.type_field("non_blocking", 4); _visitor.accept(non_blocking);
_visitor.type_field("show_info", 5); _visitor.accept(show_info);
_visitor.type_field("show_warnings", 6); _visitor.accept(show_warnings);
_visitor.type_field("error_payload", 7); _visitor.accept(error_payload);
_visitor.type_field("auto_session", 8); _visitor.accept(auto_session);
_visitor.type_field("enable_deflate", 9); _visitor.accept(enable_deflate);
_visitor.type_field("num_threads", 10); _visitor.accept(num_threads);
_visitor.type_field("session_size", 11); _visitor.accept(session_size);
_visitor.type_field("listen_queue_size", 12); _visitor.accept(listen_queue_size);
_visitor.type_field("stats_interval_ms", 13); _visitor.accept(stats_interval_ms);
_visitor.type_field("connection_timeout_ms", 14); _visitor.accept(connection_timeout_ms);
_visitor.type_field("session_timeout", 15); _visitor.accept(session_timeout);
_visitor.type_field("max_payload_size", 16); _visitor.accept(max_payload_size);
_visitor.type_field("max_chunk_size", 17); _visitor.accept(max_chunk_size);
_visitor.type_field("min_compress_size", 18); _visitor.accept(min_compress_size);
_visitor.type_field("do_compress", 19); _visitor.accept(do_compress);
_visitor.type_field("components", 20); _visitor.accept(components);
_visitor.type_field("charset", 21); _visitor.accept(charset);
_visitor.type_field("add_headers", 22); _visitor.accept(add_headers);
_visitor.type_field("default_access", 23); _visitor.accept(default_access);
_visitor.type_field("cookie_policy", 24); _visitor.accept(cookie_policy);
_visitor.type_field("session_coookie_name", 25); _visitor.accept(session_coookie_name);
_visitor.type_field("login_path", 26); _visitor.accept(login_path);
_visitor.type_field("logout_path", 27); _visitor.accept(logout_path);
_visitor.type_field("session_path", 28); _visitor.accept(session_path);
_visitor.template type_end<HttpServerBase>(29);
}
} // namespace vnx
} // namespace addons
namespace vnx {
} // vnx
#endif // INCLUDE_vnx_addons_HttpServerBase_HXX_
| 42.776224 | 224 | 0.775544 | MMX-World |
e0ae9f03c6c74fe26e351c428ff2f2bf2fd70621 | 486 | cpp | C++ | Hacks/disablepostprocessing.cpp | maikel233/X-HOOK-For-CS-GO | 811bd67171ad48c44b9c5c05cc0fbb5fff4b3687 | [
"MIT"
] | 48 | 2018-11-10T06:39:17.000Z | 2022-03-10T18:44:52.000Z | Hacks/disablepostprocessing.cpp | maikel233/X-HOOK-For-CS-GO | 811bd67171ad48c44b9c5c05cc0fbb5fff4b3687 | [
"MIT"
] | 7 | 2018-01-04T15:10:41.000Z | 2020-11-14T03:54:30.000Z | Hacks/disablepostprocessing.cpp | maikel233/X-HOOK-For-CS-GO | 811bd67171ad48c44b9c5c05cc0fbb5fff4b3687 | [
"MIT"
] | 21 | 2018-11-23T23:13:09.000Z | 2022-03-14T21:11:38.000Z | #include "../Features.h"
bool Settings::DisablePostProcessing::enabled = false;
void DisablePostProcessing::BeginFrame()
{
if (!Settings::ESP::enabled && Settings::DisablePostProcessing::enabled)
return;
static bool ToggleOnce = false;
if (!ToggleOnce)
{
auto postprocessing = pCvar->FindVar("mat_postprocess_enable");
auto postprocessingspoof = new SpoofedConvar(postprocessing);
postprocessingspoof->SetInt(0);
ToggleOnce = true;
}
}
| 19.44 | 74 | 0.699588 | maikel233 |
e0b532c042daf6472b6fa96e2006dacc3695f51e | 46,883 | cpp | C++ | srcs/EventSelectionTool.cpp | RhiannonSJ/SBND_Analysis_Tool | e31378c59da54295e2fe58ab73dfee5d6cf7f7fd | [
"Apache-2.0"
] | null | null | null | srcs/EventSelectionTool.cpp | RhiannonSJ/SBND_Analysis_Tool | e31378c59da54295e2fe58ab73dfee5d6cf7f7fd | [
"Apache-2.0"
] | null | null | null | srcs/EventSelectionTool.cpp | RhiannonSJ/SBND_Analysis_Tool | e31378c59da54295e2fe58ab73dfee5d6cf7f7fd | [
"Apache-2.0"
] | null | null | null | #include "../include/EventSelectionTool.h"
#include <iostream>
#include <numeric>
#include "TLeaf.h"
#include "TBranch.h"
#include "TVector3.h"
#include <algorithm>
#include <iterator>
#include <cmath>
#include <ctime>
#include <cstdlib>
namespace ana{
void EventSelectionTool::GetTimeLeft(const int start_time, const int total, const unsigned int i){
int now = static_cast<int>(time(NULL));
int diff = now - start_time;
int n_left = total - (i+1);
int time_left = std::round(diff/double(i+1) * n_left);
int seconds_per_minute = 60;
int seconds_per_hour = 3600;
int seconds_per_day = 86400;
int days_left = time_left / (seconds_per_day);
int hours_left = (time_left - (days_left * seconds_per_day)) / (seconds_per_hour);
int minutes_left = (time_left - (days_left * seconds_per_day) - (hours_left * seconds_per_hour)) / (seconds_per_minute);
int seconds_left = time_left - (days_left * seconds_per_day) - (hours_left * seconds_per_hour) - (minutes_left * seconds_per_minute);
if(i%2){
std::cout << " Estimated time left: " << std::setw(5) << days_left << " days, ";
std::cout << std::setw(5) << hours_left << " hours, ";
std::cout << std::setw(5) << minutes_left << " minutes, ";
std::cout << std::setw(5) << seconds_left << " seconds." << '\r' << flush;
}
}
//------------------------------------------------------------------------------------------
void EventSelectionTool::LoadEventList(const std::string &file_name, EventList &event_list, const int &file){
TFile f(file_name.c_str());
TTree *t_event = (TTree*) f.Get("event_tree");
TTree *t_particle = (TTree*) f.Get("particle_tree");
TTree *t_track = (TTree*) f.Get("recotrack_tree");
TTree *t_shower = (TTree*) f.Get("recoshower_tree");
TBranch *b_event_id = t_event->GetBranch("event_id");
TBranch *b_time_now = t_event->GetBranch("time_now");
TBranch *b_r_vertex = t_event->GetBranch("r_vertex");
TBranch *b_t_vertex = t_event->GetBranch("t_vertex");
TBranch *b_t_interaction = t_event->GetBranch("t_interaction");
TBranch *b_t_scatter = t_event->GetBranch("t_scatter");
TBranch *b_t_iscc = t_event->GetBranch("t_iscc");
TBranch *b_t_nu_pdgcode = t_event->GetBranch("t_nu_pdgcode");
TBranch *b_t_charged_pions = t_event->GetBranch("t_charged_pions");
TBranch *b_t_neutral_pions = t_event->GetBranch("t_neutral_pions");
TBranch *b_t_vertex_energy = t_event->GetBranch("t_vertex_energy");
unsigned int n_events = t_event->GetEntries();
unsigned int start_tracks = 0;
unsigned int start_showers = 0;
unsigned int start_mcparticles = 0;
for(unsigned int j = 0; j < n_events; ++j){
ParticleList mcparticles;
ParticleList recoparticles;
TrackList tracks;
ShowerList showers;
TVector3 r_vertex, t_vertex;
unsigned int interaction, pions_ch, pions_neu, scatter;
int neutrino_pdg;
bool iscc(false);
float neu_energy;
t_event->GetEntry(j);
int event_id = b_event_id->GetLeaf("event_id")->GetValue();
int time_now = b_time_now->GetLeaf("time_now")->GetValue();
r_vertex[0] = b_r_vertex->GetLeaf("r_vertex")->GetValue(0);
r_vertex[1] = b_r_vertex->GetLeaf("r_vertex")->GetValue(1);
r_vertex[2] = b_r_vertex->GetLeaf("r_vertex")->GetValue(2);
t_vertex[0] = b_t_vertex->GetLeaf("t_vertex")->GetValue(0);
t_vertex[1] = b_t_vertex->GetLeaf("t_vertex")->GetValue(1);
t_vertex[2] = b_t_vertex->GetLeaf("t_vertex")->GetValue(2);
interaction = b_t_interaction->GetLeaf("t_interaction")->GetValue();
scatter = b_t_scatter->GetLeaf("t_scatter")->GetValue();
iscc = b_t_iscc->GetLeaf("t_iscc")->GetValue();
neutrino_pdg = b_t_nu_pdgcode->GetLeaf("t_nu_pdgcode")->GetValue();
pions_ch = b_t_charged_pions->GetLeaf("t_charged_pions")->GetValue();
pions_neu = b_t_neutral_pions->GetLeaf("t_neutral_pions")->GetValue();
neu_energy = b_t_vertex_energy->GetLeaf("t_vertex_energy")->GetValue();
std::pair<int,int> event_identification(event_id,time_now);
EventSelectionTool::GetTrackList(start_tracks, t_track, event_identification, tracks);
EventSelectionTool::GetShowerList(start_showers, t_shower, event_identification, showers);
EventSelectionTool::GetMCParticleList(start_mcparticles, t_particle, event_identification, mcparticles);
EventSelectionTool::GetRecoParticleFromTrack1Escaping(tracks, recoparticles);
EventSelectionTool::GetRecoParticleFromShower(showers, r_vertex, recoparticles);
// Check if any particles should be flipped
EventSelectionTool::CheckAndFlip(r_vertex, recoparticles);
event_list.push_back(Event(mcparticles, recoparticles, interaction, scatter, neutrino_pdg, pions_ch, pions_neu, iscc, t_vertex, r_vertex, neu_energy, file, event_id));
start_tracks += tracks.size();
start_showers += showers.size();
start_mcparticles += mcparticles.size();
}
}
//------------------------------------------------------------------------------------------
void EventSelectionTool::CheckAndFlip(const TVector3 &vtx, ParticleList &particles){
// Loop over reconstructed particles
// Check if the end point of the particle is closer to the neutrino vertex than the start
// Flip if true
for(Particle &p : particles){
// Make sure the particle we are looking at is a reconstructed track
if(!p.GetFromRecoTrack()) continue;
// If the end is closer to the neutrino vertex than the start, flip it
float nu_vtx_dist = (vtx - p.GetVertex()).Mag();
float nu_end_dist = (vtx - p.GetEnd()).Mag();
if(nu_vtx_dist > nu_end_dist) p.FlipTrack();
}
}
//------------------------------------------------------------------------------------------
void EventSelectionTool::GetUniqueEventList(TTree *event_tree, UniqueEventIdList &unique_event_list){
TBranch *b_event_id = event_tree->GetBranch("event_id");
TBranch *b_time_now = event_tree->GetBranch("time_now");
unsigned int n_events = event_tree->GetEntries();
for(unsigned int i = 0; i < n_events; ++i){
event_tree->GetEntry(i);
int event_id_a = b_event_id->GetLeaf("event_id")->GetValue();
int time_now_a = b_time_now->GetLeaf("time_now")->GetValue();
bool shouldAdd(true);
for(unsigned int j = 0; j < n_events; ++j){
event_tree->GetEntry(j);
int event_id_b = b_event_id->GetLeaf("event_id")->GetValue();
int time_now_b = b_time_now->GetLeaf("time_now")->GetValue();
if (event_id_a == event_id_b && time_now_a == time_now_b && i != j){
shouldAdd = false;
break;
}
}
if (shouldAdd)
unique_event_list.push_back(std::pair<int, int>(event_id_a, time_now_a));
}
}
//------------------------------------------------------------------------------------------
void EventSelectionTool::GetTrackList(unsigned int start, TTree *track_tree, const std::pair<int, int> &unique_event, TrackList &track_list){
TBranch *b_event_id = track_tree->GetBranch("event_id");
TBranch *b_time_now = track_tree->GetBranch("time_now");
TBranch *b_id_charge = track_tree->GetBranch("tr_id_charge");
TBranch *b_id_energy = track_tree->GetBranch("tr_id_energy");
TBranch *b_id_hits = track_tree->GetBranch("tr_id_hits");
TBranch *b_n_hits = track_tree->GetBranch("tr_n_hits");
TBranch *b_vertex = track_tree->GetBranch("tr_vertex");
TBranch *b_end = track_tree->GetBranch("tr_end");
TBranch *b_pida = track_tree->GetBranch("tr_pida");
TBranch *b_chi2_mu = track_tree->GetBranch("tr_chi2_mu");
TBranch *b_chi2_pi = track_tree->GetBranch("tr_chi2_pi");
TBranch *b_chi2_pr = track_tree->GetBranch("tr_chi2_pr");
TBranch *b_chi2_ka = track_tree->GetBranch("tr_chi2_ka");
TBranch *b_length = track_tree->GetBranch("tr_length");
TBranch *b_kinetic_energy = track_tree->GetBranch("tr_kinetic_energy");
TBranch *b_mcs_mom_muon = track_tree->GetBranch("tr_mcs_mom_muon");
TBranch *b_range_mom_muon = track_tree->GetBranch("tr_range_mom_muon");
TBranch *b_range_mom_proton = track_tree->GetBranch("tr_range_mom_proton");
unsigned int n_entries = track_tree->GetEntries();
for(unsigned int i = 0; i < n_entries; ++i){
track_tree->GetEntry(i);
int event_id = b_event_id->GetLeaf("event_id")->GetValue();
int time_now = b_time_now->GetLeaf("time_now")->GetValue();
if(event_id != unique_event.first || time_now != unique_event.second) continue;
double temp_vertex[3];
double temp_end[3];
int id_charge = b_id_charge->GetLeaf("tr_id_charge")->GetValue();
int id_energy = b_id_energy->GetLeaf("tr_id_energy")->GetValue();
int id_hits = b_id_hits->GetLeaf("tr_id_hits")->GetValue();
int n_hits = b_n_hits->GetLeaf("tr_n_hits")->GetValue();
temp_vertex[0] = b_vertex->GetLeaf("tr_vertex")->GetValue(0);
temp_vertex[1] = b_vertex->GetLeaf("tr_vertex")->GetValue(1);
temp_vertex[2] = b_vertex->GetLeaf("tr_vertex")->GetValue(2);
temp_end[0] = b_end->GetLeaf("tr_end")->GetValue(0);
temp_end[1] = b_end->GetLeaf("tr_end")->GetValue(1);
temp_end[2] = b_end->GetLeaf("tr_end")->GetValue(2);
float pida = b_pida->GetLeaf("tr_pida")->GetValue();
float chi2_mu = b_chi2_mu->GetLeaf("tr_chi2_mu")->GetValue();
float chi2_pi = b_chi2_pi->GetLeaf("tr_chi2_pi")->GetValue();
float chi2_pr = b_chi2_pr->GetLeaf("tr_chi2_pr")->GetValue();
float chi2_ka = b_chi2_ka->GetLeaf("tr_chi2_ka")->GetValue();
float length = b_length->GetLeaf("tr_length")->GetValue();
float kinetic_energy = b_kinetic_energy->GetLeaf("tr_kinetic_energy")->GetValue();
float mcs_mom_muon = b_mcs_mom_muon->GetLeaf("tr_mcs_mom_muon")->GetValue();
float range_mom_muon = b_range_mom_muon->GetLeaf("tr_range_mom_muon")->GetValue();
float range_mom_proton = b_range_mom_proton->GetLeaf("tr_range_mom_proton")->GetValue();
TVector3 vertex(temp_vertex);
TVector3 end(temp_end);
float vertex_x = temp_vertex[0];
float vertex_y = temp_vertex[1];
float vertex_z = temp_vertex[2];
float end_x = temp_end[0];
float end_y = temp_end[1];
float end_z = temp_end[2];
// Co-ordinate offset in cm
int sbnd_length_x = 400;
int sbnd_length_y = 400;
int sbnd_length_z = 500;
int sbnd_offset_x = 200;
int sbnd_offset_y = 200;
int sbnd_offset_z = 0;
int sbnd_border_x = 10;
int sbnd_border_y = 20;
int sbnd_border_z = 10;
bool not_contained =
( (vertex_x > (sbnd_length_x - sbnd_offset_x))
|| (vertex_x < (-sbnd_offset_x))
|| (vertex_y > (sbnd_length_y - sbnd_offset_y))
|| (vertex_y < (-sbnd_offset_y + sbnd_border_y))
|| (vertex_z > (sbnd_length_z - sbnd_offset_z))
|| (vertex_z < (-sbnd_offset_z))
|| (end_x > (sbnd_length_x - sbnd_offset_x))
|| (end_x < (-sbnd_offset_x))
|| (end_y > (sbnd_length_y - sbnd_offset_y))
|| (end_y < (-sbnd_offset_y))
|| (end_z > (sbnd_length_z - sbnd_offset_z))
|| (end_z < (-sbnd_offset_z)));
bool does_vtx_escape =
( (vertex_x > (sbnd_length_x - sbnd_offset_x))
|| (vertex_x < (-sbnd_offset_x))
|| (vertex_y > (sbnd_length_y - sbnd_offset_y))
|| (vertex_y < (-sbnd_offset_y + sbnd_border_y))
|| (vertex_z > (sbnd_length_z - sbnd_offset_z))
|| (vertex_z < (-sbnd_offset_z)));
bool does_end_escape =
( (end_x > (sbnd_length_x - sbnd_offset_x))
|| (end_x < (-sbnd_offset_x))
|| (end_y > (sbnd_length_y - sbnd_offset_y))
|| (end_y < (-sbnd_offset_y))
|| (end_z > (sbnd_length_z - sbnd_offset_z))
|| (end_z < (-sbnd_offset_z)));
bool one_end_escapes = true;
if(does_vtx_escape && does_end_escape) one_end_escapes = false;
if(!does_vtx_escape && !does_end_escape) one_end_escapes = false;
track_list.push_back(Track(id_charge, id_energy, id_hits, n_hits, pida, chi2_mu, chi2_pi, chi2_pr, chi2_ka, length, kinetic_energy, mcs_mom_muon, range_mom_muon, range_mom_proton,vertex, end, !not_contained, one_end_escapes));
}
}
//------------------------------------------------------------------------------------------
void EventSelectionTool::GetShowerList(unsigned int start, TTree *shower_tree, const std::pair<int, int> &unique_event, ShowerList &shower_list){
TBranch *b_event_id = shower_tree->GetBranch("event_id");
TBranch *b_time_now = shower_tree->GetBranch("time_now");
TBranch *b_n_hits = shower_tree->GetBranch("sh_n_hits");
TBranch *b_vertex = shower_tree->GetBranch("sh_start");
TBranch *b_direction = shower_tree->GetBranch("sh_direction");
TBranch *b_open_angle = shower_tree->GetBranch("sh_open_angle");
TBranch *b_length = shower_tree->GetBranch("sh_length");
TBranch *b_energy = shower_tree->GetBranch("sh_energy");
unsigned int n_entries = shower_tree->GetEntries();
for(unsigned int i = 0; i < n_entries; ++i){
shower_tree->GetEntry(i);
int event_id = b_event_id->GetLeaf("event_id")->GetValue();
int time_now = b_time_now->GetLeaf("time_now")->GetValue();
if(event_id != unique_event.first || time_now != unique_event.second) continue;
double temp_vertex[3];
double temp_direction[3];
temp_vertex[0] = b_vertex->GetLeaf("sh_start")->GetValue(0);
temp_vertex[1] = b_vertex->GetLeaf("sh_start")->GetValue(1);
temp_vertex[2] = b_vertex->GetLeaf("sh_start")->GetValue(2);
temp_direction[0] = b_direction->GetLeaf("sh_direction")->GetValue(0);
temp_direction[1] = b_direction->GetLeaf("sh_direction")->GetValue(1);
temp_direction[2] = b_direction->GetLeaf("sh_direction")->GetValue(2);
float open_angle = b_open_angle->GetLeaf("sh_open_angle")->GetValue();
float length = b_length->GetLeaf("sh_length")->GetValue();
float energy = b_energy->GetLeaf("sh_energy")->GetValue();
int n_hits = b_n_hits->GetLeaf("sh_n_hits")->GetValue();
TVector3 vertex(temp_vertex);
TVector3 direction(temp_direction);
shower_list.push_back(Shower(n_hits, vertex, direction, open_angle, length, energy));
}
}
//------------------------------------------------------------------------------------------
void EventSelectionTool::GetMCParticleList(unsigned int start, TTree *mcparticle_tree, const std::pair<int, int> &unique_event, ParticleList &mcparticle_list){
TBranch *b_event_id = mcparticle_tree->GetBranch("event_id");
TBranch *b_time_now = mcparticle_tree->GetBranch("time_now");
TBranch *b_id = mcparticle_tree->GetBranch("p_id");
TBranch *b_n_hits = mcparticle_tree->GetBranch("p_n_hits");
TBranch *b_pdgcode = mcparticle_tree->GetBranch("p_pdgcode");
TBranch *b_status = mcparticle_tree->GetBranch("p_status");
TBranch *b_mass = mcparticle_tree->GetBranch("p_mass");
TBranch *b_energy = mcparticle_tree->GetBranch("p_energy");
TBranch *b_vertex = mcparticle_tree->GetBranch("p_vertex");
TBranch *b_end = mcparticle_tree->GetBranch("p_end");
TBranch *b_momentum = mcparticle_tree->GetBranch("p_momentum");
unsigned int n_entries = mcparticle_tree->GetEntries();
for(unsigned int i = 0; i < n_entries; ++i){
mcparticle_tree->GetEntry(i);
int event_id = b_event_id->GetLeaf("event_id")->GetValue();
int time_now = b_time_now->GetLeaf("time_now")->GetValue();
if(event_id != unique_event.first || time_now != unique_event.second) continue;
double temp_vertex[3];
double temp_end[3];
double temp_momentum[3];
int id = b_id->GetLeaf("p_id")->GetValue();
int pdgcode = b_pdgcode->GetLeaf("p_pdgcode")->GetValue();
int statuscode = b_status->GetLeaf("p_status")->GetValue();
int n_hits = b_n_hits->GetLeaf("p_n_hits")->GetValue();
float mass = b_mass->GetLeaf("p_mass")->GetValue();
float energy = b_energy->GetLeaf("p_energy")->GetValue();
temp_vertex[0] = b_vertex->GetLeaf("p_vertex")->GetValue(0);
temp_vertex[1] = b_vertex->GetLeaf("p_vertex")->GetValue(1);
temp_vertex[2] = b_vertex->GetLeaf("p_vertex")->GetValue(2);
temp_end[0] = b_end->GetLeaf("p_end")->GetValue(0);
temp_end[1] = b_end->GetLeaf("p_end")->GetValue(1);
temp_end[2] = b_end->GetLeaf("p_end")->GetValue(2);
temp_momentum[0] = b_momentum->GetLeaf("p_momentum")->GetValue(0);
temp_momentum[1] = b_momentum->GetLeaf("p_momentum")->GetValue(1);
temp_momentum[2] = b_momentum->GetLeaf("p_momentum")->GetValue(2);
TVector3 vertex(temp_vertex);
TVector3 end(temp_end);
TVector3 momentum(temp_momentum);
mcparticle_list.push_back(Particle(id, pdgcode, statuscode, n_hits, mass, energy, vertex, end, momentum));
}
}
//------------------------------------------------------------------------------------------
void EventSelectionTool::GetRecoParticleFromTrackRaquel(const TrackList &track_list, ParticleList &recoparticle_list){
// Assign ridiculously short length to initiate the longest track length
float longest_track_length = -std::numeric_limits<float>::max();
unsigned int longest_track_id = std::numeric_limits<unsigned int>::max();
// Get the longest track id
for(unsigned int i = 0; i < track_list.size(); ++i){
const Track &candidate(track_list[i]);
// Get the lengths of the tracks and find the longest track and compare to the rest of
// the lengths
if(candidate.m_length > longest_track_length) {
longest_track_length = candidate.m_length;
longest_track_id = i;
}
}
bool always_longest(true);
// Loop over track list
for(unsigned int id = 0; id < track_list.size(); ++id){
// Find out if the longest track is always 1.5x longer than all the others in the event
const Track &track(track_list[id]);
if(track.m_length*1.5 >= longest_track_length && id != longest_track_id) always_longest = false;
}
// Muon candidates
std::vector<unsigned int> mu_candidates;
// Check if exactly 1 track escapes and that it is the longest track
bool only_longest_escapes = false;
bool none_escape = true;
bool longest_escapes = false;
unsigned int n_escaping = 0;
for(unsigned int i = 0; i < track_list.size(); ++i){
const Track &trk(track_list[i]);
if(i == longest_track_id) longest_escapes = true;
if(trk.m_one_end_contained) n_escaping++;
}
if(n_escaping == 1 && longest_escapes) only_longest_escapes = true;
if(n_escaping != 0) none_escape = false;
// Loop over track list
for(unsigned int id = 0; id < track_list.size(); ++id){
const Track &track(track_list[id]);
// If exactly one particle escapes, call it the muon
// Then identify protons
// Then everything else
if(only_longest_escapes){
if(track.m_one_end_contained)
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, 13, track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
else if(EventSelectionTool::GetProtonByChi2Proton(track) == 2212)
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, 2212, track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
else
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, EventSelectionTool::GetPdgByChi2(track), track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
}
else if(!none_escape) continue;
else{
// If the Chi2 Proton hypothesis gives proton, call the track a proton
// Otherwise, call it a muon candidate
if(EventSelectionTool::GetProtonByChi2Proton(track) == 2212)
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, 2212, track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
else if(EventSelectionTool::GetMuonByChi2Proton(track) == 13 || (id == longest_track_id && always_longest) || track.m_one_end_contained)
mu_candidates.push_back(id);
else
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, EventSelectionTool::GetPdgByChi2(track), track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
}
}
// If the muon was found by length, this will return
if(mu_candidates.size() == 0) return;
if(mu_candidates.size() == 1) {
const Track &muon(track_list[mu_candidates[0]]);
recoparticle_list.push_back(Particle(muon.m_mc_id_charge, muon.m_mc_id_energy, muon.m_mc_id_hits, 13, muon.m_n_hits, muon.m_kinetic_energy, muon.m_mcs_mom_muon, muon.m_range_mom_muon, muon.m_range_mom_proton, muon.m_length, muon.m_vertex, muon.m_end, muon.m_chi2_pr, muon.m_chi2_mu, muon.m_chi2_pi));
return;
}
// If more than one muon candidate exists
bool foundTheMuon(false);
unsigned int muonID = std::numeric_limits<unsigned int>::max();
for(unsigned int i = 0; i < mu_candidates.size(); ++i){
unsigned int id = mu_candidates[i];
const Track &candidate(track_list[id]);
if(longest_track_id == id && always_longest) {
muonID = id;
foundTheMuon = true;
break;
}
}
if(!foundTheMuon) {
// Find the smallest chi^2 under the muon hypothesis
muonID = EventSelectionTool::GetMuonByChi2(track_list, mu_candidates);
if(muonID != std::numeric_limits<unsigned int>::max()) foundTheMuon = true;
else throw 10;
}
const Track &muon(track_list[muonID]);
recoparticle_list.push_back(Particle(muon.m_mc_id_charge, muon.m_mc_id_energy, muon.m_mc_id_hits, 13, muon.m_n_hits, muon.m_kinetic_energy, muon.m_mcs_mom_muon, muon.m_range_mom_muon, muon.m_range_mom_proton, muon.m_length, muon.m_vertex, muon.m_end, muon.m_chi2_pr, muon.m_chi2_mu, muon.m_chi2_pi));
for(unsigned int id = 0; id < mu_candidates.size(); ++id){
if(id == muonID) continue;
const Track &track(track_list[id]);
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, EventSelectionTool::GetPdgByChi2(track), track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
}
}
//------------------------------------------------------------------------------------------
void EventSelectionTool::GetRecoParticleFromTrackChi2P(const TrackList &track_list, ParticleList &recoparticle_list){
// Assign ridiculously short length to initiate the longest track length
float longest_track_length = -std::numeric_limits<float>::max();
unsigned int longest_track_id = std::numeric_limits<unsigned int>::max();
// Check if exactly 1 track escapes
bool exactly_one_escapes = false;
unsigned int n_escaping = 0;
for(unsigned int i = 0; i < track_list.size(); ++i){
const Track &trk(track_list[i]);
if(trk.m_one_end_contained) n_escaping++;
}
if(n_escaping == 1) exactly_one_escapes = true;
for(unsigned int i = 0; i < track_list.size(); ++i){
const Track &candidate(track_list[i]);
// Get the lengths of the tracks and find the longest track and compare to the rest of
// the lengths
if(candidate.m_length > longest_track_length) {
longest_track_length = candidate.m_length;
longest_track_id = i;
}
}
bool always_longest(true);
// Loop over track list
for(unsigned int id = 0; id < track_list.size(); ++id){
// Find out if the longest track is always 1.5x longer than all the others in the event
const Track &track(track_list[id]);
if(track.m_length*1.5 >= longest_track_length && id != longest_track_id) always_longest = false;
}
// Muon candidates
std::vector<unsigned int> mu_candidates;
// Loop over track list
for(unsigned int id = 0; id < track_list.size(); ++id){
const Track &track(track_list[id]);
// If exactly one particle escapes, call it the muon
// Then identify protons
// Then everything else
if(exactly_one_escapes){
if(track.m_one_end_contained)
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, 13, track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
else if(EventSelectionTool::GetProtonByChi2Proton(track) == 2212)
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, 2212, track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
else
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, EventSelectionTool::GetPdgByChi2(track), track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
}
else{
// If the Chi2 Proton hypothesis gives proton, call the track a proton
// Otherwise, call it a muon candidate
if(EventSelectionTool::GetProtonByChi2Proton(track) == 2212)
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, 2212, track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
else if(EventSelectionTool::GetMuonByChi2Proton(track) == 13 || (id == longest_track_id && always_longest) || track.m_one_end_contained)
mu_candidates.push_back(id);
else
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, EventSelectionTool::GetPdgByChi2(track), track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
}
}
// If the muon was found by length, this will return
if(mu_candidates.size() == 0) return;
if(mu_candidates.size() == 1) {
const Track &muon(track_list[mu_candidates[0]]);
recoparticle_list.push_back(Particle(muon.m_mc_id_charge, muon.m_mc_id_energy, muon.m_mc_id_hits, 13, muon.m_n_hits, muon.m_kinetic_energy, muon.m_mcs_mom_muon, muon.m_range_mom_muon, muon.m_range_mom_proton, muon.m_length, muon.m_vertex, muon.m_end, muon.m_chi2_pr, muon.m_chi2_mu, muon.m_chi2_pi));
return;
}
// If more than one muon candidate exists
bool foundTheMuon(false);
unsigned int muonID = std::numeric_limits<unsigned int>::max();
for(unsigned int i = 0; i < mu_candidates.size(); ++i){
unsigned int id = mu_candidates[i];
const Track &candidate(track_list[id]);
if(longest_track_id == id && always_longest) {
muonID = id;
foundTheMuon = true;
break;
}
}
if(!foundTheMuon) {
// Find the smallest chi^2 under the muon hypothesis
muonID = EventSelectionTool::GetMuonByChi2(track_list, mu_candidates);
if(muonID != std::numeric_limits<unsigned int>::max()) foundTheMuon = true;
else throw 10;
}
const Track &muon(track_list[muonID]);
recoparticle_list.push_back(Particle(muon.m_mc_id_charge, muon.m_mc_id_energy, muon.m_mc_id_hits, 13, muon.m_n_hits, muon.m_kinetic_energy, muon.m_mcs_mom_muon, muon.m_range_mom_muon, muon.m_range_mom_proton, muon.m_length, muon.m_vertex, muon.m_end, muon.m_chi2_pr, muon.m_chi2_mu, muon.m_chi2_pi));
for(unsigned int id = 0; id < mu_candidates.size(); ++id){
if(id == muonID) continue;
const Track &track(track_list[id]);
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, EventSelectionTool::GetPdgByChi2(track), track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
}
}
//------------------------------------------------------------------------------------------
void EventSelectionTool::GetRecoParticleFromTrack1Escaping(const TrackList &track_list, ParticleList &recoparticle_list){
// Assign ridiculously short length to initiate the longest track length
float longest_track_length = -std::numeric_limits<float>::max();
unsigned int longest_track_id = std::numeric_limits<unsigned int>::max();
// Check if exactly 1 track escapes
bool exactly_one_escapes = false;
unsigned int n_escaping = 0;
for(unsigned int i = 0; i < track_list.size(); ++i){
const Track &trk(track_list[i]);
if(trk.m_one_end_contained) n_escaping++;
}
if(n_escaping == 1) exactly_one_escapes = true;
for(unsigned int i = 0; i < track_list.size(); ++i){
const Track &candidate(track_list[i]);
// Get the lengths of the tracks and find the longest track and compare to the rest of
// the lengths
if(candidate.m_length > longest_track_length) {
longest_track_length = candidate.m_length;
longest_track_id = i;
}
}
bool always_longest(true);
// Loop over track list
for(unsigned int id = 0; id < track_list.size(); ++id){
// Find out if the longest track is always 1.5x longer than all the others in the event
const Track &track(track_list[id]);
if(track.m_length*1.5 >= longest_track_length && id != longest_track_id) always_longest = false;
}
// Muon candidates
std::vector<unsigned int> mu_candidates;
// Loop over track list
for(unsigned int id = 0; id < track_list.size(); ++id){
const Track &track(track_list[id]);
// If exactly one particle escapes, call it the muon
// Then identify protons
// Then everything else
if(exactly_one_escapes){
if(track.m_one_end_contained)
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, 13, track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
else if(EventSelectionTool::GetProtonByChi2Proton(track) == 2212)
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, 2212, track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
else
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, EventSelectionTool::GetPdgByChi2(track), track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
}
else{
// If the Chi2 Proton hypothesis gives proton, call the track a proton
// Otherwise, call it a muon candidate
if(EventSelectionTool::GetProtonByChi2Proton(track) == 2212)
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, 2212, track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
else if(EventSelectionTool::GetPdgByChi2MuonCandidate(track) == 13 || (id == longest_track_id && always_longest))
mu_candidates.push_back(id);
else
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, EventSelectionTool::GetPdgByChi2(track), track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
}
}
// If the muon was found by length, this will return
if(mu_candidates.size() == 0) return;
if(mu_candidates.size() == 1) {
const Track &muon(track_list[mu_candidates[0]]);
recoparticle_list.push_back(Particle(muon.m_mc_id_charge, muon.m_mc_id_energy, muon.m_mc_id_hits, 13, muon.m_n_hits, muon.m_kinetic_energy, muon.m_mcs_mom_muon, muon.m_range_mom_muon, muon.m_range_mom_proton, muon.m_length, muon.m_vertex, muon.m_end, muon.m_chi2_pr, muon.m_chi2_mu, muon.m_chi2_pi));
return;
}
// If more than one muon candidate exists
bool foundTheMuon(false);
unsigned int muonID = std::numeric_limits<unsigned int>::max();
for(unsigned int i = 0; i < mu_candidates.size(); ++i){
unsigned int id = mu_candidates[i];
const Track &candidate(track_list[id]);
if(longest_track_id == id && always_longest) {
muonID = id;
foundTheMuon = true;
break;
}
}
if(!foundTheMuon) {
// Find the smallest chi^2 under the muon hypothesis
muonID = EventSelectionTool::GetMuonByChi2(track_list, mu_candidates);
if(muonID != std::numeric_limits<unsigned int>::max()) foundTheMuon = true;
else throw 10;
}
const Track &muon(track_list[muonID]);
recoparticle_list.push_back(Particle(muon.m_mc_id_charge, muon.m_mc_id_energy, muon.m_mc_id_hits, 13, muon.m_n_hits, muon.m_kinetic_energy, muon.m_mcs_mom_muon, muon.m_range_mom_muon, muon.m_range_mom_proton, muon.m_length, muon.m_vertex, muon.m_end, muon.m_chi2_pr, muon.m_chi2_mu, muon.m_chi2_pi));
for(unsigned int id = 0; id < mu_candidates.size(); ++id){
if(id == muonID) continue;
const Track &track(track_list[id]);
recoparticle_list.push_back(Particle(track.m_mc_id_charge, track.m_mc_id_energy, track.m_mc_id_hits, EventSelectionTool::GetPdgByChi2(track), track.m_n_hits, track.m_kinetic_energy, track.m_mcs_mom_muon, track.m_range_mom_muon, track.m_range_mom_proton, track.m_length, track.m_vertex, track.m_end, track.m_chi2_pr, track.m_chi2_mu, track.m_chi2_pi));
}
}
//------------------------------------------------------------------------------------------
void EventSelectionTool::GetRecoParticleFromShower(const ShowerList &shower_list, const TVector3 &reco_vertex, ParticleList &recoparticle_list){
// To start with,
// If an event has 2 showers
// Push back a pi0 at that point
//if(shower_list.size() == 2) recoparticle_list.push_back(Particle(111,reco_vertex,reco_vertex));
// New method
// Calculate distance of closest approach between 2 photon showers
// There must be at least 2 showers
if(shower_list.size() <= 2) return;
std::vector<unsigned int> used_photon;
used_photon.clear();
// Loop over showers
for(unsigned int i = 0; i < shower_list.size(); ++i){
// Vector to hold 'j' values of candidate photon to pair with current photon
// Vector to hold to position at which the photons meet to call it the point at which
// the pi0 decayed
// Vector to hold the distance of closest approach, in order to minimise this
std::vector<unsigned int> candidate_id_for_pair;
std::vector<TVector3> decay_point;
std::vector<float> c_distance;
std::vector<int> total_hits;
candidate_id_for_pair.clear();
decay_point.clear();
c_distance.clear();
total_hits.clear();
for( unsigned int j = i+1; j < shower_list.size(); ++j){
// If we are only looking at a single photon, continue
if(i==j) continue;
// If the photon has already been assigned to a pi0
for(unsigned int k = 0; k < used_photon.size(); ++k) if(used_photon[k] == j) continue;
// Get the distance of closest approach of the current two showers we are looking at
TVector3 dir_1, dir_2, start_1, start_2, link;
dir_1 = shower_list[i].m_direction;
dir_2 = shower_list[j].m_direction;
start_1 = shower_list[i].m_vertex;
start_2 = shower_list[j].m_vertex;
link = start_1 - start_2;
float a = dir_1.Dot(dir_1);
float b = dir_1.Dot(dir_2);
float c = dir_2.Dot(dir_2);
float d = dir_1.Dot(link);
float e = dir_2.Dot(link);
float denomenator = a*c - b*b;
// Get the invariant mass of the current 2 showers
float energy_1 = shower_list[i].m_energy;
float energy_2 = shower_list[j].m_energy;
float cos_theta = (b / (std::sqrt(a)*std::sqrt(c)));
float inv_mass = std::sqrt(2*energy_1*energy_2*(1-cos_theta));
float pi0_mass = 134.97; // MeV
// If the lines are parallel
if(denomenator == 0) continue;
float m_closest = (b*e - c*d)/denomenator;
float n_closest = (a*e - b*d)/denomenator;
TVector3 d_closest = link + ((b*e - c*d)*dir_1 - (a*e - b*d)*dir_2)*(1/denomenator);
float mag_d_closest = d_closest.Mag();
TVector3 d_middle = (start_1 + m_closest*dir_1) + 0.5*d_closest;
// If the distance of closest approach is smaller than 15 cm call it a candidate
if(mag_d_closest < 15) {
candidate_id_for_pair.push_back(j);
decay_point.push_back(d_closest);
c_distance.push_back(mag_d_closest);
total_hits.push_back(shower_list[i].m_n_hits + shower_list[j].m_n_hits);
}
}
if(candidate_id_for_pair.size() == 0) continue;
if(candidate_id_for_pair.size() == 1){
// If the location with respect to the neutrino vertex at which the photons
// were produced by the candidate pi0 is more than 15 cm continue
if((reco_vertex - decay_point[0]).Mag() > 15) continue;
// push back a pi0 corresponding to the two photons
recoparticle_list.push_back(Particle(111, total_hits[0], reco_vertex,decay_point[0]));
}
else{
// Find the minimum distance
std::vector<float>::iterator min = std::min_element(c_distance.begin(), c_distance.end());
TVector3 best_decay_point = decay_point[std::distance(c_distance.begin(), min)];
int best_total_hits = total_hits[std::distance(c_distance.begin(), min)];
recoparticle_list.push_back(Particle(111,best_total_hits, reco_vertex, best_decay_point));
used_photon.push_back(candidate_id_for_pair[std::distance(c_distance.begin(), min)]);
}
}
}
//------------------------------------------------------------------------------------------
int EventSelectionTool::GetPdgByChi2(const Track &track){
// Push the chi2 values onto a vector to find the minimum
// NOT MUON
std::map<int, float> chi2_map;
chi2_map.insert(std::map<int, float>::value_type(211, track.m_chi2_pi));
chi2_map.insert(std::map<int, float>::value_type(321, track.m_chi2_ka));
chi2_map.insert(std::map<int, float>::value_type(2212, track.m_chi2_pr));
float min_chi2 = std::numeric_limits<float>::max();
int best_pdg = std::numeric_limits<int>::max();
for(std::map<int, float>::const_iterator it = chi2_map.begin(); it != chi2_map.end(); ++it){
if(it->second < min_chi2){
min_chi2 = it->second;
best_pdg = it->first;
}
}
return best_pdg;
}
//------------------------------------------------------------------------------------------
int EventSelectionTool::GetMuonByChi2(const TrackList &tracks, const std::vector<unsigned int> &mu_candidates){
// Loop over muon candidates and find smallest corresponding chi2_mu
float min_chi2_mu = std::numeric_limits<float>::max();
unsigned int min_chi2_id = std::numeric_limits<unsigned int>::max();
// Find the smallest chi^2 under the muon hypothesis
for(unsigned int i = 0; i < mu_candidates.size(); ++i){
unsigned int id = mu_candidates[i];
const Track &candidate(tracks[id]);
if(candidate.m_chi2_mu < min_chi2_mu) {
min_chi2_mu = candidate.m_chi2_mu;
min_chi2_id = id;
}
}
return min_chi2_id;
}
//------------------------------------------------------------------------------------------
int EventSelectionTool::GetProtonByChi2Proton(const Track &track){
// Limit based on particle gun plots of muon and proton vs proton chi^2
if(track.m_chi2_pr < 80) return 2212;
return std::numeric_limits<int>::max();
}
//------------------------------------------------------------------------------------------
int EventSelectionTool::GetMuonByChi2Proton(const Track &track){
// Limit based on particle gun plots of muon and proton vs proton chi^2
if(track.m_chi2_pr > 80) return 13;
return std::numeric_limits<int>::max();
}
//------------------------------------------------------------------------------------------
int EventSelectionTool::GetPdgByChi2MuonCandidate(const Track &track){
// Limit based on particle gun plots of muon and proton vs proton chi^2
if(track.m_chi2_mu < 16) return 13;
return std::numeric_limits<int>::max();
}
//------------------------------------------------------------------------------------------
int EventSelectionTool::GetPdgByPIDA(const Track &track){
// Muon
if(track.m_pida >= 5 && track.m_pida < 9) return 13;
//Pion
if(track.m_pida >= 9 && track.m_pida < 13) return 211;
//Kaon
if(track.m_pida >= 13 && track.m_pida < 13.5) return 321;
//Proton
if(track.m_pida >= 13) return 2212;
return std::numeric_limits<int>::max();
}
//------------------------------------------------------------------------------------------
int EventSelectionTool::GetPdgByPIDAStrict(const Track &track){
// Muon
if(track.m_pida >= 7.5 && track.m_pida < 8) return 13;
//Pion
if(track.m_pida >= 8 && track.m_pida < 9) return 211;
//Kaon
if(track.m_pida >= 12.9 && track.m_pida < 13.5) return 321;
//Proton
if(track.m_pida >= 16.9 && track.m_pida < 17.4) return 2212;
return std::numeric_limits<int>::max();
}
//------------------------------------------------------------------------------------------
EventSelectionTool::Track::Track(const int mc_id_charge, const int mc_id_energy, const int mc_id_hits, const int n_hits, const float pida, const float chi2_mu, const float chi2_pi, const float chi2_pr, const float chi2_ka, const float length, const float kinetic_energy, const float mcs_momentum_muon, const float range_momentum_muon, const float range_momentum_proton, const TVector3 &vertex, const TVector3 &end, const bool &contained, const bool &one_end_contained) :
m_mc_id_charge(mc_id_charge),
m_mc_id_energy(mc_id_energy),
m_mc_id_hits(mc_id_hits),
m_n_hits(n_hits),
m_pida(pida),
m_chi2_mu(chi2_mu),
m_chi2_pi(chi2_pi),
m_chi2_pr(chi2_pr),
m_chi2_ka(chi2_ka),
m_length(length),
m_kinetic_energy(kinetic_energy),
m_mcs_mom_muon(mcs_momentum_muon),
m_range_mom_muon(range_momentum_muon),
m_range_mom_proton(range_momentum_proton),
m_vertex(vertex),
m_end(end),
m_contained(contained),
m_one_end_contained(one_end_contained){}
//------------------------------------------------------------------------------------------
EventSelectionTool::Shower::Shower(const int n_hits, const TVector3 &vertex, const TVector3 &direction, const float open_angle, const float length, const float energy) :
m_n_hits(n_hits),
m_vertex(vertex),
m_direction(direction),
m_open_angle(open_angle),
m_length(length),
m_energy(energy/3.) {}
} // namespace: ana
| 49.350526 | 472 | 0.64533 | RhiannonSJ |
e0b58b8e7b4e7c38891ee522dd0fed15f48fc20d | 2,520 | cpp | C++ | profiling/lab_memory/mailparser.cpp | allstarschh/training-handout | 86b16316e99ed5c1c7bc8dbb0a77dcf49c7e0a57 | [
"BSD-3-Clause-Clear"
] | null | null | null | profiling/lab_memory/mailparser.cpp | allstarschh/training-handout | 86b16316e99ed5c1c7bc8dbb0a77dcf49c7e0a57 | [
"BSD-3-Clause-Clear"
] | null | null | null | profiling/lab_memory/mailparser.cpp | allstarschh/training-handout | 86b16316e99ed5c1c7bc8dbb0a77dcf49c7e0a57 | [
"BSD-3-Clause-Clear"
] | null | null | null | /*************************************************************************
*
* Copyright (c) 2016-2019, Klaralvdalens Datakonsult AB (KDAB)
* All rights reserved.
*
* See the LICENSE.txt file shipped along with this file for the license.
*
*************************************************************************/
#include "mailparser.h"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cmath>
namespace {
bool startsWith(std::string haystack, std::string needle)
{
// the needle may be larger than the haystack, so let's be super safe here
// step 1: allocate zero-initialized buffer, which is "large enough"
const int BUF_SIZE = 1024;
auto* buf = calloc(1, BUF_SIZE);
// step 2: copy the first characters from the haystack into the buffer
memcpy(buf, haystack.c_str(), std::min(haystack.size(), needle.size()));
// step 3: compare the buffer against the needle
return memcmp(buf, needle.c_str(), needle.size()) == 0;
}
void countWords(const std::string& line, Mail &mail)
{
std::istringstream iss(line);
std::string word;
while (std::getline(iss, word, ' ')) {
if (word.empty()) {
continue;
}
if (mail.wordCount.find(word) == mail.wordCount.end()) {
++mail.words;
}
mail.wordCount[word]++;
}
}
}
MailParser::MailParser()
{
}
MailList MailParser::parse(const std::string& filePath)
{
MailList mails;
std::ifstream stream;
stream.open(filePath);
if (!stream.is_open()) {
std::cerr << "Failed to parse mail file " << filePath << '\n';
return mails;
}
unsigned mailsByMilian = 0;
Mail currentMail;
while (true) {
std::string line;
if (!std::getline(stream, line)) {
break;
}
countWords(line, currentMail);
if (startsWith(line, "From: ")) {
currentMail.from = line.substr(6);
}
if (startsWith(line, "Date: ")) {
currentMail.dateTime = line.substr(6);
}
if (startsWith(line, "Subject: ")) {
currentMail.subject = line.substr(9);
currentMail.validate();
mails.push_back(currentMail);
currentMail = {};
}
if (startsWith(line, "From: milian.wolff at kdab.com (Milian Wolff)")) {
++mailsByMilian;
}
}
std::cout << mailsByMilian << " written by Milian" << std::endl;
return mails;
}
| 25.979381 | 80 | 0.554762 | allstarschh |
e0b986da1c0b083c7369f2e58ef2d2eef4d85e3f | 877 | cpp | C++ | Src/system-helper.cpp | savent404/MX-F411RE | 4e3705cfcca3dd382cea2dfa66cdc3bb3d061f11 | [
"MIT"
] | null | null | null | Src/system-helper.cpp | savent404/MX-F411RE | 4e3705cfcca3dd382cea2dfa66cdc3bb3d061f11 | [
"MIT"
] | null | null | null | Src/system-helper.cpp | savent404/MX-F411RE | 4e3705cfcca3dd382cea2dfa66cdc3bb3d061f11 | [
"MIT"
] | 1 | 2020-09-01T22:02:33.000Z | 2020-09-01T22:02:33.000Z | #include "textHelper.h"
#include "mbed.h"
#include <queue>
static Semaphore event_sem;
static Mutex event_mutex;
static queue<uint32_t> event_queue;
bool defaultEventSender(uint32_t message)
{
event_mutex.lock();
event_queue.push(message);
event_mutex.unlock();
event_sem.release();
return true;
}
bool defaultEventReciver(uint32_t& message, uint32_t timeout)
{
if (event_sem.wait() != 0)
return false;
event_mutex.lock();
message = event_queue.front();
event_queue.pop();
event_mutex.unlock();
return true;
}
void mDebug(int level, const char* str, ...)
{
static char buffer[512];
va_list aptr;
int cnt;
va_start(aptr, str);
cnt = sprintf(buffer, ":%d ", level);
cnt += vsprintf(buffer + cnt, str, aptr);
cnt += sprintf(buffer, "\r\n", buffer + cnt);
va_end(aptr);
debug(buffer);
}
| 20.395349 | 61 | 0.652223 | savent404 |
e0ba76ecb912c7d077e06d82a0aac50ef4f7e62e | 167 | hpp | C++ | src/ctti/ctti_fwd.hpp | PiotrMoscicki/s4_rtti | 8d22f42f84eb0a831b2472349d2d97b4cb351e07 | [
"MIT"
] | null | null | null | src/ctti/ctti_fwd.hpp | PiotrMoscicki/s4_rtti | 8d22f42f84eb0a831b2472349d2d97b4cb351e07 | [
"MIT"
] | 3 | 2021-12-18T16:50:24.000Z | 2021-12-18T16:53:54.000Z | src/ctti/ctti_fwd.hpp | PiotrMoscicki/s4_rtti | 8d22f42f84eb0a831b2472349d2d97b4cb351e07 | [
"MIT"
] | null | null | null | #pragma once
namespace ctti {
template <typename TYPE>
constexpr auto constexpr_type() { return TYPE::template constexpr_type<TYPE>(); }
} // namespace ctti | 20.875 | 85 | 0.712575 | PiotrMoscicki |
e0c94576f9e265927a6c6bbdc0809dc3d6bdfb44 | 1,995 | cpp | C++ | AdvancedGraphics/texture.cpp | Trodek/Advanced-Graphics-Subject | 5e89fa33a3bc5c4e0910cfae907a22f879be035a | [
"MIT"
] | null | null | null | AdvancedGraphics/texture.cpp | Trodek/Advanced-Graphics-Subject | 5e89fa33a3bc5c4e0910cfae907a22f879be035a | [
"MIT"
] | null | null | null | AdvancedGraphics/texture.cpp | Trodek/Advanced-Graphics-Subject | 5e89fa33a3bc5c4e0910cfae907a22f879be035a | [
"MIT"
] | null | null | null | #include "texture.h"
#include "appmanager.h"
#include "openglwidget.h"
#include <iostream>
#include <QFile>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
Texture::Texture() : Resource(Resource::Type::Texture)
{
}
void Texture::loadFromFile(QString path)
{
AppManager::Instance()->GetOpenGLWidget()->MakeCurrent();
this->name = ResourceManager::Instance()->GetNameFrom(path.toStdString()).c_str();
this->path = ResourceManager::Instance()->GetPathFrom(path.toStdString()).c_str();
AppManager::Instance()->GetOpenGLWidget()->glGenTextures(1,&id);
int width, height, nrComponents;
unsigned char* data = stbi_load(path.toStdString().c_str(),&width,&height,&nrComponents,0);
if(data != nullptr)
{
GLenum format;
if(nrComponents == 1)
format = GL_RED;
if(nrComponents == 3)
format = GL_RGB;
if(nrComponents == 4)
format = GL_RGBA;
AppManager::Instance()->GetOpenGLWidget()->glBindTexture(GL_TEXTURE_2D,id);
AppManager::Instance()->GetOpenGLWidget()->glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
AppManager::Instance()->GetOpenGLWidget()->glGenerateMipmap(GL_TEXTURE_2D);
AppManager::Instance()->GetOpenGLWidget()->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
AppManager::Instance()->GetOpenGLWidget()->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
AppManager::Instance()->GetOpenGLWidget()->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
AppManager::Instance()->GetOpenGLWidget()->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
AppManager::Instance()->GetOpenGLWidget()->glBindTexture(GL_TEXTURE_2D, 0);
stbi_image_free(data);
}
else
{
std::cout << "Error loading textur with path: " << path.toStdString() << std::endl;
stbi_image_free(data);
}
}
| 36.944444 | 140 | 0.688722 | Trodek |
e0cb34fb501513fc9aebdb99e42889d3e5aee926 | 17,974 | hpp | C++ | include/qtl_mysql.hpp | wyyrepo/qtl | ab9dec8671eeb90230064474cf86c49c69fd8e10 | [
"Apache-2.0"
] | 1 | 2022-03-26T08:24:12.000Z | 2022-03-26T08:24:12.000Z | include/qtl_mysql.hpp | wyyrepo/qtl | ab9dec8671eeb90230064474cf86c49c69fd8e10 | [
"Apache-2.0"
] | null | null | null | include/qtl_mysql.hpp | wyyrepo/qtl | ab9dec8671eeb90230064474cf86c49c69fd8e10 | [
"Apache-2.0"
] | null | null | null | #ifndef _MYDTL_MYSQL_H_
#define _MYDTL_MYSQL_H_
#include <mysql.h>
#include <errmsg.h>
#include <time.h>
#include <memory.h>
#include <assert.h>
#include <stdint.h>
#include <string>
#include <vector>
#include <array>
#include <functional>
#include <algorithm>
#include "qtl_common.hpp"
namespace qtl
{
namespace mysql
{
struct init
{
init(int argc=-1, char **argv=NULL, char **groups=NULL)
{
//my_init();
mysql_library_init(argc, argv, groups);
}
~init()
{
mysql_library_end();
}
};
struct thread_init
{
thread_init()
{
mysql_thread_init();
}
~thread_init()
{
mysql_thread_end();
}
};
class binder : public MYSQL_BIND
{
friend class statement;
public:
binder()
{
init();
}
void init()
{
memset(this, 0, sizeof(MYSQL_BIND));
}
void bind()
{
init();
buffer_type=MYSQL_TYPE_NULL;
}
void bind(null)
{
bind();
}
void bind(std::nullptr_t)
{
bind();
}
void bind(bool& v)
{
init();
buffer_type = MYSQL_TYPE_TINY;
buffer = &v;
}
void bind(int8_t& v)
{
init();
buffer_type=MYSQL_TYPE_TINY;
buffer=&v;
}
void bind(uint8_t& v)
{
init();
buffer_type=MYSQL_TYPE_TINY;
buffer=&v;
is_unsigned=true;
}
void bind(int16_t& v)
{
init();
buffer_type=MYSQL_TYPE_SHORT;
buffer=&v;
}
void bind(uint16_t& v)
{
init();
buffer_type=MYSQL_TYPE_SHORT;
buffer=&v;
is_unsigned=true;
}
void bind(int32_t& v)
{
init();
buffer_type=MYSQL_TYPE_LONG;
buffer=&v;
}
void bind(uint32_t& v)
{
init();
buffer_type=MYSQL_TYPE_LONG;
buffer=&v;
is_unsigned=true;
}
void bind(int64_t& v)
{
init();
buffer_type=MYSQL_TYPE_LONGLONG;
buffer=&v;
}
void bind(uint64_t& v)
{
init();
buffer_type=MYSQL_TYPE_LONGLONG;
buffer=&v;
is_unsigned=true;
}
void bind(double& v)
{
init();
buffer_type=MYSQL_TYPE_DOUBLE;
buffer=&v;
}
void bind(float& v)
{
init();
buffer_type=MYSQL_TYPE_FLOAT;
buffer=&v;
}
void bind(MYSQL_TIME& v, enum_field_types type=MYSQL_TYPE_TIMESTAMP)
{
init();
buffer_type=type;
buffer=&v;
}
void bind(void* data, unsigned long length, enum_field_types type=MYSQL_TYPE_BLOB)
{
init();
buffer_type=type;
buffer=data;
buffer_length=length;
}
void bind(const const_blob_data& data, enum_field_types type=MYSQL_TYPE_BLOB)
{
init();
buffer_type=type;
buffer=const_cast<void*>(data.data);
buffer_length=data.size;
}
void bind(blob_data& data, enum_field_types type=MYSQL_TYPE_BLOB)
{
init();
buffer_type=type;
buffer=data.data;
buffer_length=data.size;
}
};
template<typename T>
inline void bind(binder& binder, const T& v)
{
binder.bind(const_cast<T&>(v));
}
template<typename T>
inline void bind(binder& binder, T&& v)
{
binder.bind(v);
}
inline void bind(binder& binder, const char* str, size_t length=0)
{
if(length==0) length=strlen(str);
binder.bind(const_cast<char*>(str), static_cast<unsigned long>(length), MYSQL_TYPE_VAR_STRING);
}
class statement;
class database;
class error : public std::exception
{
public:
error() : m_error(0) { }
error(unsigned int err, const char* errmsg) : m_error(err), m_errmsg(errmsg) { }
explicit error(unsigned int err) : m_error(err), m_errmsg(ER(err)) { }
explicit error(statement& stmt);
explicit error(database& db);
error(const error& src) = default;
virtual ~error() throw() { }
int code() const throw() { return m_error; }
virtual const char* what() const throw() override { return m_errmsg.data(); }
private:
unsigned int m_error;
std::string m_errmsg;
};
class statement final
{
public:
statement() : m_stmt(NULL), m_result(NULL) {}
explicit statement(database& db);
statement(const statement&) = delete;
statement(statement&& src)
: m_stmt(src.m_stmt), m_result(src.m_result),
m_binders(std::move(src.m_binders)), m_binderAddins(std::move(src.m_binderAddins))
{
src.m_stmt=NULL;
src.m_result=NULL;
}
statement& operator=(const statement&) = delete;
statement& operator=(statement&& src)
{
if(this!=&src)
{
m_stmt=src.m_stmt;
m_result=src.m_result;
src.m_stmt=NULL;
src.m_result=NULL;
m_binders=std::move(src.m_binders);
m_binderAddins=std::move(src.m_binderAddins);
}
return *this;
}
~statement()
{
close();
}
operator MYSQL_STMT*() { return m_stmt; }
void open(const char *query_text, unsigned long text_length=0)
{
mysql_stmt_reset(m_stmt);
if(text_length==0) text_length=(unsigned long)strlen(query_text);
if(mysql_stmt_prepare(m_stmt, query_text, text_length)!=0)
throw_exception();
}
void execute()
{
resize_binders(0);
if(mysql_stmt_execute(m_stmt)!=0)
throw_exception();
}
template<typename Types>
void execute(const Types& params)
{
unsigned long count=mysql_stmt_param_count(m_stmt);
if(count>0)
{
resize_binders(count);
qtl::bind_params(*this, params);
if(mysql_stmt_bind_param(m_stmt, &m_binders.front()))
throw_exception();
for(size_t i=0; i!=count; i++)
{
if(m_binderAddins[i].m_after_fetch)
m_binderAddins[i].m_after_fetch(m_binders[i]);
}
}
if(mysql_stmt_execute(m_stmt)!=0)
throw_exception();
}
template<typename Types>
bool fetch(Types&& values)
{
if(m_result==NULL)
{
unsigned long count=mysql_stmt_field_count(m_stmt);
if(count>0)
{
m_result=mysql_stmt_result_metadata(m_stmt);
if(m_result==NULL) throw_exception();
resize_binders(count);
qtl::bind_record(*this, std::forward<Types>(values));
set_binders();
if(mysql_stmt_bind_result(m_stmt, m_binders.data())!=0)
throw_exception();
}
}
return fetch();
}
void bind_param(size_t index, const char* param, size_t length)
{
bind(m_binders[index], param, length);
}
void bind_param(size_t index, const std::nullptr_t&)
{
m_binders[index].bind();
}
void bind_param(size_t index, std::istream& param)
{
m_binders[index].bind(NULL, 0, MYSQL_TYPE_LONG_BLOB);
m_binderAddins[index].m_after_fetch=[this, index, ¶m](const binder&) {
std::array<char, blob_buffer_size> buffer;
unsigned long readed=0;
while(!param.eof() && !param.fail())
{
param.read(buffer.data(), buffer.size());
readed=(unsigned long)param.gcount();
if(readed>0)
{
if(mysql_stmt_send_long_data(m_stmt, index, buffer.data(), readed)!=0)
throw_exception();
}
}
};
}
template<class Param>
void bind_param(size_t index, const Param& param)
{
bind(m_binders[index], param);
}
template<class Type>
void bind_field(size_t index, Type&& value)
{
if(m_result)
{
bind(m_binders[index], std::forward<Type>(value));
m_binderAddins[index].m_after_fetch=if_null<typename std::remove_reference<Type>::type>(value);
}
}
void bind_field(size_t index, char* value, size_t length)
{
m_binders[index].bind(value, length-1, MYSQL_TYPE_VAR_STRING);
m_binderAddins[index].m_after_fetch=[](const binder& bind) {
if(*bind.is_null)
memset(bind.buffer, 0, bind.buffer_length+1);
else
{
char* text=reinterpret_cast<char*>(bind.buffer);
text[*bind.length]='\0';
}
};
}
template<size_t N>
void bind_field(size_t index, std::array<char, N>&& value)
{
bind_field(index, value.data(), value.size());
}
template<typename T>
void bind_field(size_t index, bind_string_helper<T>&& value)
{
if(m_result)
{
MYSQL_FIELD* field=mysql_fetch_field_direct(m_result, (unsigned int)index);
if(field==NULL) throw_exception();
value.clear();
typename bind_string_helper<T>::char_type* data=value.alloc(field->length);
m_binderAddins[index].m_before_fetch = [this, value](binder& b) mutable {
if (value.size() < b.buffer_length)
{
value.alloc(b.buffer_length);
if (b.buffer != value.data())
{
b.buffer = const_cast<char*>(value.data());
mysql_stmt_bind_result(m_stmt, &m_binders.front());
}
}
};
m_binderAddins[index].m_after_fetch= [value](const binder& b) mutable {
if(*b.is_null) value.clear();
else value.truncate(*b.length);
};
m_binders[index].bind(data, field->length, field->type);
}
}
void bind_field(size_t index, std::ostream&& value)
{
if(m_result)
{
m_binders[index].bind(NULL, 0, MYSQL_TYPE_LONG_BLOB);
m_binderAddins[index].m_after_fetch=[this, index, &value](const binder& b) {
unsigned long readed=0;
std::array<char, blob_buffer_size> buffer;
binder& bb=const_cast<binder&>(b);
if(*b.is_null) return;
bb.buffer=const_cast<char*>(buffer.data());
bb.buffer_length=buffer.size();
while(readed<=*b.length)
{
int ret=mysql_stmt_fetch_column(m_stmt, &bb, index, readed);
if(ret!=0)
throw_exception();
value.write(buffer.data(), std::min(b.buffer_length, *b.length-b.offset));
readed+=bb.buffer_length;
}
};
}
}
template<typename Type>
void bind_field(size_t index, indicator<Type>&& value)
{
if(m_result)
{
qtl::bind_field(*this, index, value.data);
binder_addin& addin=m_binderAddins[index];
auto fetch_fun=addin.m_after_fetch;
addin.m_after_fetch=[&addin, fetch_fun, &value](const binder& b) {
value.is_null= *b.is_null!=0;
value.length=*b.length;
value.is_truncated=addin.is_truncated;
if(fetch_fun) fetch_fun(b);
};
}
}
unsigned int get_parameter_count() const { return mysql_stmt_param_count(m_stmt); }
unsigned int get_column_count() const { return mysql_stmt_field_count(m_stmt); }
unsigned long length(unsigned int index) const
{
return m_binderAddins[index].m_length;
}
bool is_null(unsigned int index) const
{
return m_binderAddins[index].m_isNull!=0;
}
size_t find_field(const char* name) const
{
if(m_result)
{
for(size_t i=0; i!=m_result->field_count; i++)
{
if(strncmp(m_result->fields[i].name, name, m_result->fields[i].name_length)==0)
return i;
}
}
return -1;
}
void close()
{
if(m_result)
{
mysql_free_result(m_result);
m_result=NULL;
}
if(m_stmt)
{
mysql_stmt_close(m_stmt);
m_stmt=NULL;
}
}
bool fetch()
{
for (size_t i = 0; i != m_binders.size(); i++)
{
if (m_binderAddins[i].m_before_fetch)
m_binderAddins[i].m_before_fetch(m_binders[i]);
}
int err=mysql_stmt_fetch(m_stmt);
if(err==0 || err==MYSQL_DATA_TRUNCATED)
{
for(size_t i=0; i!=m_binders.size(); i++)
{
m_binderAddins[i].is_truncated = (err==MYSQL_DATA_TRUNCATED);
if(m_binderAddins[i].m_after_fetch)
m_binderAddins[i].m_after_fetch(m_binders[i]);
}
return true;
}
else if(err==1)
throw_exception();
return false;
}
bool next_result()
{
if(m_result)
{
mysql_free_result(m_result);
m_result=NULL;
mysql_stmt_free_result(m_stmt);
}
int ret=0;
do
{
ret=mysql_stmt_next_result(m_stmt);
if(ret>0) throw_exception();
}while(ret==0 && mysql_stmt_field_count(m_stmt)<=0);
return ret==0;
}
my_ulonglong affetced_rows()
{
return mysql_stmt_affected_rows(m_stmt);
}
my_ulonglong insert_id()
{
return mysql_stmt_insert_id(m_stmt);
}
binder* get_binder(unsigned long index)
{
return &m_binders[index];
}
unsigned int error() const
{
return mysql_stmt_errno(m_stmt);
}
const char* errmsg() const
{
return mysql_stmt_error(m_stmt);
}
MYSQL_RES* result() { return m_result; }
bool reset() { return mysql_stmt_reset(m_stmt)!=0; }
private:
MYSQL_STMT* m_stmt;
MYSQL_RES* m_result;
std::vector<binder> m_binders;
struct binder_addin
{
unsigned long m_length;
my_bool m_isNull;
my_bool m_error;
bool is_truncated;
std::function<void(binder&)> m_before_fetch;
std::function<void(const binder&)> m_after_fetch;
};
std::vector<binder_addin> m_binderAddins;
void resize_binders(size_t n)
{
m_binders.resize(n);
m_binderAddins.resize(n);
}
void set_binders()
{
for(size_t i=0; i!=m_binders.size(); i++)
{
m_binderAddins[i].m_length=0;
m_binders[i].length=&m_binderAddins[i].m_length;
m_binderAddins[i].m_isNull=0;
m_binders[i].is_null=&m_binderAddins[i].m_isNull;
m_binderAddins[i].m_error=0;
m_binders[i].error=&m_binderAddins[i].m_error;
}
}
void throw_exception() { throw mysql::error(*this); }
private:
template<typename Value>
struct if_null
{
if_null(Value& value, Value&& def=Value()) : m_value(value), m_def(std::move(def)) { }
void operator()(const binder& b)
{
if(*b.is_null) m_value=m_def;
}
Value& m_value;
Value m_def;
};
};
class database final : public qtl::base_database<database, statement>
{
public:
typedef mysql::error exception_type;
database()
{
m_mysql=mysql_init(NULL);
}
~database()
{
mysql_close(m_mysql);
}
database(const database&) = delete;
database(database&& src)
{
m_mysql=src.m_mysql;
src.m_mysql=NULL;
}
database& operator==(const database&) = delete;
database& operator==(database&& src)
{
if(this!=&src)
{
mysql_close(m_mysql);
m_mysql=src.m_mysql;
src.m_mysql=NULL;
}
return *this;
}
MYSQL* handle() { return m_mysql; }
void options(enum mysql_option option, const void *arg)
{
if(mysql_options(m_mysql, option, arg)!=0)
throw_exception();
}
void charset_name(const char* charset)
{
if(mysql_set_character_set(m_mysql, charset)!=0)
throw_exception();
}
void protocol(mysql_protocol_type type)
{
return options(MYSQL_OPT_PROTOCOL, &type);
}
void reconnect(my_bool re)
{
return options(MYSQL_OPT_RECONNECT, &re);
}
bool open(const char *host, const char *user, const char *passwd, const char *db,
unsigned long clientflag=0, unsigned int port=0, const char *unix_socket=NULL)
{
if(m_mysql==NULL) m_mysql=mysql_init(NULL);
return mysql_real_connect(m_mysql, host, user, passwd, db, port, unix_socket, clientflag)!=NULL;
}
void close()
{
mysql_close(m_mysql);
m_mysql=NULL;
}
void refresh(unsigned int options)
{
if(mysql_refresh(m_mysql, options)<0)
throw_exception();
}
void select(const char* db)
{
if(mysql_select_db(m_mysql, db)!=0)
throw_exception();
}
const char* current() const
{
return m_mysql->db;
}
unsigned int error() const
{
return mysql_errno(m_mysql);
}
const char* errmsg() const
{
return mysql_error(m_mysql);
}
statement open_command(const char* query_text, size_t text_length)
{
statement stmt(*this);
stmt.open(query_text, text_length);
return stmt;
}
statement open_command(const char* query_text)
{
return open_command(query_text, strlen(query_text));
}
statement open_command(const std::string& query_text)
{
return open_command(query_text.data(), query_text.length());
}
void simple_execute(const char* query_text, uint64_t* paffected=NULL)
{
if(mysql_query(m_mysql, query_text)!=0)
throw_exception();
if(paffected) *paffected=affected_rows();
}
void simple_execute(const char* query_text, unsigned long text_length, uint64_t* paffected=NULL)
{
if(text_length==0) text_length=(unsigned long)strlen(query_text);
if(mysql_real_query(m_mysql, query_text, text_length)!=0)
throw_exception();
if(paffected) *paffected=affected_rows();
}
uint64_t affected_rows()
{
return mysql_affected_rows(m_mysql);
}
unsigned int field_count()
{
return mysql_field_count(m_mysql);
}
uint64_t insert_id()
{
return mysql_insert_id(m_mysql);
}
void auto_commit(bool on)
{
if(mysql_autocommit(m_mysql, on?1:0)!=0)
throw_exception();
}
void begin_transaction()
{
auto_commit(false);
}
void rollback()
{
if(mysql_rollback(m_mysql)!=0)
throw_exception();
auto_commit(true);
}
void commit()
{
if(mysql_commit(m_mysql)!=0)
throw_exception();
auto_commit(true);
}
bool is_alive()
{
return mysql_ping(m_mysql)==0;
}
template<typename Pred>
bool simple_query(const char* query, unsigned long length, Pred&& pred)
{
simple_execute(query, length);
unsigned int fieldCount=mysql_field_count(m_mysql);
MYSQL_RES* result=mysql_store_result(m_mysql);
if(fieldCount>0 && result)
{
MYSQL_RES* result=mysql_store_result(m_mysql);
MYSQL_ROW row;
while(row=mysql_fetch_row(result))
{
pred(*this, row, fieldCount);
}
mysql_free_result(result);
return true;
}
return false;
}
private:
MYSQL* m_mysql;
void throw_exception() { throw mysql::error(*this); }
};
struct time : public MYSQL_TIME
{
time()
{
memset(this, 0, sizeof(MYSQL_TIME));
time_type=MYSQL_TIMESTAMP_NONE;
}
time(const struct tm& tm)
{
memset(this, 0, sizeof(MYSQL_TIME));
year=tm.tm_year+1900;
month=tm.tm_mon+1;
day=tm.tm_mday;
hour=tm.tm_hour;
minute=tm.tm_min;
second=tm.tm_sec;
time_type=MYSQL_TIMESTAMP_DATETIME;
}
time(time_t value)
{
struct tm tm;
#if defined(_MSC_VER)
localtime_s(&tm, &value);
#elif defined(_POSIX_VERSION)
localtime_r(&value, &tm);
#else
tm=*localtime(&value);
#endif
new(this)time(tm);
}
time(const time& src)
{
memcpy(this, &src, sizeof(MYSQL_TIME));
}
time& operator=(const time& src)
{
if(this!=&src)
memcpy(this, &src, sizeof(MYSQL_TIME));
return *this;
}
static time now()
{
time_t value;
::time(&value);
return time(value);
}
time_t as_tm(struct tm& tm) const
{
tm.tm_year=year-1900;
tm.tm_mon=month-1;
tm.tm_mday=day;
tm.tm_hour=hour;
tm.tm_min=minute;
tm.tm_sec=second;
return mktime(&tm);
}
time_t get_time() const
{
struct tm tm;
return as_tm(tm);
}
};
typedef qtl::transaction<database> transaction;
template<typename Record>
using query_iterator = qtl::query_iterator<statement, Record>;
template<typename Record>
using query_result = qtl::query_result<statement, Record>;
template<typename Params>
inline statement& operator<<(statement& stmt, const Params& params)
{
stmt.reset();
stmt.execute(params);
return stmt;
}
inline error::error(statement& stmt)
{
const char* errmsg=stmt.errmsg();
m_error=stmt.error();
if(errmsg) m_errmsg=errmsg;
}
inline error::error(database& db)
{
const char* errmsg=db.errmsg();
m_error=db.error();
if(errmsg) m_errmsg=errmsg;
}
inline statement::statement(database& db)
{
m_stmt=mysql_stmt_init(db.handle());
m_result=NULL;
}
}
}
#endif //_MYDTL_MYSQL_H_
| 20.378685 | 98 | 0.688439 | wyyrepo |
e0cf7c8d151c26e27a3288e475350f3d99645cc5 | 20,443 | cpp | C++ | src/tests/add-ons/kernel/file_systems/userlandfs/r5/src/test/ramfs/Volume.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | 4 | 2017-06-17T22:03:56.000Z | 2019-01-25T10:51:55.000Z | src/tests/add-ons/kernel/file_systems/userlandfs/r5/src/test/ramfs/Volume.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | null | null | null | src/tests/add-ons/kernel/file_systems/userlandfs/r5/src/test/ramfs/Volume.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | 3 | 2018-12-17T13:07:38.000Z | 2021-09-08T13:07:31.000Z | // Volume.cpp
//
// Copyright (c) 2003, Ingo Weinhold (bonefish@cs.tu-berlin.de)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can alternatively use *this file* under the terms of the the MIT
// license included in this package.
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "Block.h"
#include "BlockAllocator.h"
#include "Debug.h"
#include "Directory.h"
#include "Entry.h"
#include "EntryListener.h"
#include "IndexDirectory.h"
#include "Locking.h"
#include "Misc.h"
#include "NameIndex.h"
#include "Node.h"
#include "NodeChildTable.h"
#include "NodeListener.h"
#include "NodeTable.h"
#include "TwoKeyAVLTree.h"
#include "Volume.h"
// default block size
static const off_t kDefaultBlockSize = 4096;
static const size_t kDefaultAreaSize = kDefaultBlockSize * 128;
// default volume name
static const char *kDefaultVolumeName = "RAM FS";
// NodeListenerGetPrimaryKey
class NodeListenerGetPrimaryKey {
public:
inline Node *operator()(const NodeListenerValue &a)
{
return a.node;
}
inline Node *operator()(const NodeListenerValue &a) const
{
return a.node;
}
};
// NodeListenerGetSecondaryKey
class NodeListenerGetSecondaryKey {
public:
inline NodeListener *operator()(const NodeListenerValue &a)
{
return a.listener;
}
inline NodeListener *operator()(const NodeListenerValue &a) const
{
return a.listener;
}
};
// NodeListenerTree
typedef TwoKeyAVLTree<NodeListenerValue, Node*,
AVLTreeStandardCompare<Node*>,
NodeListenerGetPrimaryKey, NodeListener*,
AVLTreeStandardNode<NodeListenerValue>,
AVLTreeStandardCompare<NodeListener*>,
NodeListenerGetSecondaryKey > _NodeListenerTree;
class NodeListenerTree : public _NodeListenerTree {};
// EntryListenerGetPrimaryKey
class EntryListenerGetPrimaryKey {
public:
inline Entry *operator()(const EntryListenerValue &a)
{
return a.entry;
}
inline Entry *operator()(const EntryListenerValue &a) const
{
return a.entry;
}
};
// EntryListenerGetSecondaryKey
class EntryListenerGetSecondaryKey {
public:
inline EntryListener *operator()(const EntryListenerValue &a)
{
return a.listener;
}
inline EntryListener *operator()(const EntryListenerValue &a) const
{
return a.listener;
}
};
// EntryListenerTree
typedef TwoKeyAVLTree<EntryListenerValue, Entry*,
AVLTreeStandardCompare<Entry*>,
EntryListenerGetPrimaryKey, EntryListener*,
AVLTreeStandardNode<EntryListenerValue>,
AVLTreeStandardCompare<EntryListener*>,
EntryListenerGetSecondaryKey > _EntryListenerTree;
class EntryListenerTree : public _EntryListenerTree {};
/*!
\class Volume
\brief Represents a volume.
*/
// constructor
Volume::Volume()
: fID(0),
fNextNodeID(kRootParentID + 1),
fNodeTable(NULL),
fDirectoryEntryTable(NULL),
fNodeAttributeTable(NULL),
fIndexDirectory(NULL),
fRootDirectory(NULL),
fName(kDefaultVolumeName),
fLocker("volume"),
fIteratorLocker("iterators"),
fQueryLocker("queries"),
fNodeListeners(NULL),
fAnyNodeListeners(),
fEntryListeners(NULL),
fAnyEntryListeners(),
fBlockAllocator(NULL),
fBlockSize(kDefaultBlockSize),
fAllocatedBlocks(0),
fAccessTime(0),
fMounted(false)
{
}
// destructor
Volume::~Volume()
{
Unmount();
}
// Mount
status_t
Volume::Mount(nspace_id id)
{
Unmount();
// check the locker's semaphores
if (fLocker.Sem() < 0)
return fLocker.Sem();
if (fIteratorLocker.Sem() < 0)
return fIteratorLocker.Sem();
if (fQueryLocker.Sem() < 0)
return fQueryLocker.Sem();
status_t error = B_OK;
fID = id;
// create a block allocator
if (error == B_OK) {
fBlockAllocator = new(nothrow) BlockAllocator(kDefaultAreaSize);
if (fBlockAllocator)
error = fBlockAllocator->InitCheck();
else
SET_ERROR(error, B_NO_MEMORY);
}
// create the listener trees
if (error == B_OK) {
fNodeListeners = new(nothrow) NodeListenerTree;
if (!fNodeListeners)
error = B_NO_MEMORY;
}
if (error == B_OK) {
fEntryListeners = new(nothrow) EntryListenerTree;
if (!fEntryListeners)
error = B_NO_MEMORY;
}
// create the node table
if (error == B_OK) {
fNodeTable = new(nothrow) NodeTable;
if (fNodeTable)
error = fNodeTable->InitCheck();
else
SET_ERROR(error, B_NO_MEMORY);
}
// create the directory entry table
if (error == B_OK) {
fDirectoryEntryTable = new(nothrow) DirectoryEntryTable;
if (fDirectoryEntryTable)
error = fDirectoryEntryTable->InitCheck();
else
SET_ERROR(error, B_NO_MEMORY);
}
// create the node attribute table
if (error == B_OK) {
fNodeAttributeTable = new(nothrow) NodeAttributeTable;
if (fNodeAttributeTable)
error = fNodeAttributeTable->InitCheck();
else
SET_ERROR(error, B_NO_MEMORY);
}
// create the index directory
if (error == B_OK) {
fIndexDirectory = new(nothrow) IndexDirectory(this);
if (!fIndexDirectory)
SET_ERROR(error, B_NO_MEMORY);
}
// create the root dir
if (error == B_OK) {
fRootDirectory = new(nothrow) Directory(this);
if (fRootDirectory) {
// set permissions: -rwxr-xr-x
fRootDirectory->SetMode(
S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
error = fRootDirectory->Link(NULL);
} else
SET_ERROR(error, B_NO_MEMORY);
}
// set mounted flag / cleanup on error
if (error == B_OK)
fMounted = true;
else
Unmount();
RETURN_ERROR(error);
}
// Unmount
status_t
Volume::Unmount()
{
fMounted = false;
// delete the root directory
if (fRootDirectory) {
// deleting the root directory destroys the complete hierarchy
delete fRootDirectory;
fRootDirectory = NULL;
}
// delete the index directory
if (fIndexDirectory) {
delete fIndexDirectory;
fIndexDirectory = NULL;
}
// delete the listener trees
if (fEntryListeners) {
delete fEntryListeners;
fEntryListeners = NULL;
}
if (fNodeListeners) {
delete fNodeListeners;
fNodeListeners = NULL;
}
// delete the tables
if (fNodeAttributeTable) {
delete fNodeAttributeTable;
fNodeAttributeTable = NULL;
}
if (fDirectoryEntryTable) {
delete fDirectoryEntryTable;
fDirectoryEntryTable = NULL;
}
if (fNodeTable) {
delete fNodeTable;
fNodeTable = NULL;
}
// delete the block allocator
if (fBlockAllocator) {
delete fBlockAllocator;
fBlockAllocator = NULL;
}
fID = 0;
return B_OK;
}
// GetBlockSize
off_t
Volume::GetBlockSize() const
{
return fBlockSize;
}
// CountBlocks
off_t
Volume::CountBlocks() const
{
size_t bytes = 0;
system_info sysInfo;
if (get_system_info(&sysInfo) == B_OK) {
int32 freePages = sysInfo.max_pages - sysInfo.used_pages;
bytes = (uint32)freePages * B_PAGE_SIZE
+ fBlockAllocator->GetAvailableBytes();
}
return bytes / kDefaultBlockSize;
}
// CountFreeBlocks
off_t
Volume::CountFreeBlocks() const
{
// TODO:...
return CountBlocks() - fBlockAllocator->GetUsedBytes() / kDefaultBlockSize;
}
// SetName
status_t
Volume::SetName(const char *name)
{
status_t error = (name ? B_OK : B_BAD_VALUE);
if (error == B_OK) {
if (!fName.SetTo(name))
SET_ERROR(error, B_NO_MEMORY);
}
return error;
}
// GetName
const char *
Volume::GetName() const
{
return fName.GetString();
}
// NewVNode
status_t
Volume::NewVNode(Node *node)
{
status_t error = NodeAdded(node);
if (error == B_OK) {
error = new_vnode(GetID(), node->GetID(), node);
if (error != B_OK)
NodeRemoved(node);
}
return error;
}
// GetVNode
status_t
Volume::GetVNode(vnode_id id, Node **node)
{
return (fMounted ? get_vnode(GetID(), id, (void**)node) : B_BAD_VALUE);
}
// GetVNode
status_t
Volume::GetVNode(Node *node)
{
Node *dummy = NULL;
status_t error = (fMounted ? GetVNode(node->GetID(), &dummy)
: B_BAD_VALUE );
if (error == B_OK && dummy != node) {
FATAL(("Two Nodes have the same ID: %Ld!\n", node->GetID()));
PutVNode(dummy);
error = B_ERROR;
}
return error;
}
// PutVNode
status_t
Volume::PutVNode(vnode_id id)
{
return (fMounted ? put_vnode(GetID(), id) : B_BAD_VALUE);
}
// PutVNode
status_t
Volume::PutVNode(Node *node)
{
return (fMounted ? put_vnode(GetID(), node->GetID()) : B_BAD_VALUE);
}
// RemoveVNode
status_t
Volume::RemoveVNode(Node *node)
{
if (fMounted)
return remove_vnode(GetID(), node->GetID());
status_t error = NodeRemoved(node);
if (error == B_OK)
delete node;
return error;
}
// UnremoveVNode
status_t
Volume::UnremoveVNode(Node *node)
{
return (fMounted ? unremove_vnode(GetID(), node->GetID()) : B_BAD_VALUE);
}
// NodeAdded
status_t
Volume::NodeAdded(Node *node)
{
status_t error = (node ? B_OK : B_BAD_VALUE);
if (error == B_OK) {
error = fNodeTable->AddNode(node);
// notify listeners
if (error == B_OK) {
// listeners interested in that node
NodeListenerTree::Iterator it;
if (fNodeListeners->FindFirst(node, &it)) {
for (NodeListenerValue *value = it.GetCurrent();
value && value->node == node;
value = it.GetNext()) {
if (value->flags & NODE_LISTEN_ADDED)
value->listener->NodeAdded(node);
}
}
// listeners interested in any node
int32 count = fAnyNodeListeners.CountItems();
for (int32 i = 0; i < count; i++) {
const NodeListenerValue &value = fAnyNodeListeners.ItemAt(i);
if (value.flags & NODE_LISTEN_ADDED)
value.listener->NodeAdded(node);
}
}
}
return error;
}
// NodeRemoved
status_t
Volume::NodeRemoved(Node *node)
{
status_t error = (node ? B_OK : B_BAD_VALUE);
if (error == B_OK) {
error = fNodeTable->RemoveNode(node);
// notify listeners
if (error == B_OK) {
// listeners interested in that node
NodeListenerTree::Iterator it;
if (fNodeListeners->FindFirst(node, &it)) {
for (NodeListenerValue *value = it.GetCurrent();
value && value->node == node;
value = it.GetNext()) {
if (value->flags & NODE_LISTEN_REMOVED)
value->listener->NodeRemoved(node);
}
}
// listeners interested in any node
int32 count = fAnyNodeListeners.CountItems();
for (int32 i = 0; i < count; i++) {
const NodeListenerValue &value = fAnyNodeListeners.ItemAt(i);
if (value.flags & NODE_LISTEN_REMOVED)
value.listener->NodeRemoved(node);
}
}
}
return error;
}
// FindNode
/*! \brief Finds the node identified by a vnode_id.
\note The method does not initialize the parent ID for non-directory nodes.
\param id ID of the node to be found.
\param node pointer to a pre-allocated Node* to be set to the found node.
\return \c B_OK, if everything went fine.
*/
status_t
Volume::FindNode(vnode_id id, Node **node)
{
status_t error = (node ? B_OK : B_BAD_VALUE);
if (error == B_OK) {
*node = fNodeTable->GetNode(id);
if (!*node)
error = B_ENTRY_NOT_FOUND;
}
return error;
}
// AddNodeListener
status_t
Volume::AddNodeListener(NodeListener *listener, Node *node, uint32 flags)
{
// check parameters
if (!listener || !node && !(flags & NODE_LISTEN_ANY_NODE)
|| !(flags & NODE_LISTEN_ALL)) {
return B_BAD_VALUE;
}
// add the listener to the right container
status_t error = B_OK;
NodeListenerValue value(listener, node, flags);
if (flags & NODE_LISTEN_ANY_NODE) {
if (!fAnyNodeListeners.AddItem(value))
error = B_NO_MEMORY;
} else
error = fNodeListeners->Insert(value);
return error;
}
// RemoveNodeListener
status_t
Volume::RemoveNodeListener(NodeListener *listener, Node *node)
{
if (!listener)
return B_BAD_VALUE;
status_t error = B_OK;
if (node)
error = fNodeListeners->Remove(node, listener);
else {
NodeListenerValue value(listener, node, 0);
if (!fAnyNodeListeners.RemoveItem(value))
error = B_ENTRY_NOT_FOUND;
}
return error;
}
// EntryAdded
status_t
Volume::EntryAdded(vnode_id id, Entry *entry)
{
status_t error = (entry ? B_OK : B_BAD_VALUE);
if (error == B_OK) {
error = fDirectoryEntryTable->AddNodeChild(id, entry);
if (error == B_OK) {
// notify listeners
// listeners interested in that entry
EntryListenerTree::Iterator it;
if (fEntryListeners->FindFirst(entry, &it)) {
for (EntryListenerValue *value = it.GetCurrent();
value && value->entry == entry;
value = it.GetNext()) {
if (value->flags & ENTRY_LISTEN_ADDED)
value->listener->EntryAdded(entry);
}
}
// listeners interested in any entry
int32 count = fAnyEntryListeners.CountItems();
for (int32 i = 0; i < count; i++) {
const EntryListenerValue &value = fAnyEntryListeners.ItemAt(i);
if (value.flags & ENTRY_LISTEN_ADDED)
value.listener->EntryAdded(entry);
}
}
}
return error;
}
// EntryRemoved
status_t
Volume::EntryRemoved(vnode_id id, Entry *entry)
{
status_t error = (entry ? B_OK : B_BAD_VALUE);
if (error == B_OK) {
error = fDirectoryEntryTable->RemoveNodeChild(id, entry);
if (error == B_OK) {
// notify listeners
// listeners interested in that entry
EntryListenerTree::Iterator it;
if (fEntryListeners->FindFirst(entry, &it)) {
for (EntryListenerValue *value = it.GetCurrent();
value && value->entry == entry;
value = it.GetNext()) {
if (value->flags & ENTRY_LISTEN_REMOVED)
value->listener->EntryRemoved(entry);
}
}
// listeners interested in any entry
int32 count = fAnyEntryListeners.CountItems();
for (int32 i = 0; i < count; i++) {
const EntryListenerValue &value = fAnyEntryListeners.ItemAt(i);
if (value.flags & ENTRY_LISTEN_REMOVED)
value.listener->EntryRemoved(entry);
}
}
}
return error;
}
// FindEntry
status_t
Volume::FindEntry(vnode_id id, const char *name, Entry **entry)
{
status_t error = (entry ? B_OK : B_BAD_VALUE);
if (error == B_OK) {
*entry = fDirectoryEntryTable->GetNodeChild(id, name);
if (!*entry)
error = B_ENTRY_NOT_FOUND;
}
return error;
}
// AddEntryListener
status_t
Volume::AddEntryListener(EntryListener *listener, Entry *entry, uint32 flags)
{
// check parameters
if (!listener || !entry && !(flags & ENTRY_LISTEN_ANY_ENTRY)
|| !(flags & ENTRY_LISTEN_ALL)) {
return B_BAD_VALUE;
}
// add the listener to the right container
status_t error = B_OK;
EntryListenerValue value(listener, entry, flags);
if (flags & ENTRY_LISTEN_ANY_ENTRY) {
if (!fAnyEntryListeners.AddItem(value))
error = B_NO_MEMORY;
} else
error = fEntryListeners->Insert(value);
return error;
}
// RemoveEntryListener
status_t
Volume::RemoveEntryListener(EntryListener *listener, Entry *entry)
{
if (!listener)
return B_BAD_VALUE;
status_t error = B_OK;
if (entry)
error = fEntryListeners->Remove(entry, listener);
else {
EntryListenerValue value(listener, entry, 0);
if (!fAnyEntryListeners.RemoveItem(value))
error = B_ENTRY_NOT_FOUND;
}
return error;
}
// NodeAttributeAdded
status_t
Volume::NodeAttributeAdded(vnode_id id, Attribute *attribute)
{
status_t error = (attribute ? B_OK : B_BAD_VALUE);
if (error == B_OK) {
error = fNodeAttributeTable->AddNodeChild(id, attribute);
// notify the respective attribute index
if (error == B_OK) {
if (AttributeIndex *index = FindAttributeIndex(
attribute->GetName(), attribute->GetType())) {
index->Added(attribute);
}
}
}
return error;
}
// NodeAttributeRemoved
status_t
Volume::NodeAttributeRemoved(vnode_id id, Attribute *attribute)
{
status_t error = (attribute ? B_OK : B_BAD_VALUE);
if (error == B_OK) {
error = fNodeAttributeTable->RemoveNodeChild(id, attribute);
// notify the respective attribute index
if (error == B_OK) {
if (AttributeIndex *index = FindAttributeIndex(
attribute->GetName(), attribute->GetType())) {
index->Removed(attribute);
}
}
// update live queries
if (error == B_OK && attribute->GetNode()) {
const uint8* oldKey;
size_t oldLength;
attribute->GetKey(&oldKey, &oldLength);
UpdateLiveQueries(NULL, attribute->GetNode(), attribute->GetName(),
attribute->GetType(), oldKey, oldLength, NULL, 0);
}
}
return error;
}
// FindNodeAttribute
status_t
Volume::FindNodeAttribute(vnode_id id, const char *name, Attribute **attribute)
{
status_t error = (attribute ? B_OK : B_BAD_VALUE);
if (error == B_OK) {
*attribute = fNodeAttributeTable->GetNodeChild(id, name);
if (!*attribute)
error = B_ENTRY_NOT_FOUND;
}
return error;
}
// GetNameIndex
NameIndex *
Volume::GetNameIndex() const
{
return (fIndexDirectory ? fIndexDirectory->GetNameIndex() : NULL);
}
// GetLastModifiedIndex
LastModifiedIndex *
Volume::GetLastModifiedIndex() const
{
return (fIndexDirectory ? fIndexDirectory->GetLastModifiedIndex() : NULL);
}
// GetSizeIndex
SizeIndex *
Volume::GetSizeIndex() const
{
return (fIndexDirectory ? fIndexDirectory->GetSizeIndex() : NULL);
}
// FindIndex
Index *
Volume::FindIndex(const char *name)
{
return (fIndexDirectory ? fIndexDirectory->FindIndex(name) : NULL);
}
// FindAttributeIndex
AttributeIndex *
Volume::FindAttributeIndex(const char *name, uint32 type)
{
return (fIndexDirectory
? fIndexDirectory->FindAttributeIndex(name, type) : NULL);
}
// AddQuery
void
Volume::AddQuery(Query *query)
{
AutoLocker<Locker> _(fQueryLocker);
if (query)
fQueries.Insert(query);
}
// RemoveQuery
void
Volume::RemoveQuery(Query *query)
{
AutoLocker<Locker> _(fQueryLocker);
if (query)
fQueries.Remove(query);
}
// UpdateLiveQueries
void
Volume::UpdateLiveQueries(Entry *entry, Node* node, const char *attribute,
int32 type, const uint8 *oldKey, size_t oldLength, const uint8 *newKey,
size_t newLength)
{
AutoLocker<Locker> _(fQueryLocker);
for (Query* query = fQueries.First();
query;
query = fQueries.GetNext(query)) {
query->LiveUpdate(entry, node, attribute, type, oldKey, oldLength,
newKey, newLength);
}
}
// AllocateBlock
status_t
Volume::AllocateBlock(size_t size, BlockReference **block)
{
status_t error = (size > 0 && size <= fBlockSize && block
? B_OK : B_BAD_VALUE);
if (error == B_OK) {
*block = fBlockAllocator->AllocateBlock(size);
if (*block)
fAllocatedBlocks++;
else
SET_ERROR(error, B_NO_MEMORY);
}
return error;
}
// FreeBlock
void
Volume::FreeBlock(BlockReference *block)
{
if (block) {
fBlockAllocator->FreeBlock(block);
fAllocatedBlocks--;
}
}
// ResizeBlock
BlockReference *
Volume::ResizeBlock(BlockReference *block, size_t size)
{
BlockReference *newBlock = NULL;
if (size <= fBlockSize && block) {
if (size == 0) {
fBlockAllocator->FreeBlock(block);
fAllocatedBlocks--;
} else
newBlock = fBlockAllocator->ResizeBlock(block, size);
}
return newBlock;
}
// CheckBlock
bool
Volume::CheckBlock(BlockReference *block, size_t size)
{
return fBlockAllocator->CheckBlock(block, size);
}
// GetAllocationInfo
void
Volume::GetAllocationInfo(AllocationInfo &info)
{
// tables
info.AddOtherAllocation(sizeof(NodeTable));
fNodeTable->GetAllocationInfo(info);
info.AddOtherAllocation(sizeof(DirectoryEntryTable));
fDirectoryEntryTable->GetAllocationInfo(info);
info.AddOtherAllocation(sizeof(NodeAttributeTable));
fNodeAttributeTable->GetAllocationInfo(info);
// node hierarchy
fRootDirectory->GetAllocationInfo(info);
// name
info.AddStringAllocation(fName.GetLength());
// block allocator
info.AddOtherAllocation(sizeof(BlockAllocator));
fBlockAllocator->GetAllocationInfo(info);
}
// ReadLock
bool
Volume::ReadLock()
{
bool alreadyLocked = fLocker.IsLocked();
if (fLocker.Lock()) {
if (!alreadyLocked)
fAccessTime = system_time();
return true;
}
return false;
}
// ReadUnlock
void
Volume::ReadUnlock()
{
fLocker.Unlock();
}
// WriteLock
bool
Volume::WriteLock()
{
bool alreadyLocked = fLocker.IsLocked();
if (fLocker.Lock()) {
if (!alreadyLocked)
fAccessTime = system_time();
return true;
}
return false;
}
// WriteUnlock
void
Volume::WriteUnlock()
{
fLocker.Unlock();
}
// IteratorLock
bool
Volume::IteratorLock()
{
return fIteratorLocker.Lock();
}
// IteratorUnlock
void
Volume::IteratorUnlock()
{
fIteratorLocker.Unlock();
}
| 22.815848 | 79 | 0.706208 | axeld |
e0d4dc61b32e2f7cec5646eb3915ff1c82089f78 | 9,667 | cpp | C++ | src/Features/Demo/DemoGhostPlayer.cpp | Zyntex1/SourceAutoRecord | 7e1419183de2b7c9638ad6dc0cbb5701e4a392c0 | [
"MIT"
] | 42 | 2021-04-27T17:03:24.000Z | 2022-03-03T18:56:13.000Z | src/Features/Demo/DemoGhostPlayer.cpp | Zyntex1/SourceAutoRecord | 7e1419183de2b7c9638ad6dc0cbb5701e4a392c0 | [
"MIT"
] | 43 | 2021-04-27T21:20:06.000Z | 2022-03-22T12:45:46.000Z | src/Features/Demo/DemoGhostPlayer.cpp | Zyntex1/SourceAutoRecord | 7e1419183de2b7c9638ad6dc0cbb5701e4a392c0 | [
"MIT"
] | 29 | 2021-06-11T23:52:24.000Z | 2022-03-30T14:33:46.000Z | #include "DemoGhostPlayer.hpp"
#include "Event.hpp"
#include "Features/Demo/Demo.hpp"
#include "Features/Demo/DemoParser.hpp"
#include "Features/Session.hpp"
#include "Modules/Client.hpp"
#include "Modules/Engine.hpp"
#include "NetworkGhostPlayer.hpp"
#include "Utils.hpp"
#include <filesystem>
#include <fstream>
Variable ghost_sync("ghost_sync", "0", "When loading a new level, pauses the game until other players load it.\n");
DemoGhostPlayer demoGhostPlayer;
DemoGhostPlayer::DemoGhostPlayer()
: isPlaying(false)
, currentTick(0)
, isFullGame(false) {
}
void DemoGhostPlayer::SpawnAllGhosts() {
for (auto &ghost : this->ghostPool) {
ghost.Spawn();
}
this->isPlaying = true;
}
void DemoGhostPlayer::StartAllGhost() {
for (auto &ghost : this->ghostPool) {
ghost.SetGhostOnFirstMap();
ghost.Spawn();
}
this->isPlaying = true;
}
void DemoGhostPlayer::ResetAllGhosts() {
this->isPlaying = false;
for (auto &ghost : this->ghostPool) {
if (this->IsFullGame()) {
ghost.ChangeDemo();
}
ghost.LevelReset();
}
}
void DemoGhostPlayer::PauseAllGhosts() {
this->isPlaying = false;
}
void DemoGhostPlayer::ResumeAllGhosts() {
this->isPlaying = true;
}
void DemoGhostPlayer::DeleteAllGhosts() {
this->ghostPool.clear();
this->isPlaying = false;
}
void DemoGhostPlayer::DeleteAllGhostModels() {
for (int i = 0; i < this->ghostPool.size(); ++i) {
this->ghostPool[i].DeleteGhost();
}
}
void DemoGhostPlayer::DeleteGhostsByID(const unsigned int ID) {
for (int i = 0; i < this->ghostPool.size(); ++i) {
if (this->ghostPool[i].ID == ID) {
this->ghostPool[i].DeleteGhost();
this->ghostPool.erase(this->ghostPool.begin() + i);
return;
}
}
}
void DemoGhostPlayer::UpdateGhostsPosition() {
if (this->currentTick != session->GetTick()) {
this->currentTick = session->GetTick();
for (auto &ghost : this->ghostPool) {
if (!ghost.hasFinished) {
if (ghost_sync.GetBool() && !ghost.sameMap) {
return;
}
ghost.UpdateDemoGhost();
}
}
}
}
void DemoGhostPlayer::UpdateGhostsSameMap() {
for (auto &ghost : this->ghostPool) {
ghost.sameMap = engine->GetCurrentMapName() == ghost.GetCurrentMap();
ghost.isAhead = engine->GetMapIndex(ghost.GetCurrentMap()) > engine->GetMapIndex(engine->GetCurrentMapName());
}
}
void DemoGhostPlayer::UpdateGhostsModel(const std::string model) {
if (GhostEntity::ghost_type != GhostType::CIRCLE && GhostEntity::ghost_type != GhostType::PYRAMID) {
for (auto &ghost : this->ghostPool) {
ghost.modelName = model;
ghost.DeleteGhost();
ghost.Spawn();
}
}
}
void DemoGhostPlayer::Sync() {
for (auto &ghost : this->ghostPool) {
if (!ghost.sameMap && !ghost.isAhead) { //isAhead prevents the ghost from restarting if the player load a save after the ghost has finished a chamber
ghost.ChangeDemo();
ghost.LevelReset();
}
}
}
DemoGhostEntity *DemoGhostPlayer::GetGhostByID(int ID) {
for (auto &ghost : this->ghostPool) {
if (ghost.ID == ID) {
return &ghost;
}
}
return nullptr;
}
bool DemoGhostPlayer::SetupGhostFromDemo(const std::string &demo_path, const unsigned int ghost_ID, bool fullGame) {
DemoParser parser;
Demo demo;
std::map<int, DataGhost> datas;
if (parser.Parse(demo_path, &demo, true, &datas)) {
parser.Adjust(&demo);
DemoDatas demoDatas{datas, demo};
DemoGhostEntity *ghost = demoGhostPlayer.GetGhostByID(ghost_ID);
if (ghost == nullptr) { //New fullgame or CM ghost
DemoGhostEntity new_ghost = {ghost_ID, demo.clientName, DataGhost{{0, 0, 0}, {0, 0, 0}}, demo.mapName};
new_ghost.SetFirstLevelDatas(demoDatas);
new_ghost.firstLevel = demo.mapName;
new_ghost.lastLevel = demo.mapName;
new_ghost.totalTicks = demo.playbackTicks;
demoGhostPlayer.AddGhost(new_ghost);
} else { //Only fullGame
ghost->AddLevelDatas(demoDatas);
ghost->lastLevel = demo.mapName;
ghost->totalTicks += demo.playbackTicks;
}
return true;
}
return false;
}
void DemoGhostPlayer::AddGhost(DemoGhostEntity &ghost) {
this->ghostPool.push_back(ghost);
}
bool DemoGhostPlayer::IsPlaying() {
return this->isPlaying;
}
bool DemoGhostPlayer::IsFullGame() {
return this->isFullGame;
}
void DemoGhostPlayer::PrintRecap() {
auto current = 1;
auto total = this->ghostPool.size();
console->Print("Recap of all ghosts :\n");
for (auto &ghost : this->ghostPool) {
console->Msg(" [%i of %i] %s: %s -> %s in %s\n", current++, total, ghost.name.c_str(), ghost.firstLevel.c_str(), ghost.lastLevel.c_str(), SpeedrunTimer::Format(ghost.totalTicks * *engine->interval_per_tick).c_str());
}
}
void DemoGhostPlayer::DrawNames(HudContext *ctx) {
auto player = client->GetPlayer(GET_SLOT() + 1);
if (player) {
//auto pos = client->GetAbsOrigin(player);
for (int i = 0; i < this->ghostPool.size(); ++i) {
if (this->ghostPool[i].sameMap && !this->ghostPool[i].hasFinished && this->ghostPool[i].demoTick <= this->ghostPool[i].nbDemoTicks) {
this->ghostPool[i].DrawName(ctx, i);
}
}
}
}
CON_COMMAND_AUTOCOMPLETEFILE(ghost_set_demo, "ghost_set_demo <demo> [ID] - ghost will use this demo. If ID is specified, will create or modify the ID-th ghost\n", 0, 0, dem) {
if (args.ArgC() < 2) {
return console->Print(ghost_set_demo.ThisPtr()->m_pszHelpString);
}
sf::Uint32 ID = args.ArgC() > 2 ? std::atoi(args[2]) : 0;
demoGhostPlayer.DeleteGhostsByID(ID);
if (demoGhostPlayer.SetupGhostFromDemo(engine->GetGameDirectory() + std::string("/") + args[1], ID, false)) {
console->Print("Ghost successfully created! Final time of the ghost: %s\n", SpeedrunTimer::Format(demoGhostPlayer.GetGhostByID(ID)->GetTotalTime()).c_str());
} else {
console->Print("Could not parse \"%s\"!\n", engine->GetGameDirectory() + std::string("/") + args[1]);
}
demoGhostPlayer.UpdateGhostsSameMap();
demoGhostPlayer.isFullGame = false;
}
CON_COMMAND_AUTOCOMPLETEFILE(ghost_set_demos,
"ghost_set_demos <first_demo> [first_id] [ID] - ghost will setup a speedrun with first_demo, first_demo_2, etc.\n"
"If first_id is specified as e.g. 5, will instead start from first_demo_5, then first_demo_6, etc. Specifying first_id as 1 will use first_demo, first_demo_2 etc as normal.\n"
"If ID is specified, will create or modify the ID-th ghost.\n",
0,
0,
dem) {
if (args.ArgC() < 2) {
return console->Print(ghost_set_demos.ThisPtr()->m_pszHelpString);
}
int firstDemoId = args.ArgC() > 2 ? std::atoi(args[2]) : 0;
sf::Uint32 ID = args.ArgC() > 3 ? std::atoi(args[3]) : 0;
demoGhostPlayer.DeleteGhostsByID(ID);
auto dir = engine->GetGameDirectory() + std::string("/") + args[1];
int counter = firstDemoId > 1 ? firstDemoId : 2;
bool ok = true;
if (firstDemoId < 2) {
ok = std::filesystem::exists(dir + ".dem");
if (!ok || !demoGhostPlayer.SetupGhostFromDemo(dir, ID, true)) {
return console->Print("Could not parse \"%s\"!\n", engine->GetGameDirectory() + std::string("/") + args[1]);
}
}
while (ok) {
auto tmp_dir = dir + "_" + std::to_string(counter) + ".dem";
ok = std::filesystem::exists(tmp_dir);
if (ok && !demoGhostPlayer.SetupGhostFromDemo(tmp_dir, ID, true)) {
return console->Print("Could not parse \"%s\"!\n", tmp_dir.c_str());
}
++counter;
}
console->Print("Ghost successfully created! Final time of the ghost: %s\n", SpeedrunTimer::Format(demoGhostPlayer.GetGhostByID(ID)->GetTotalTime()).c_str());
demoGhostPlayer.UpdateGhostsSameMap();
demoGhostPlayer.isFullGame = true;
}
CON_COMMAND(ghost_delete_by_ID, "ghost_delete_by_ID <ID> - delete the ghost selected\n") {
if (args.ArgC() < 2) {
return console->Print(ghost_delete_by_ID.ThisPtr()->m_pszHelpString);
}
demoGhostPlayer.DeleteGhostsByID(std::atoi(args[1]));
console->Print("Ghost %d has been deleted!\n", std::atoi(args[1]));
}
CON_COMMAND(ghost_delete_all, "ghost_delete_all - delete all ghosts\n") {
demoGhostPlayer.DeleteAllGhostModels();
demoGhostPlayer.DeleteAllGhosts();
console->Print("All ghosts have been deleted!\n");
}
CON_COMMAND(ghost_recap, "ghost_recap - recap all ghosts setup\n") {
demoGhostPlayer.PrintRecap();
}
CON_COMMAND(ghost_start, "ghost_start - start ghosts\n") {
if (engine->GetCurrentMapName().length() == 0 && !engine->demoplayer->IsPlaying()) {
return console->Print("Can't start ghosts in menu.\n");
}
demoGhostPlayer.StartAllGhost();
console->Print("All ghosts have started.\n");
}
CON_COMMAND(ghost_reset, "ghost_reset - reset ghosts\n") {
demoGhostPlayer.ResetAllGhosts();
console->Print("All ghost have been reset.\n");
}
CON_COMMAND(ghost_offset, "ghost_offset <offset> <ID> - delay the ghost start by <offset> frames\n") {
if (args.ArgC() < 2) {
return console->Print(ghost_offset.ThisPtr()->m_pszHelpString);
}
unsigned int ID = args.ArgC() > 2 ? std::atoi(args[2]) : 0;
auto ghost = demoGhostPlayer.GetGhostByID(ID);
if (ghost) {
ghost->offset = -std::atoi(args[1]);
console->Print("Final time of ghost %d: %s\n", ID, SpeedrunTimer::Format(demoGhostPlayer.GetGhostByID(ID)->GetTotalTime()).c_str());
} else {
return console->Print("No ghost with that ID\n");
}
}
ON_EVENT(PRE_TICK) {
if (demoGhostPlayer.IsPlaying() && engine->isRunning()) {
demoGhostPlayer.UpdateGhostsPosition();
}
}
ON_EVENT(SESSION_START) {
if (demoGhostPlayer.IsPlaying()) {
demoGhostPlayer.UpdateGhostsSameMap();
if (demoGhostPlayer.IsFullGame()) {
if (ghost_sync.GetBool()) {
demoGhostPlayer.Sync();
}
} else {
demoGhostPlayer.ResetAllGhosts();
demoGhostPlayer.ResumeAllGhosts();
}
demoGhostPlayer.SpawnAllGhosts();
}
}
| 29.744615 | 221 | 0.684494 | Zyntex1 |
e0dcbc40cbb13b4d70050e4722e5d7ad09e8b3bb | 892 | hpp | C++ | nacl/graph/flows/global-min-cut.hpp | ToxicPie/NaCl | 8cb50bacc25f2b99a33fb5938ea4ec9906d8d65c | [
"MIT"
] | 3 | 2021-08-31T17:51:01.000Z | 2021-11-13T16:22:25.000Z | nacl/graph/flows/global-min-cut.hpp | ToxicPie/NaCl | 8cb50bacc25f2b99a33fb5938ea4ec9906d8d65c | [
"MIT"
] | null | null | null | nacl/graph/flows/global-min-cut.hpp | ToxicPie/NaCl | 8cb50bacc25f2b99a33fb5938ea4ec9906d8d65c | [
"MIT"
] | null | null | null | /// source: KACTL
// weights is an adjacency matrix, undirected
pair<int, vi> getMinCut(vector<vi> &weights) {
int N = sz(weights);
vi used(N), cut, best_cut;
int best_weight = -1;
for (int phase = N - 1; phase >= 0; phase--) {
vi w = weights[0], added = used;
int prev, k = 0;
rep(i, 0, phase) {
prev = k;
k = -1;
rep(j, 1, N) if (!added[j] &&
(k == -1 || w[j] > w[k])) k = j;
if (i == phase - 1) {
rep(j, 0, N) weights[prev][j] += weights[k][j];
rep(j, 0, N) weights[j][prev] = weights[prev][j];
used[k] = true;
cut.push_back(k);
if (best_weight == -1 || w[k] < best_weight) {
best_cut = cut;
best_weight = w[k];
}
} else {
rep(j, 0, N) w[j] += weights[k][j];
added[k] = true;
}
}
}
return {best_weight, best_cut};
}
| 26.235294 | 57 | 0.463004 | ToxicPie |
e0df0273b7c8f10e91f8279b15f3d12f512589b3 | 10,791 | cpp | C++ | src/plugins/robots/attabot/real_robot/real_kheperaiv_camera_sensor.cpp | DiegoD616/argos3-ATTABOT | e909bf1432dbd6649450dbb95e4e9f68f375eefa | [
"MIT"
] | null | null | null | src/plugins/robots/attabot/real_robot/real_kheperaiv_camera_sensor.cpp | DiegoD616/argos3-ATTABOT | e909bf1432dbd6649450dbb95e4e9f68f375eefa | [
"MIT"
] | null | null | null | src/plugins/robots/attabot/real_robot/real_kheperaiv_camera_sensor.cpp | DiegoD616/argos3-ATTABOT | e909bf1432dbd6649450dbb95e4e9f68f375eefa | [
"MIT"
] | null | null | null | #include "real_attabot_camera_sensor.h"
#include <argos3/core/utility/logging/argos_log.h>
using SBlob = CCI_AttabotCameraSensor::SBlob;
using TBlobs = CCI_AttabotCameraSensor::TBlobs;
using TBlobFilters = CRealAttabotCameraSensor::TBlobFilters;
/****************************************/
/****************************************/
static std::string InitErrorMsg(int n_errcode) {
switch(n_errcode) {
case -1:
return "no device /dev/video0";
case -2:
return "no video capture device";
case -3:
return "capabilities error";
case -4:
return "cannot open the device";
case -5:
return "cannot call system for media-ctl pipes";
case -6:
return "media-ctl pipes command exited with error";
case -7:
return "cannot call system for media-ctl formats";
case -8:
return "media-ctl formats command exited with error";
}
return "no error";
}
static std::string CaptureErrorMsg(int n_errcode) {
switch(n_errcode) {
case -1:
return "device not open";
case -2:
return "device not initialised";
case -3:
return "capture start error";
case -4:
return "unknown error";
case -5:
return "error stopping capture";
case -6:
return "read error into frameRead";
case -7:
return "VIDIOC_DQBUF error into frameRead";
case -8:
return "xioctl error into frameRead";
case -9:
return "try again into frameRead";
case -10:
return "buffer size error into frameRead";
}
return "no error";
}
/****************************************/
/****************************************/
static void RGBtoHSV(unsigned char* pch_hsv, unsigned char* pch_rgb) {
UInt8 unCMax = pch_rgb[0] > pch_rgb[1] ? pch_rgb[0] : pch_rgb[1];
unCMax = unCMax > pch_rgb[2] ? unCMax : pch_rgb[2];
UInt8 unCMin = pch_rgb[0] < pch_rgb[1] ? pch_rgb[0] : pch_rgb[1];
unCMin = unCMin < pch_rgb[2] ? unCMin : pch_rgb[2];
UInt8 unDelta = unCMax - unCMin;
/* Value */
pch_hsv[2] = unCMax;
/* Hue */
if(unDelta == 0) {
pch_hsv[0] = 0;
}
else if(unCMax == pch_rgb[0]) {
pch_hsv[0] = 42.5 * Mod((static_cast<Real>(pch_rgb[1]) - static_cast<Real>(pch_rgb[2])) / unDelta, 6);
}
else if(unCMax == pch_rgb[1]) {
pch_hsv[0] = 42.5 * (2 + (static_cast<Real>(pch_rgb[2]) - static_cast<Real>(pch_rgb[0])) / unDelta);
}
else if(unCMax == pch_rgb[2]) {
pch_hsv[0] = 42.5 * (4 + (static_cast<Real>(pch_rgb[0]) - static_cast<Real>(pch_rgb[1])) / unDelta);
}
/* Saturation */
if(pch_hsv[2] == 0) {
pch_hsv[1] = 0;
}
else {
pch_hsv[1] = 255 * static_cast<Real>(unDelta) / pch_hsv[2];
}
}
static ssize_t FilterMatch(TBlobFilters& t_blob_filters,
const unsigned char* pch_hsv) {
for(size_t i = 0; i < t_blob_filters.size(); ++i) {
if(t_blob_filters[i].Match(pch_hsv))
return i;
}
return -1;
}
static SBlob* FindBlob(TBlobs& t_blobs,
UInt32 un_x,
UInt32 un_y,
UInt32 un_tolerance) {
for(size_t i = 0; i < t_blobs.size(); ++i) {
SBlob& sBlob = t_blobs[i];
if(((un_x >= sBlob.Min.GetX() && un_x <= sBlob.Max.GetX()) ||
(Abs(sBlob.Min.GetX() - un_x) < un_tolerance) ||
(Abs(sBlob.Max.GetX() - un_x) < un_tolerance)) &&
((un_y >= sBlob.Min.GetY() && un_y <= sBlob.Max.GetY()) ||
(Abs(sBlob.Min.GetY() - un_y) < un_tolerance) ||
(Abs(sBlob.Max.GetY() - un_y) < un_tolerance))) {
return &sBlob;
}
}
return NULL;
}
static void AddToBlob(SBlob& s_blob,
UInt32 un_x,
UInt32 un_y) {
s_blob.Min.Set(
Min<Real>(s_blob.Min.GetX(), un_x),
Min<Real>(s_blob.Min.GetY(), un_y));
s_blob.Max.Set(
Max<Real>(s_blob.Max.GetX(), un_x),
Max<Real>(s_blob.Max.GetY(), un_y));
}
struct SCameraThreadParams {
unsigned char* ImgBuffer;
UInt32 Width;
UInt32 Height;
TBlobs& WorkBuffer;
TBlobs& ReadyBuffer;
TBlobFilters& Filters;
pthread_mutex_t& Mutex;
bool& NewReadings;
SCameraThreadParams(
unsigned char* pch_img_buffer,
UInt32 un_img_width,
UInt32 un_img_height,
TBlobs& c_blob_work_buffer,
TBlobs& c_blob_ready_buffer,
TBlobFilters& t_blob_filters,
pthread_mutex_t& t_blob_ready_mutex,
bool& b_new_blob_readings) :
ImgBuffer(pch_img_buffer),
Width(un_img_width),
Height(un_img_height),
WorkBuffer(c_blob_work_buffer),
ReadyBuffer(c_blob_ready_buffer),
Filters(t_blob_filters),
Mutex(t_blob_ready_mutex),
NewReadings(b_new_blob_readings) {
}
};
static void* CameraThread(void* pvoid_params) {
/* Get parameters */
SCameraThreadParams* ptParams =
reinterpret_cast<SCameraThreadParams*>(pvoid_params);
/* Data collection loop */
int nErrCode;
while(1) {
/* Cancellation point */
pthread_testcancel();
/* Get frame */
nErrCode = take_one_image(ptParams->ImgBuffer);
if(nErrCode == 0) {
/* Process frame */
unsigned char* pchRGBPx;
unsigned char pchHSVPx[3];
for(UInt32 x = 0; x < ptParams->Width; ++x) {
for(UInt32 y = 0; y < ptParams->Height; ++y) {
/* Cancellation point */
pthread_testcancel();
/* Convert RGB pixel to HSV */
pchRGBPx = ptParams->ImgBuffer + 3 * (ptParams->Width * y + x);
RGBtoHSV(pchHSVPx, pchRGBPx);
/* Check if HSV pixel matches a filter */
ssize_t nFilter = FilterMatch(ptParams->Filters, pchHSVPx);
if(nFilter >= 0) {
/* Yes, check if HSV pixel can be added to an existing blob */
SBlob* psBlob = FindBlob(ptParams->WorkBuffer,
x, y,
ptParams->Filters[nFilter].Tolerance);
if(psBlob) {
/* Yes, add to blob */
AddToBlob(*psBlob, x, y);
}
else {
/* No, create new blob */
ptParams->WorkBuffer.push_back(
SBlob(ptParams->Filters[nFilter].Color,
CVector2(x, y)));
}
}
}
}
/* Done with blobs, make them available */
pthread_mutex_trylock(&ptParams->Mutex);
ptParams->NewReadings = true;
ptParams->ReadyBuffer.swap(ptParams->WorkBuffer);
pthread_mutex_unlock(&ptParams->Mutex);
/* Clear work buffer for new image */
ptParams->WorkBuffer.clear();
}
else {
LOGERR << "[WARNING] Error capturing camera frame: "
<< CaptureErrorMsg(nErrCode)
<< std::endl;
}
}
}
/****************************************/
/****************************************/
CRealAttabotCameraSensor::CRealAttabotCameraSensor(knet_dev_t* pt_dspic) :
CRealAttabotDevice(NULL),
m_bNewBlobReadings(false) {
}
/****************************************/
/****************************************/
CRealAttabotCameraSensor::~CRealAttabotCameraSensor() {
}
/****************************************/
/****************************************/
void CRealAttabotCameraSensor::Init(TConfigurationNode& t_node) {
try {
/* Parse XML */
m_unWidth = 640;
m_unHeight = 480;
GetNodeAttributeOrDefault(t_node, "image_width", m_unWidth, m_unWidth);
GetNodeAttributeOrDefault(t_node, "image_height", m_unHeight, m_unHeight);
/* Initialize camera resources */
int x = kb_camera_init(&m_unWidth, &m_unHeight);
if(x < 0) {
THROW_ARGOSEXCEPTION(InitErrorMsg(x));
}
m_pchImgBuffer = new unsigned char[3 * m_unWidth * m_unHeight];
LOG << "[INFO] Camera initialized with image size ("
<< m_unWidth
<< ","
<< m_unHeight
<< ")" << std::endl;
/* Create data mutex */
if(pthread_mutex_init(&m_tBlobReadyMutex, NULL) != 0) {
kb_camera_release();
delete[] m_pchImgBuffer;
THROW_ARGOSEXCEPTION("pthread_mutex_init: " << strerror(errno));
}
/* Spawn worker thread */
SCameraThreadParams sCameraThreadParams(
m_pchImgBuffer,
m_unWidth,
m_unHeight,
m_tBlobWorkBuffer,
m_tBlobReadyBuffer,
m_tBlobFilters,
m_tBlobReadyMutex,
m_bNewBlobReadings);
if(pthread_create(&m_tThread, NULL, CameraThread, &sCameraThreadParams) != 0) {
pthread_mutex_destroy(&m_tBlobReadyMutex);
kb_camera_release();
delete[] m_pchImgBuffer;
THROW_ARGOSEXCEPTION("pthread_create: " << strerror(errno));
}
LOG << "[INFO] Camera started" << std::endl;
}
catch(CARGoSException& ex) {
THROW_ARGOSEXCEPTION_NESTED("Error initializing the camera", ex);
}
}
/****************************************/
/****************************************/
void CRealAttabotCameraSensor::Destroy() {
/* Release mutex */
pthread_mutex_unlock(&m_tBlobReadyMutex);
/* Stop worker thread */
pthread_cancel(m_tThread);
pthread_join(m_tThread, NULL);
/* Destroy mutex */
pthread_mutex_destroy(&m_tBlobReadyMutex);
/* Release camera resources */
kb_camera_release();
/* Dispose of image buffer */
delete[] m_pchImgBuffer;
LOG << "[INFO] Camera stopped" << std::endl;
}
/****************************************/
/****************************************/
const unsigned char* CRealAttabotCameraSensor::GetPixels() const {
return m_pchImgBuffer;
}
/****************************************/
/****************************************/
void CRealAttabotCameraSensor::Do(Real f_elapsed_time) {
/* Take latest reading from worker thread */
pthread_mutex_trylock(&m_tBlobReadyMutex);
if(m_bNewBlobReadings) {
m_tBlobs.swap(m_tBlobReadyBuffer);
m_bNewBlobReadings = false;
}
pthread_mutex_unlock(&m_tBlobReadyMutex);
}
/****************************************/
/****************************************/
bool CRealAttabotCameraSensor::SBlobFilter::Match(const unsigned char* pch_hsv) {
return
Hue.WithinMinBoundIncludedMaxBoundIncluded(pch_hsv[0]) &&
Saturation.WithinMinBoundIncludedMaxBoundIncluded(pch_hsv[1]) &&
Value.WithinMinBoundIncludedMaxBoundIncluded(pch_hsv[2]);
}
/****************************************/
/****************************************/
| 32.503012 | 108 | 0.545177 | DiegoD616 |
e0e4b534090ee37444ac182878381278e6398224 | 2,352 | cpp | C++ | tests/8bppbackground/src/main.cpp | taellinglin/butano | 13b93c1296970262e047b728496908c036f7e789 | [
"Zlib"
] | null | null | null | tests/8bppbackground/src/main.cpp | taellinglin/butano | 13b93c1296970262e047b728496908c036f7e789 | [
"Zlib"
] | null | null | null | tests/8bppbackground/src/main.cpp | taellinglin/butano | 13b93c1296970262e047b728496908c036f7e789 | [
"Zlib"
] | null | null | null | //#include "bn_sprite_items_cursor_right.h"
//Background, Midground, Foreground
#include "bn_regular_bg_items_cutscene_background.h"
//Scene BGM
#include "bn_music_items.h"
#include "bn_music_actions.h"
#include "bn_sprite_text_generator.h"
#include "bn_core.h"
#include "bn_keypad.h"
#include "info.h"
#include "bn_optional.h"
#include "bn_regular_bg_ptr.h"
#include "bn_regular_bg_actions.h"
#include "bn_regular_bg_builder.h"
#include "bn_regular_bg_attributes.h"
#include "bn_regular_bg_position_hbe_ptr.h"
#include "bn_affine_bg_ptr.h"
#include "bn_affine_bg_map_ptr.h"
#include "bn_string_view.h"
#include "bn_vector.h"
#include "bn_sprite_text_generator.h"
#include "bn_affine_bg_map_cell.h"
#include "variable_8x16_sprite_font.h"
int main()
{
bn::core::init();
bn::sprite_text_generator text_generator(variable_8x16_sprite_font);
//BG0 BG1 BG2 render the background, midground, and foreground on 3 layers.
bn::optional <bn::regular_bg_ptr> cutscene_bg;
cutscene_bg = bn::regular_bg_items::cutscene_background.create_bg(0,16);
cutscene_bg->set_priority(0); //Set the foreground to have priority depth.
//Options
constexpr bn::string_view info_text_lines[] = {
"",
"I started to fall and everything",
"turned to a white fog.",
"The sunset and red light",
"illuminated the ground.",
"The next moment I was in",
"the form of a frog...",
"I am a form shifting wizard,",
"and my name is Oorta",
"",
"",
};
info info("", info_text_lines, text_generator);
info.set_show_always(true);
//Play Cutscene1 BGM
bn::music_items::cutscene_1.play(0.5);
//Scroll the Backgrounds
while(1){
int wait = 512;
while(wait >0){
if(cutscene_bg->y() >-48){
cutscene_bg->set_y(cutscene_bg->y() - 0.5);
}
wait--;
}
info.update();
bn::core::update();
}
cutscene_bg.reset();
};
| 31.783784 | 87 | 0.565901 | taellinglin |
e0f48cb01f68e2d7eeef5120a89dbdac0e6219cf | 12,686 | cpp | C++ | distributed/scheduler/Connection.cpp | taozhijiang/qmf | ed2a46222f7e6113b61fb36ce669190ed6e0965a | [
"Apache-2.0"
] | 1 | 2020-05-03T09:23:58.000Z | 2020-05-03T09:23:58.000Z | distributed/scheduler/Connection.cpp | taozhijiang/qmf | ed2a46222f7e6113b61fb36ce669190ed6e0965a | [
"Apache-2.0"
] | null | null | null | distributed/scheduler/Connection.cpp | taozhijiang/qmf | ed2a46222f7e6113b61fb36ce669190ed6e0965a | [
"Apache-2.0"
] | null | null | null |
/*-
* Copyright (c) 2020 taozhijiang@gmail.com
*
* Licensed under the BSD-3-Clause license, see LICENSE for full information.
*
*/
#include <fcntl.h>
#include <distributed/scheduler/Connection.h>
#include <distributed/scheduler/Scheduler.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#include <distributed/proto/task.pb.h>
#include <distributed/common/SendOps.h>
#include <distributed/common/RecvOps.h>
#include <glog/logging.h>
namespace distributed {
namespace scheduler {
bool Connection::event() {
if (stage_ == Stage::kHead) {
char* ptr = reinterpret_cast<char*>(&head_);
// need to read more
if (head_idx_ < kHeadSize) {
int len = ::read(socket_, ptr + head_idx_, kHeadSize - head_idx_);
if (len == -1) {
LOG(ERROR) << "read head failed for " << addr();
return false;
} else if (len == 0) {
LOG(ERROR) << "peer closed " << addr();
return false;
}
head_idx_ += len;
// need additional read
if (head_idx_ < kHeadSize) {
return true;
}
}
// prase net header
head_.from_net_endian();
if (!head_.validate()) {
LOG(ERROR) << "message header magic, version, length check failed."
<< head_.dump();
return false;
}
VLOG(3) << "read head successful, transmit to kBody: " << addr();
stage_ = Stage::kBody;
return handle_head();
} else if (stage_ == Stage::kBody) {
// need to read more
if (data_idx_ < head_.length) {
// reserve more space
if (data_.size() < head_.length)
data_.resize(head_.length);
char* ptr = data_.data();
if (!ptr) {
LOG(ERROR) << "Bug me! reserved data_ pointer to nullptr...";
return false;
}
int len = ::read(socket_, ptr + data_idx_, head_.length - data_idx_);
if (len == -1) {
LOG(ERROR) << "read data failed for " << addr();
return false;
} else if (len == 0) {
LOG(ERROR) << "peer closed " << addr();
return false;
}
// normal read
data_idx_ += len;
// need additional read
if (data_idx_ < head_.length) {
return true;
}
VLOG(3) << "read head successful, transmit to kDone: " << addr();
stage_ = Stage::kDone;
return handle_body();
}
// If new message here, we not process currently;
return true;
}
LOG(ERROR) << "uknown stage_: " << static_cast<int>(stage_);
return false;
}
bool Connection::handle_head() {
bool retval = true;
switch (head_.opcode) {
case static_cast<int>(OpCode::kSubmitTask):
case static_cast<int>(OpCode::kAttachLabor):
case static_cast<int>(OpCode::kPushRateRsp):
case static_cast<int>(OpCode::kPushFixedRsp):
case static_cast<int>(OpCode::kCalcRsp):
case static_cast<int>(OpCode::kInfoRsp):
break;
case static_cast<int>(OpCode::kSubmitTaskRsp):
case static_cast<int>(OpCode::kAttachLaborRsp):
case static_cast<int>(OpCode::kPushRate):
case static_cast<int>(OpCode::kPushFixed):
case static_cast<int>(OpCode::kCalc):
case static_cast<int>(OpCode::kHeartBeat):
default:
LOG(FATAL) << "invalid OpCode received by scheduler:"
<< static_cast<int>(head_.opcode);
retval = false;
break;
}
return retval;
}
bool Connection::handle_body() {
bool retval = true;
this->touch();
switch (head_.opcode) {
case static_cast<int>(OpCode::kSubmitTask): {
std::string message = std::string(data_.data(), data_idx_);
VLOG(3) << "kSubmitTask recv with " << message;
is_labor_ = false;
bool success = false;
do {
std::string taskfile = std::string(data_.data(), data_idx_);
int taskfd = ::open(taskfile.c_str(), O_RDONLY);
if (taskfd < 0) {
LOG(ERROR) << "read task file failed " << taskfile;
break;
}
auto task = std::make_shared<TaskDef>();
if (!task) {
LOG(ERROR) << "create TaskDef failed.";
break;
}
google::protobuf::io::FileInputStream finput(taskfd);
finput.SetCloseOnDelete(true);
if (!google::protobuf::TextFormat::Parse(&finput, task.get())) {
LOG(ERROR) << "parse task file failed " << taskfile;
break;
}
scheduler_.add_task(task);
success = true;
LOG(INFO) << "add new task successfully: " << taskfile;
} while (0);
reset();
message = success ? "OK" : "FA";
SendOps::send_message(socket_, OpCode::kSubmitTaskRsp, message);
break;
}
case static_cast<int>(OpCode::kAttachLabor): {
std::string message = std::string(data_.data(), data_idx_);
VLOG(3) << "kAttachLabor recv with " << message;
is_labor_ = true;
reset();
message = "attach_labor_rsp_ok";
SendOps::send_message(socket_, OpCode::kAttachLaborRsp, message);
break;
}
case static_cast<int>(OpCode::kPushRateRsp): {
std::string message = std::string(data_.data(), data_idx_);
VLOG(3) << "kPushRateRsp recv with " << message;
if (message == "OK") {
LOG(INFO) << "kPushRateRsp return OK, update our status";
taskid_ = head_.taskid;
epchoid_ = head_.epchoid;
}
reset();
break;
}
case static_cast<int>(OpCode::kPushFixedRsp): {
std::string message = std::string(data_.data(), data_idx_);
VLOG(3) << "kPushFixedRsp recv with " << message;
if (message == "OK") {
LOG(INFO) << "kPushFixedRsp OK from " << addr() << ", update our status";
taskid_ = head_.taskid;
epchoid_ = head_.epchoid;
}
reset();
break;
}
case static_cast<int>(OpCode::kCalcRsp): {
auto& bigdata_ptr = scheduler_.bigdata_ptr();
auto& engine_ptr = scheduler_.engine_ptr();
// note: we can not download the data directly to the destination, because
// we should check whether the result is valid
VLOG(3) << "already recv data size: " << data_idx_;
do {
// the result is not our desire, drop and return
if (head_.taskid != bigdata_ptr->taskid() ||
head_.epchoid != bigdata_ptr->epchoid()) {
LOG(ERROR) << "unmatch calc response: " << head_.dump();
break;
}
// copy the result to the destination, and then update bucket_bits_
char* dest = nullptr;
uint64_t len = 0;
bool iterate_user = bigdata_ptr->epchoid() % 2;
if (iterate_user) {
const uint64_t start_idx = head_.bucket * kBucketSize;
const uint64_t end_idx =
std::min<uint64_t>(start_idx + kBucketSize, engine_ptr->nusers());
// users factors
const qmf::Matrix& matrix = bigdata_ptr->user_factor_ptr_->getFactors();
dest = reinterpret_cast<char*>(
const_cast<qmf::Matrix&>(matrix).data(start_idx));
len = (end_idx - start_idx) * sizeof(qmf::Double) * head_.nfactors;
if (len != head_.length) {
LOG(ERROR) << "length check failed, expect " << len << ", but get "
<< head_.length;
dest = nullptr;
break;
}
} else {
const uint64_t start_idx = head_.bucket * kBucketSize;
const uint64_t end_idx =
std::min<uint64_t>(start_idx + kBucketSize, engine_ptr->nitems());
// items factors
const qmf::Matrix& matrix = bigdata_ptr->item_factor_ptr_->getFactors();
dest = reinterpret_cast<char*>(
const_cast<qmf::Matrix&>(matrix).data(start_idx));
len = (end_idx - start_idx) * sizeof(qmf::Double) * head_.nfactors;
if (len != head_.length) {
LOG(ERROR) << "length check failed, expect " << len << ", but get "
<< head_.length;
dest = nullptr;
break;
}
}
if (dest && len) {
// this bucket calculate successfully, we update the time cost to
// the bigdata for stale estimate.
::memcpy(dest, data_.data(), len);
bigdata_ptr->bucket_bits_[head_.bucket] = true;
time_t cost = ::time(NULL) - bucket_start_;
LOG(INFO) << "bucket calculate task " << head_.stepinfo()
<< " successfully, time cost " << cost << " secs. ";
}
} while (0);
reset();
break;
}
case static_cast<int>(OpCode::kInfoRsp): {
// this is the backup schema part
// when Labors receive the kHeartBeat message, or the Scheduler's request
// check failed, then the Labor will send its local taskid and epchoid,
// indicates the already received data, then Scheduler can decide whether
// the Labor is in stale status.
auto& bigdata_ptr = scheduler_.bigdata_ptr();
do {
if (head_.taskid != bigdata_ptr->taskid()) {
LOG(INFO) << "found remote taskid: " << head_.taskid
<< ", update it with " << bigdata_ptr->taskid();
if (lock_socket_.test_and_set()) {
LOG(INFO) << "connection socket used by other ..." << addr();
break;
}
VLOG(3) << "== LUCKY resent task " << bigdata_ptr->taskid()
<< " rating to remote " << addr();
const auto& dataset = bigdata_ptr->rating_vec_;
const char* dat = reinterpret_cast<const char*>(dataset.data());
uint64_t len = sizeof(dataset[0]) * dataset.size();
if (!SendOps::send_bulk(
socket_, OpCode::kPushRate, dat, len, bigdata_ptr->taskid(),
bigdata_ptr->epchoid(), bigdata_ptr->nfactors(), 0,
bigdata_ptr->lambda(), bigdata_ptr->confidence())) {
LOG(ERROR) << "fallback sending rating to " << addr() << " failed.";
}
lock_socket_.clear();
} else if (head_.epchoid != bigdata_ptr->epchoid()) {
LOG(INFO) << "found for taskid " << head_.taskid
<< ", remote epchoid: " << head_.epchoid
<< ", update it with " << bigdata_ptr->epchoid();
if (lock_socket_.test_and_set()) {
LOG(INFO) << "connection socket used by other ..." << addr();
break;
}
VLOG(3) << "== LUCKY resent fixedfactor " << bigdata_ptr->taskid()
<< ":" << bigdata_ptr->epchoid() << " rating to remote "
<< addr();
const char* dat = nullptr;
uint64_t len = 0;
if (bigdata_ptr->epchoid() % 2) {
const qmf::Matrix& matrix =
bigdata_ptr->item_factor_ptr_->getFactors();
dat = reinterpret_cast<const char*>(
const_cast<qmf::Matrix&>(matrix).data());
len =
sizeof(qmf::Matrix::value_type) * matrix.nrows() * matrix.ncols();
LOG(INFO) << "epcho_id " << bigdata_ptr->epchoid()
<< " transform itemFactors with size " << len;
} else {
const qmf::Matrix& matrix =
bigdata_ptr->user_factor_ptr_->getFactors();
dat = reinterpret_cast<const char*>(
const_cast<qmf::Matrix&>(matrix).data());
len =
sizeof(qmf::Matrix::value_type) * matrix.nrows() * matrix.ncols();
LOG(INFO) << "epcho_id " << bigdata_ptr->epchoid()
<< " transform userFactors with size " << len;
}
if (!SendOps::send_bulk(
socket_, OpCode::kPushFixed, dat, len, bigdata_ptr->taskid(),
bigdata_ptr->epchoid(), bigdata_ptr->nfactors(), 0,
bigdata_ptr->lambda(), bigdata_ptr->confidence())) {
LOG(ERROR) << "fallback sending fixed to " << addr() << " failed.";
}
lock_socket_.clear();
} else {
// GOOD, latest info for this connection.
// don't forget to update the latest labor information to our Scheduler
// local record
std::string message = std::string(data_.data(), data_idx_);
VLOG(3) << "kPushFixedRsp recv with " << message;
if (message == "OK") {
LOG(INFO) << "kPushFixedRsp OK from " << addr()
<< ", update our status";
taskid_ = head_.taskid;
epchoid_ = head_.epchoid;
}
reset();
break;
}
} while (0);
reset();
break;
}
case static_cast<int>(OpCode::kSubmitTaskRsp):
case static_cast<int>(OpCode::kAttachLaborRsp):
case static_cast<int>(OpCode::kPushRate):
case static_cast<int>(OpCode::kPushFixed):
case static_cast<int>(OpCode::kCalc):
case static_cast<int>(OpCode::kHeartBeat):
default:
LOG(FATAL) << "invalid OpCode received by Scheduler:"
<< static_cast<int>(head_.opcode);
retval = false;
break;
}
return retval;
}
} // end namespace scheduler
} // end namespace distributed
| 29.297921 | 80 | 0.581744 | taozhijiang |
e0f65529003410e0b8be7001bf787223b834ecd2 | 312 | cpp | C++ | pattern.cpp | shoharto/cpp | 5e2e1a8341d16477e25618f52687324c3cec5acc | [
"Unlicense",
"MIT"
] | null | null | null | pattern.cpp | shoharto/cpp | 5e2e1a8341d16477e25618f52687324c3cec5acc | [
"Unlicense",
"MIT"
] | 3 | 2021-09-28T05:32:13.000Z | 2022-02-26T09:55:15.000Z | pattern.cpp | shoharto/cpp | 5e2e1a8341d16477e25618f52687324c3cec5acc | [
"Unlicense",
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter The Number: " << endl;
cin >> num;
for (int row = 1; row <= num; row++)
{
for (int col = 1; col <= row; col++)
{
cout << " "<< row;
}
cout<<endl;
}
return 0;
} | 15.6 | 44 | 0.426282 | shoharto |
e0f704d1565df66a1512ce84d6c8fe6b7979e0d2 | 917 | cpp | C++ | CPPSolutions/Hackerrank/BetweenTwoSets.cpp | Dilbarjot/CP | 2395c6c270e53277a7a020e5b467e517353bc229 | [
"MIT"
] | null | null | null | CPPSolutions/Hackerrank/BetweenTwoSets.cpp | Dilbarjot/CP | 2395c6c270e53277a7a020e5b467e517353bc229 | [
"MIT"
] | null | null | null | CPPSolutions/Hackerrank/BetweenTwoSets.cpp | Dilbarjot/CP | 2395c6c270e53277a7a020e5b467e517353bc229 | [
"MIT"
] | null | null | null | /**
** Created by dilbar on 2021-01-17
** Problem: https://www.hackerrank.com/challenges/between-two-sets/problem
**/
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
int getTotalX(vector<int> a, vector<int> b) {
int l = a.back();
int u = b.front();
int sol = 0;
for (int i = l; i <= u; i++) {
int j, k;
for (j = 0; j < a.size(); j++) {
int c = a.at(j);
if (i % c != 0) {
break;
}
}
for (k = 0; k < b.size(); k++) {
int c = b.at(k);
if (c % i != 0) {
break;
}
}
if (j == a.size() && k == b.size()) {
sol++;
}
}
return sol;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
vi v = {2, 4};
vi v2 = {16, 32, 96};
cout << getTotalX(v, v2) << "\n";
return 0;
}
| 20.377778 | 75 | 0.411123 | Dilbarjot |
803d8447a1e8dfad902e1eee9b3e653d77a91b69 | 7,965 | hpp | C++ | c++/Ail/PoolManager.hpp | aamshukov/miscellaneous | 6fc0d2cb98daff70d14f87b2dfc4e58e61d2df60 | [
"MIT"
] | null | null | null | c++/Ail/PoolManager.hpp | aamshukov/miscellaneous | 6fc0d2cb98daff70d14f87b2dfc4e58e61d2df60 | [
"MIT"
] | null | null | null | c++/Ail/PoolManager.hpp | aamshukov/miscellaneous | 6fc0d2cb98daff70d14f87b2dfc4e58e61d2df60 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////
//......................................................................................
// This is a part of AI Library [Arthur's Interfaces Library]. .
// 1998-2001 Arthur Amshukov .
//......................................................................................
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND .
// DO NOT REMOVE MY NAME AND THIS NOTICE FROM THE SOURCE .
//......................................................................................
////////////////////////////////////////////////////////////////////////////////////////
#ifndef __POOL_MANAGER_H__
#define __POOL_MANAGER_H__
#pragma once
__BEGIN_NAMESPACE__
////////////////////////////////////////////////////////////////////////////////////////
#pragma pack(push, before, 2)
////////////////////////////////////////////////////////////////////////////////////////
// class PoolManager
// ----- -----------
template <typename _Media = File<>, typename _Mutex = Synchronization::ThreadMutex<>, typename _Allocator = StandardAllocator> class PoolManager
{
private:
enum EDefConst
{
PageSize = 512, // size of page
CacheSize = 32, // how many pages in cache
AheadCount = 4 // how many pages read/write ahead
};
/////////////////////
// class KeyExtractor
// ----- ------------
template <typename _T, typename _Key> struct KeyExtractor
{
const _Key& operator () (const _T& _val) const { return _val.GetKey(); }
};
///////////////////
// class Comparator
// ----- ----------
template <typename _Key> struct Comparator
{
int operator () (const _Key& _k1, const _Key& _k2) const { return _k1 < _k2 ? -1 : _k1 == _k2 ? 0 : 1; }
};
//////////////
// class _Page
// ----- -----
class _Page : public TreeNodeBase<_Page, uint>, public ListNodeBase<_Page, uint>
{
friend class PoolManager<_Media, _Mutex, _Allocator>;
private:
enum EPageState
{
PageFree = 0x00, // page is free
PageDirty = 0x01, // page was modified
PageBusy = 0x02, // page is reading/writing from/to storage
PageWait = 0x04, // some tasks are waiting for page
PageLocked = 0x08 // do not remove page from memory
};
private:
uint Id; // number of page
uint State; // dirty, busy, wait
_time TimeStamp; // time stamp of page
uint UsageCount; // least used page will be deleted
byte* Data; // actual data
public:
_Page(uint _id) : Id(_id),
State(PoolManager::PageFree),
TimeStamp(Time::GetCurrentTime().GetTime()),
Count(0),
Data(this+sizeof(*this))
{
}
~_Page()
{
}
const uint& GetKey() const { return Id; }
};
//
typedef Synchronization::NullThreadMutex<> _NullMutex;
typedef Synchronization::Event<> _Event;
typedef KeyExtractor<_Page, uint> _KeyExtractor;
typedef Comparator<uint> _Comparator;
typedef Allocator<_NullMutex, _Allocator> _PageAllocator;
typedef AVLTree<_Page, uint, _KeyExtractor, _Comparator, _NullMutex, _PageAllocator> _PageManager;
typedef List<_Page, uint, _KeyExtractor, _Comparator, _NullMutex, _PageAllocator> _LRU_Manager;
//
private:
uint PageSize; // size of page
uint PageCount; // how many pages now in memory (-1 in memory database)
uint CacheSize; // how many pages in memory (-1 in memory database)
uint AheadCount; // how many pages read/write ahead
uint Flags; // flags
_Media Media; // media (file, memory or whatever)
_Mutex Mutex; // synchronization monitor
_Event Event; // prevent concurrent reading/writing of page
_PageAllocator PageAllocator; // allocates continuous memory block and places pages in it
_PageManager PageManager; // AVL tree
_LRU_Manager LRU_Manager; // LRU/MRU discipline (head-MRU, tail-LRU)
_KeyExtractor KeyExtractor; // key extractor for ADT
_Comparator Comparator; // key comparator for ADT
private:
_Page* ConstructPage(uint);
void DestroyPage(_Page*);
public:
enum EFlag
{
ZeroOut = 0x00000001, // page is filled out with zero (create/destroy)
ReadAhead = 0x00000002, // mechanism read ahead (round up to system disk page)
WriteAhead = 0x00000004, // mechanism write ahead (round up to system disk page)
WriteBehind = 0x00000008, // on - mechanism write behind (lazy flush)
// off - mechanism write through (immediately flush)
WriteSorting = 0x00000010, // reorder writes to minimize rotational delays
SequentialAccess = 0x00000020, // optimization for sequential access
RandowAccess = 0x00000040, // optimization for random access
};
public:
// ctor/dtor
PoolManager(uint = PoolManager::ReadAhead|PoolManager::WriteAhead|PoolManager::WriteBehind,
const tchar* = null,
uint = Synchronization::TimeoutNoLimit,
uint = 0,
uint = 64);
virtual ~PoolManager();
// access
uint GetPageSize() const;
void SetPageSize(uint);
uint GetPageCount() const;
uint GetCacheSize() const;
void SetCacheSize(uint);
uint GetAheadCount() const;
void SetAheadCount(uint);
uint GetFlags() const;
void SetFlags(uint);
//
const _Media& GetMedia() const;
// protocol
void Create(const tchar*, uint = _Media::CreateNew|_Media::AccessReadWrite|_Media::ShareExclusive|_Media::WriteThrough, uint = -1, uint = -1, uint = -1, uint = 64);
void Open(const tchar*, uint = _Media::AccessReadWrite|_Media::ShareExclusive, uint = -1, uint = -1, uint = -1, uint = 64);
void Close();
void LockPage(uint);
void LockRange(_fpos_t, _fsize_t);
void UnlockRange(_fpos_t, _fsize_t);
uint Read(void*, ulong, _fpos_t = -1);
uint Write(const void*, ulong, _fpos_t = -1);
void Flush();
};
////////////////////////////////////////////////////////////////////////////////////////
// class XPoolManager
// ----- ------------
class XPoolManager : public X
{
public:
XPoolManager(uint = X::Failure);
~XPoolManager();
};
////////////////////////////////////////////////////////////////////////////////////////
#pragma pack(pop, before)
////////////////////////////////////////////////////////////////////////////////////////
__END_NAMESPACE__
#endif // __POOL_MANAGER_H__
| 43.52459 | 183 | 0.452354 | aamshukov |
803e78bb5ce0d3fb57a608b9845294c68c810ad2 | 406 | hpp | C++ | include/rua/thread/wait/posix.hpp | yulon/rua | acb14aa0e60b68f09e88c726965552f7f4f5ace0 | [
"MIT"
] | null | null | null | include/rua/thread/wait/posix.hpp | yulon/rua | acb14aa0e60b68f09e88c726965552f7f4f5ace0 | [
"MIT"
] | null | null | null | include/rua/thread/wait/posix.hpp | yulon/rua | acb14aa0e60b68f09e88c726965552f7f4f5ace0 | [
"MIT"
] | null | null | null | #ifndef _RUA_THREAD_WAIT_POSIX_HPP
#define _RUA_THREAD_WAIT_POSIX_HPP
#include "../basic/posix.hpp"
#include "../../sched/await.hpp"
#include <pthread.h>
namespace rua { namespace posix {
inline generic_word thread::wait() {
if (!_id) {
return nullptr;
}
void *retval;
if (await(pthread_join, _id, &retval)) {
return nullptr;
}
reset();
return retval;
}
}} // namespace rua::posix
#endif
| 15.037037 | 41 | 0.692118 | yulon |
8041e803aa2936385916ee21939a086828559b13 | 730 | hpp | C++ | PUTM_EV_TELEMETRY_2022/Core/Inc/lib/CanHeaders/PM08-CANBUS-AQ_CARD.hpp | PUT-Motorsport/PUTM_EV_TELEMETRY_2022 | 808ed3e7c9b4263b541a804233e5905f6a9b4240 | [
"Apache-2.0"
] | null | null | null | PUTM_EV_TELEMETRY_2022/Core/Inc/lib/CanHeaders/PM08-CANBUS-AQ_CARD.hpp | PUT-Motorsport/PUTM_EV_TELEMETRY_2022 | 808ed3e7c9b4263b541a804233e5905f6a9b4240 | [
"Apache-2.0"
] | null | null | null | PUTM_EV_TELEMETRY_2022/Core/Inc/lib/CanHeaders/PM08-CANBUS-AQ_CARD.hpp | PUT-Motorsport/PUTM_EV_TELEMETRY_2022 | 808ed3e7c9b4263b541a804233e5905f6a9b4240 | [
"Apache-2.0"
] | 1 | 2021-11-22T20:06:58.000Z | 2021-11-22T20:06:58.000Z | //Generated on Sat Apr 30 12:45:21 2022
#ifndef AQ
#define AQ
#include <cstdint>
#include "lib/message_abstraction.hpp"
enum struct AQ_states: uint8_t {
Power_up,
Normal_operation,
Sensor_impossibility,
};
struct __attribute__ ((packed)) AQ_main{
uint16_t adc_susp_right;
uint16_t adc_susp_left; // i brake balance
uint8_t brake_pressure_front; // pressure of braking lquid front in %
uint8_t brake_pressure_back; // pressure of braking lquid back in %
};
const uint16_t AQ_MAIN_CAN_ID = 0x5f;
const uint8_t AQ_MAIN_CAN_DLC = sizeof(AQ_main);
const uint8_t AQ_MAIN_FREQUENCY = 100;
const CAN_TxHeaderTypeDef can_tx_header_AQ_MAIN{
AQ_MAIN_CAN_ID, 0xFFF, CAN_ID_STD, CAN_RTR_DATA, AQ_MAIN_CAN_DLC, DISABLE};
#endif
| 23.548387 | 75 | 0.787671 | PUT-Motorsport |
8043f8454db65de0d7c09500f1dc8d766a0b08ba | 6,253 | cpp | C++ | Extern/mssdk_dx7/samples/Multimedia/DInput/src/MouseNon/mousenon.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 1,040 | 2021-07-27T12:12:06.000Z | 2021-08-02T14:24:49.000Z | Extern/mssdk_dx7/samples/Multimedia/DInput/src/MouseNon/mousenon.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 20 | 2021-07-27T12:25:22.000Z | 2021-08-02T12:22:19.000Z | Extern/mssdk_dx7/samples/Multimedia/DInput/src/MouseNon/mousenon.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 71 | 2021-07-27T14:19:49.000Z | 2021-08-02T05:51:52.000Z | //-----------------------------------------------------------------------------
// File: MouseNon.cpp
//
// Desc: Demonstrates an application which receives relative mouse data
// in non-exclusive mode via a dialog timer.
//
// Copyright (c) 1998-1999 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#define INITGUID
#include "MouseNon.h"
#include "resource.h"
//-----------------------------------------------------------------------------
// Global variables for the DirectMusic sample
//-----------------------------------------------------------------------------
IDirectInput* g_pDI = NULL;
IDirectInputDevice* g_pMouse = NULL;
HINSTANCE g_hInst = NULL;
BOOL g_bActive = TRUE;
//-----------------------------------------------------------------------------
// Function: InitDirectInput
//
// Description:
// Initialize the DirectInput variables.
//
//-----------------------------------------------------------------------------
HRESULT InitDirectInput( HWND hDlg )
{
HRESULT hr;
// Register with the DirectInput subsystem and get a pointer
// to a IDirectInput interface we can use.
hr = DirectInputCreate( g_hInst, DIRECTINPUT_VERSION, &g_pDI, NULL );
if ( FAILED(hr) )
return hr;
// Obtain an interface to the system mouse device.
hr = g_pDI->CreateDevice( GUID_SysMouse, &g_pMouse, NULL );
if ( FAILED(hr) )
return hr;
// Set the data format to "mouse format" - a predefined data format
//
// A data format specifies which controls on a device we
// are interested in, and how they should be reported.
//
// This tells DirectInput that we will be passing a
// DIMOUSESTATE structure to IDirectInputDevice::GetDeviceState.
hr = g_pMouse->SetDataFormat( &c_dfDIMouse );
if ( FAILED(hr) )
return hr;
// Set the cooperativity level to let DirectInput know how
// this device should interact with the system and with other
// DirectInput applications.
hr = g_pMouse->SetCooperativeLevel( hDlg,
DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);
if ( FAILED(hr) )
return hr;
return S_OK;
}
//-----------------------------------------------------------------------------
// Function: SetAcquire
//
// Description:
// Acquire or unacquire the mouse, depending on if the app is active
// Input device must be acquired before the GetDeviceState is called
//
//-----------------------------------------------------------------------------
HRESULT SetAcquire( HWND hDlg )
{
char szText[128];
HWND hDlgText;
// nothing to do if g_pMouse is NULL
if (NULL == g_pMouse)
return S_FALSE;
if (g_bActive)
{
// acquire the input device
g_pMouse->Acquire();
}
else
{
// update the dialog text
strcpy( szText, "Unacquired" );
hDlgText = GetDlgItem( hDlg, IDC_MOUSE_STATE );
SetWindowText( hDlgText, szText );
// unacquire the input device
g_pMouse->Unacquire();
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Function: UpdateInputState
//
// Description:
// Get the input device's state and display it.
//
//-----------------------------------------------------------------------------
HRESULT UpdateInputState( HWND hDlg )
{
char szOldText[128]; // previous mouse state text
char szNewText[128]; // current mouse state text
HWND hDlgText; // handle to static text box
if (NULL != g_pMouse)
{
DIMOUSESTATE dims; // DirectInput mouse state structure
HRESULT hr;
hr = DIERR_INPUTLOST;
// if input is lost then acquire and keep trying
while ( DIERR_INPUTLOST == hr )
{
// get the input's device state, and put the state in dims
hr = g_pMouse->GetDeviceState( sizeof(DIMOUSESTATE), &dims );
if ( hr == DIERR_INPUTLOST )
{
// DirectInput is telling us that the input stream has
// been interrupted. We aren't tracking any state
// between polls, so we don't have any special reset
// that needs to be done. We just re-acquire and
// try again.
hr = g_pMouse->Acquire();
if ( FAILED(hr) )
return hr;
}
}
if ( FAILED(hr) )
return hr;
// The dims structure now has the state of the mouse, so
// display mouse coordinates (x, y, z) and buttons.
wsprintf( szNewText, "(%d, %d, %d) %c %c %c %c",
dims.lX, dims.lY, dims.lZ,
(dims.rgbButtons[0] & 0x80) ? '0' : ' ',
(dims.rgbButtons[1] & 0x80) ? '1' : ' ',
(dims.rgbButtons[2] & 0x80) ? '2' : ' ',
(dims.rgbButtons[3] & 0x80) ? '3' : ' ');
// if anything changed then repaint - avoid flicker
hDlgText = GetDlgItem( hDlg, IDC_MOUSE_STATE );
GetWindowText( hDlgText, szOldText, 255 );
if ( 0 != lstrcmp( szOldText, szNewText ) )
{
// set the text on the dialog
SetWindowText( hDlgText, szNewText );
}
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Function: FreeDirectInput
//
// Description:
// Initialize the DirectInput variables.
//
//-----------------------------------------------------------------------------
HRESULT FreeDirectInput()
{
// Unacquire and release any DirectInputDevice objects.
if (NULL != g_pMouse)
{
// Unacquire the device one last time just in case
// the app tried to exit while the device is still acquired.
g_pMouse->Unacquire();
g_pMouse->Release();
g_pMouse = NULL;
}
// Release any DirectInput objects.
if (NULL != g_pDI)
{
g_pDI->Release();
g_pDI = NULL;
}
return S_OK;
}
| 29.91866 | 79 | 0.489845 | Ybalrid |
804701c8137503507627112e52df23e851cd5eb7 | 6,690 | cpp | C++ | sample/console/esm_md.cpp | eel3/esm | da2f4a62e27896a0931b4a82f3b5ee428d5d8e9b | [
"Zlib"
] | 1 | 2020-01-11T10:34:18.000Z | 2020-01-11T10:34:18.000Z | sample/console/esm_md.cpp | eel3/esm | da2f4a62e27896a0931b4a82f3b5ee428d5d8e9b | [
"Zlib"
] | null | null | null | sample/console/esm_md.cpp | eel3/esm | da2f4a62e27896a0931b4a82f3b5ee428d5d8e9b | [
"Zlib"
] | null | null | null | /* ********************************************************************** */
/**
* @brief ESM: machdep implementation (sample && test application).
* @author eel3
* @date 2017-10-18
*/
/* ********************************************************************** */
#include "esm_md.h"
#include <cassert>
#include <chrono>
#include <mutex>
namespace {
/* ---------------------------------------------------------------------- */
/* Data structures */
/* ---------------------------------------------------------------------- */
/** Module context type. */
struct MODULE_CTX {
bool initialized;
bool prepared;
ESM_MESSAGE_CELL messages[ESM_CFG_MAX_MESSAGE];
std::mutex mutex_for_api;
MODULE_CTX() : initialized(false), prepared(false) {}
};
/* ---------------------------------------------------------------------- */
/* File scope variables */
/* ---------------------------------------------------------------------- */
/** Module context. */
MODULE_CTX module_ctx;
/* ---------------------------------------------------------------------- */
/* Template Functions */
/* ---------------------------------------------------------------------- */
/* ====================================================================== */
/**
* @brief Return the maximum number of elements.
*
* @param[in] (no_parameter_name) An array.
*
* @return Maximum number of elements.
*/
/* ====================================================================== */
template <typename T, size_t N>
inline size_t
NELEMS(const T (&)[N])
{
return N;
}
} // namespace
/* ---------------------------------------------------------------------- */
/* Functions */
/* ---------------------------------------------------------------------- */
extern "C" {
/* ********************************************************************** */
/**
* @brief Initialize the machdep library.
*
* @retval ESM_E_OK Exit success.
* @retval ESM_E_RES No system resources.
* @retval ESM_E_STATUS Internal status error.
* @retval ESM_E_SYS Error caused by underlying library routines.
*
* @note This function will be called in esm_Initialize().
*/
/* ********************************************************************** */
ESM_ERR
esm_md_Initialize(void)
{
auto& mc = module_ctx;
if (mc.initialized) {
return ESM_E_STATUS;
}
mc.prepared = false;
mc.initialized = true;
return ESM_E_OK;
}
/* ********************************************************************** */
/**
* @brief Finalize the machdep library.
*
* @note This function will be called in esm_Finalize().
*/
/* ********************************************************************** */
void
esm_md_Finalize(void)
{
auto& mc = module_ctx;
if (!mc.initialized) {
return;
}
mc.initialized = false;
}
/* ********************************************************************** */
/**
* @brief Prepare the machdep library before main loop.
*
* @retval ESM_E_OK Exit success.
* @retval ESM_E_STATUS Internal status error.
*
* @note This function will be called in esm_PrepareBeforeMainLoop().
*/
/* ********************************************************************** */
ESM_ERR
esm_md_PrepareBeforeMainLoop(void)
{
auto& mc = module_ctx;
assert(mc.initialized);
if (mc.prepared) {
return ESM_E_STATUS;
}
for (size_t i { 0 }; i < NELEMS(mc.messages); i++) {
mc.messages[i].empty = true;
}
mc.prepared = true;
return ESM_E_OK;
}
/* ********************************************************************** */
/**
* @brief Cleanup the machdep library after main loop.
*
* @retval ESM_E_OK Exit success.
* @retval ESM_E_STATUS Internal status error.
*
* @note This function will be called in esm_CleanupAfterMainLoop().
*/
/* ********************************************************************** */
ESM_ERR
esm_md_CleanupAfterMainLoop(void)
{
auto& mc = module_ctx;
assert(mc.initialized);
if (!mc.prepared) {
return ESM_E_STATUS;
}
mc.prepared = false;
return ESM_E_OK;
}
/* ********************************************************************** */
/**
* @brief Allocate memory space for ESM_MESSAGE_CELL type.
*
* @retval !=NULL Exit success.
* @retval NULL Exit failure.
*/
/* ********************************************************************** */
ESM_MESSAGE_CELL *
esm_md_AllocMessageCell(void)
{
auto& mc = module_ctx;
assert(mc.initialized);
for (size_t i { 0 }; i < NELEMS(mc.messages); i++) {
auto& cell = mc.messages[i];
if (cell.empty) {
cell.empty = false;
return &cell;
}
}
return nullptr;
}
/* ********************************************************************** */
/**
* @brief Deallocate memory space for ESM_MESSAGE_CELL type.
*
* @param[in,out] cell Memory space to deallocate.
*/
/* ********************************************************************** */
void
esm_md_DeallocMessageCell(ESM_MESSAGE_CELL * const cell)
{
assert(module_ctx.initialized);
cell->empty = true;
}
/* ********************************************************************** */
/**
* @brief Get system tick value.
*
* @return System tick in milliseconds.
*/
/* ********************************************************************** */
ESM_SYS_TICK_MSEC
esm_md_GetTick(void)
{
assert(module_ctx.initialized);
using std::chrono::steady_clock;
using std::chrono::milliseconds;
using std::chrono::duration_cast;
auto tp = steady_clock::now();
auto ms = duration_cast<milliseconds>(tp.time_since_epoch());
return static_cast<ESM_SYS_TICK_MSEC>(ms.count());
}
/* ********************************************************************** */
/**
* @brief A lock function for the library.
*/
/* ********************************************************************** */
void
esm_md_LockForAPI(void)
{
auto& mc = module_ctx;
assert(mc.initialized);
mc.mutex_for_api.lock();
}
/* ********************************************************************** */
/**
* @brief An unlock function for the library.
*/
/* ********************************************************************** */
void
esm_md_UnlockForAPI(void)
{
auto& mc = module_ctx;
assert(mc.initialized);
mc.mutex_for_api.unlock();
}
} // extern "C"
| 25.437262 | 77 | 0.398505 | eel3 |
8047e0f716757629bbe32536ae0550fd02866d8e | 565 | cpp | C++ | libs/multiprecision/test/test_eigen_interop_cpp_int.cpp | Talustus/boost_src | ffe074de008f6e8c46ae1f431399cf932164287f | [
"BSL-1.0"
] | 32 | 2019-02-27T06:57:07.000Z | 2021-08-29T10:56:19.000Z | third_party/boost/libs/multiprecision/test/test_eigen_interop_cpp_int.cpp | avplayer/cxxrpc | 7049b4079fac78b3828e68f787d04d699ce52f6d | [
"BSL-1.0"
] | 1 | 2019-04-04T18:00:00.000Z | 2019-04-04T18:00:00.000Z | third_party/boost/libs/multiprecision/test/test_eigen_interop_cpp_int.cpp | avplayer/cxxrpc | 7049b4079fac78b3828e68f787d04d699ce52f6d | [
"BSL-1.0"
] | 5 | 2019-08-20T13:45:04.000Z | 2022-03-01T18:23:49.000Z | ///////////////////////////////////////////////////////////////////////////////
// Copyright 2018 John Maddock. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/multiprecision/cpp_int.hpp>
#include "eigen.hpp"
int main()
{
using namespace boost::multiprecision;
test_integer_type<int>();
test_integer_type<boost::multiprecision::int256_t>();
test_integer_type<boost::multiprecision::cpp_int>();
return 0;
}
| 31.388889 | 80 | 0.614159 | Talustus |
804802105c5a3a6950798246728cfb30a8ee20a3 | 313 | cpp | C++ | sort.cpp | Amanda-Chang/APCS_practice | 83ee6b62d6d18039440ac79f4763bd0d23bb6842 | [
"MIT"
] | null | null | null | sort.cpp | Amanda-Chang/APCS_practice | 83ee6b62d6d18039440ac79f4763bd0d23bb6842 | [
"MIT"
] | null | null | null | sort.cpp | Amanda-Chang/APCS_practice | 83ee6b62d6d18039440ac79f4763bd0d23bb6842 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
using namespace std;
int main() {
int arr[] = {4, 5, 8, 3, 7, 1, 2, 6, 10, 9};
sort(arr, arr+10);
cout << "sort array by default (increasing):" << endl;
for (int i = 0; i < 10; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
| 20.866667 | 58 | 0.495208 | Amanda-Chang |
804bb4607b5c8af2948cea6b32e27cb54e6c304a | 930 | hpp | C++ | src/backends/neon/workloads/NeonStridedSliceWorkload.hpp | Srivathsav-max/armnn-clone | af2daa6526623c91ee97f7141be4d1b07de92a48 | [
"MIT"
] | 1 | 2022-03-31T18:21:59.000Z | 2022-03-31T18:21:59.000Z | src/backends/neon/workloads/NeonStridedSliceWorkload.hpp | Elm8116/armnn | e571cde8411803aec545b1070ed677e481f46f3f | [
"MIT"
] | null | null | null | src/backends/neon/workloads/NeonStridedSliceWorkload.hpp | Elm8116/armnn | e571cde8411803aec545b1070ed677e481f46f3f | [
"MIT"
] | null | null | null | //
// Copyright © 2017 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once
#include "NeonBaseWorkload.hpp"
#include <arm_compute/core/Error.h>
#include <arm_compute/runtime/IFunction.h>
#include <arm_compute/runtime/NEON/functions/NEStridedSlice.h>
#include <memory>
namespace armnn
{
arm_compute::Status NeonStridedSliceWorkloadValidate(const TensorInfo& input,
const TensorInfo& output,
const StridedSliceDescriptor& descriptor);
class NeonStridedSliceWorkload : public NeonBaseWorkload<StridedSliceQueueDescriptor>
{
public:
NeonStridedSliceWorkload(const StridedSliceQueueDescriptor& descriptor, const WorkloadInfo& info);
virtual void Execute() const override;
private:
mutable std::unique_ptr<arm_compute::NEStridedSlice> m_Layer;
};
} //namespace armnn | 27.352941 | 102 | 0.705376 | Srivathsav-max |
804d040fbd23bb770b61f495c0469ab333002f70 | 344 | cpp | C++ | src/operator_c/buffer/consdest.cpp | ichi-rika/glottal-inverse | c922ed540278e3c8eec528c2cf66b89e6d310575 | [
"MIT"
] | 6 | 2019-01-24T17:01:28.000Z | 2021-05-26T16:22:08.000Z | src/operator_c/buffer/consdest.cpp | ichi-rika/glottal-inverse | c922ed540278e3c8eec528c2cf66b89e6d310575 | [
"MIT"
] | null | null | null | src/operator_c/buffer/consdest.cpp | ichi-rika/glottal-inverse | c922ed540278e3c8eec528c2cf66b89e6d310575 | [
"MIT"
] | 2 | 2019-04-27T00:23:35.000Z | 2020-03-27T14:41:25.000Z | #include "operators.h"
#include "operators_buffer.h"
OperatorBuffer::OperatorBuffer()
{
// read into m_data
readCompressedFiles();
decompressFiles();
}
OperatorBuffer::~OperatorBuffer()
{
for (auto& entry : m_data) {
free(entry.second);
}
for (auto& mat : m_mats) {
gsl_matrix_free(mat);
}
}
| 13.76 | 33 | 0.616279 | ichi-rika |
805605c6dbe7ead087b9d195b59e96220b38a9c6 | 6,481 | cpp | C++ | thirdparty/ULib/tests/ulib/test_rdb_client.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | thirdparty/ULib/tests/ulib/test_rdb_client.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | thirdparty/ULib/tests/ulib/test_rdb_client.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | // test_rdb_client.cpp
#include <ulib/string.h>
#include <ulib/net/tcpsocket.h>
#include <ulib/net/client/client_rdb.h>
static void print(UStringRep* key, UStringRep* data)
{
U_TRACE(5, "::print(%.*S,%.*S)", U_STRING_TO_TRACE(*key), U_STRING_TO_TRACE(*data))
cout << UString(key) << "->" << UString(data) << endl;
}
static void transaction(URDBClient<UTCPSocket>& rdb)
{
U_TRACE(5, "::transaction(%p)", &rdb)
if (rdb.beginTransaction())
{
UString key0 = U_STRING_FROM_CONSTANT("chiave_di_prova0"),
data0 = U_STRING_FROM_CONSTANT("valore_di_prova0"),
key1 = U_STRING_FROM_CONSTANT("chiave_di_prova1"),
data1 = U_STRING_FROM_CONSTANT("valore_di_prova1"),
key2 = U_STRING_FROM_CONSTANT("chiave_di_prova2"),
data2 = U_STRING_FROM_CONSTANT("valore_di_prova2"),
key3 = U_STRING_FROM_CONSTANT("chiave_di_prova3"),
data3 = U_STRING_FROM_CONSTANT("valore_di_prova3");
rdb.store(key0, data0, RDB_INSERT);
rdb.store(key1, data1, RDB_REPLACE);
U_ASSERT( rdb.remove(key1) == 0 )
U_ASSERT( rdb[key1].empty() )
rdb.store(key2, data2, RDB_INSERT);
U_ASSERT( rdb[key2] == data2 )
rdb.substitute(key2, key3, data3);
rdb.commitTransaction();
U_ASSERT( rdb[key3] == data3 )
U_ASSERT( rdb.remove(key2) == -2 )
rdb.abortTransaction();
U_ASSERT( rdb[key0].empty() )
U_ASSERT( rdb[key1].empty() )
U_ASSERT( rdb[key2].empty() )
U_ASSERT( rdb[key3].empty() )
}
}
int
U_EXPORT main(int argc, char* argv[], char* env[])
{
U_ULIB_INIT(argv);
U_TRACE(5,"main(%d)",argc)
int result;
UString host(argv[1]);
URDBClient<UTCPSocket> x(0);
if (x.setHostPort(host, 8080) && x.connect())
{
UString key = U_STRING_FROM_CONSTANT("foo");
UString data = U_STRING_FROM_CONSTANT("bar");
UString value = x[key];
U_ASSERT( value.empty() )
result = x.remove(key);
U_ASSERT( result == -1 )
x.store(key, data, RDB_INSERT);
x.store(key, data, RDB_REPLACE);
value = x[key];
U_ASSERT( value == data )
result = x.remove(key);
U_ASSERT( result == 0 )
result = x.remove(key);
U_ASSERT( result == -2 )
x.store(key, data, RDB_INSERT);
UString new_key = U_STRING_FROM_CONSTANT("foo1");
UString new_data = U_STRING_FROM_CONSTANT("bar1");
x.substitute(key, new_key, new_data);
value = x[key];
U_ASSERT( value.empty() )
value = x[new_key];
U_ASSERT( value == new_data )
x.substitute(new_key, key, data);
value = x[new_key];
U_ASSERT( value.empty() )
value = x[key];
U_ASSERT( value == data )
// Network services, Internet style
// --------------------------------
// +6,4:@7/tcp.echo
// +8,1:echo/tcp.7
// +6,4:@7/udp.echo
// +8,1:echo/udp.7
// +6,7:@9/tcp.discard
// +11,1:discard/tcp.9
// +8,1:sink/tcp.9
// +8,1:null/tcp.9
// +6,7:@9/udp.discard
// +11,1:discard/udp.9
// +8,1:sink/udp.9
// +8,1:null/udp.9
// +7,6:@11/tcp.systat
// +10,2:systat/tcp.11
// +9,2:users/tcp.11
// +7,6:@11/udp.systat
// +10,2:systat/udp.11
// +9,2:users/udp.11
char buffer1[128];
char buffer2[128];
const char* tbl[9] = { "@7", "echo", "@9", "discard", "sink", "null", "@11", "systat", "users" };
const char* _data[9] = { "echo", "7", "discard", "9", "9", "9", "systat", "11", "11" };
for (int i = 0; i < 9; ++i)
{
strcat(strcpy(buffer1, tbl[i]), "/tcp");
strcat(strcpy(buffer2, tbl[i]), "/udp");
value = x[UString(buffer1)];
U_ASSERT( value == UString(_data[i]) )
value = x[UString(buffer2)];
U_ASSERT( value == UString(_data[i]) )
}
// handles repeated keys
// ---------------------
// +3,5:one.Hello
// +3,7:one.Goodbye
// +3,7:one.Another
// +3,5:two.Hello
// +3,7:two.Goodbye
// +3,7:two.Another
UString key1 = U_STRING_FROM_CONSTANT("one");
UString key2 = U_STRING_FROM_CONSTANT("two");
value = x[key1];
U_ASSERT( value == U_STRING_FROM_CONSTANT("Hello") )
value = x[key2];
U_ASSERT( value == U_STRING_FROM_CONSTANT("Hello") )
// handles long keys and data
// --------------------------
// +320,320:ba483b3442e75cace82def4b5df25bfca887b41687537.....
#define LKEY "ba483b3442e75cace82def4b5df25bfca887b41687537c21dc4b82cb4c36315e2f6a0661d1af2e05e686c4c595c16561d8c1b3fbee8a6b99c54b3d10d61948445298e97e971f85a600c88164d6b0b09\nb5169a54910232db0a56938de61256721667bddc1c0a2b14f5d063ab586a87a957e87f704acb7246c5e8c25becef713a365efef79bb1f406fecee88f3261f68e239c5903e3145961eb0fbc538ff506a\n"
#define LDATA "152e113d5deec3638ead782b93e1b9666d265feb5aebc840e79aa69e2cfc1a2ce4b3254b79fa73c338d22a75e67cfed4cd17b92c405e204a48f21c31cdcf7da46312dc80debfbdaf6dc39d74694a711\n6d170c5fde1a81806847cf71732c7f3217a38c6234235951af7b7c1d32e62d480d7c82a63a9d94291d92767ed97dd6a6809d1eb856ce23eda20268cb53fda31c016a19fc20e80aec3bd594a3eb82a5a\n"
U_ASSERT( x[U_STRING_FROM_CONSTANT(LKEY)] == U_STRING_FROM_CONSTANT(LDATA) )
x.closeReorganize();
if (x.connect())
{
/*
value = x[key1];
U_ASSERT( value == U_STRING_FROM_CONSTANT("Another"))
value = x[key2];
U_ASSERT( value == U_STRING_FROM_CONSTANT("Another"))
*/
U_ASSERT( x[U_STRING_FROM_CONSTANT(LKEY)] == U_STRING_FROM_CONSTANT(LDATA) )
UString _key = U_STRING_FROM_CONSTANT("chiave_di_prova");
UString data1 = U_STRING_FROM_CONSTANT("valore_di_prova");
x.store(_key, data1, RDB_INSERT);
x.store(_key, data1, RDB_REPLACE);
value = x[_key];
U_ASSERT( value == data1 )
result = x.remove(_key);
U_ASSERT( result == 0 )
result = x.remove(_key);
U_ASSERT( result == -2 )
transaction(x);
cout << "--------------------------" << endl;
x.callForAllEntry(print);
cout << "-------- sorted ----------" << endl;
x.callForAllEntrySorted(print);
cout << "--------------------------" << endl;
value.clear();
x.close();
}
}
}
| 28.425439 | 338 | 0.583243 | liftchampion |
8061a29b03a69b701653b84fbd1b35acac60512e | 211 | cpp | C++ | memecity.engine/Engine/SDL/Wrappers/Color.cpp | TvanBronswijk/memecity | f0410fb72d5484a642be90964defb87654ebd66b | [
"MIT"
] | null | null | null | memecity.engine/Engine/SDL/Wrappers/Color.cpp | TvanBronswijk/memecity | f0410fb72d5484a642be90964defb87654ebd66b | [
"MIT"
] | 4 | 2018-10-01T09:44:02.000Z | 2018-12-10T12:08:39.000Z | memecity.engine/Engine/SDL/Wrappers/Color.cpp | TvanBronswijk/memecity | f0410fb72d5484a642be90964defb87654ebd66b | [
"MIT"
] | null | null | null | #include "Color.h"
namespace memecity::engine::sdl {
Color::Color(Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
sdl_color = { r, g, b , a };
}
SDL_Color Color::get_sdl_color() const
{
return sdl_color;
}
}
| 15.071429 | 49 | 0.630332 | TvanBronswijk |
8062d6a6b1b5d78ba42ec5b289c021ae70a6cb23 | 178 | cpp | C++ | ch01/after_practice/002.cpp | mingxiali3/DataStructure | 1703755e6f74d754cc6ba59e055fd176bdde1c4b | [
"Apache-2.0"
] | null | null | null | ch01/after_practice/002.cpp | mingxiali3/DataStructure | 1703755e6f74d754cc6ba59e055fd176bdde1c4b | [
"Apache-2.0"
] | null | null | null | ch01/after_practice/002.cpp | mingxiali3/DataStructure | 1703755e6f74d754cc6ba59e055fd176bdde1c4b | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
int sum = 0;
for(int i = -5; i<= 100 ;i=i+7)
sum = sum +1;
cout << "sum : " << sum << endl;
return 0;
} | 17.8 | 36 | 0.5 | mingxiali3 |
8066232c745b9fd715b734089c36a13834dac452 | 811 | cpp | C++ | P/3366.cpp | langonginc/cfile | 46458897b8a4a8d58a2bc63ecb6ef84f76bdb61f | [
"MIT"
] | 1 | 2020-09-13T02:51:25.000Z | 2020-09-13T02:51:25.000Z | P/3366.cpp | langonginc/cfile | 46458897b8a4a8d58a2bc63ecb6ef84f76bdb61f | [
"MIT"
] | null | null | null | P/3366.cpp | langonginc/cfile | 46458897b8a4a8d58a2bc63ecb6ef84f76bdb61f | [
"MIT"
] | 1 | 2021-06-05T03:37:57.000Z | 2021-06-05T03:37:57.000Z | #include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<set>
#include<climits>
#include<algorithm>
using namespace std;
const int INF=INT_MAX;
const int inf=300000;
struct node{
int u,v,w;
bool operator<(const node &a)const{
return w<a.w;
}
}ph[inf];
int n,m,f[inf],ans=0,c=0;
int find(int x){
if(f[x]==x){
return x;
}
f[x]=find(f[x]);
return f[x];
}
bool kal(){
for(int i=0;i<m;i++){
node p=ph[i];
if(find(p.u)!=find(p.v)){
f[find(p.u)]=find(p.v);
ans+=p.w;
c++;
if(c==n-1)return true;
}
}
return false;
}
int main(){
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++){
scanf("%d%d%d",&ph[i].u,&ph[i].v,&ph[i].w);
}
for(int i=1;i<=n;i++){
f[i]=i;
}
sort(ph,ph+m);
if(kal()==true){
cout<<ans;
}
else{
cout<<"orz";
}
return 0;
}
| 14.745455 | 45 | 0.567201 | langonginc |
806a83488ea67e8368adec392bab43be72ade63e | 107,237 | cpp | C++ | test/adiar/internal/test_levelized_priority_queue.cpp | logsem/adiar | 056c62a37eedcc5a9e46ccc8c235b5aacedebe32 | [
"MIT"
] | null | null | null | test/adiar/internal/test_levelized_priority_queue.cpp | logsem/adiar | 056c62a37eedcc5a9e46ccc8c235b5aacedebe32 | [
"MIT"
] | null | null | null | test/adiar/internal/test_levelized_priority_queue.cpp | logsem/adiar | 056c62a37eedcc5a9e46ccc8c235b5aacedebe32 | [
"MIT"
] | null | null | null | #include <adiar/internal/levelized_priority_queue.h>
using namespace adiar;
struct pq_test_data {
label_t label;
uint64_t nonce;
};
namespace adiar
{
template <>
struct FILE_CONSTANTS<pq_test_data>
{
static constexpr size_t files = 1u;
};
}
bool operator== (const pq_test_data &a, const pq_test_data &b)
{
return a.label == b.label && a.nonce == b.nonce;
}
struct pq_test_label_ext {
static label_t label_of(const pq_test_data &d)
{
return d.label;
}
};
struct pq_test_lt {
bool operator()(const pq_test_data &a, const pq_test_data &b)
{
return a.label < b.label || (a.label == b.label && a.nonce < b.nonce);
}
};
struct pq_test_gt {
bool operator()(const pq_test_data &a, const pq_test_data &b)
{
return a.label > b.label || (a.label == b.label && a.nonce > b.nonce);
}
};
typedef meta_file<pq_test_data> pq_test_file;
typedef meta_file_writer<pq_test_data> pq_test_writer;
template <typename file_t, size_t LOOK_AHEAD>
using test_priority_queue = levelized_priority_queue<pq_test_data, pq_test_label_ext, pq_test_lt,
file_t, 1u, std::less<label_t>,
1u,
LOOK_AHEAD>;
go_bandit([]() {
describe("adiar/internal/levelized_priority_queue.h", []() {
describe("label_merger", [&]() {
it("can pull from one level_info stream", [&]() {
pq_test_file f;
{ // Garbage collect the writer
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(4,1u));
fw.unsafe_push(create_level_info(3,2u));
fw.unsafe_push(create_level_info(2,2u));
fw.unsafe_push(create_level_info(1,1u));
}
label_merger<pq_test_file, std::less<>, 1u> merger;
merger.hook({f});
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(1u));
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(2u));
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(3u));
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(4u));
AssertThat(merger.can_pull(), Is().False());
});
it("can peek from one level_info streams", [&]() {
pq_test_file f;
{ // Garbage collect the writer
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(4,1u));
fw.unsafe_push(create_level_info(3,2u));
fw.unsafe_push(create_level_info(2,1u));
fw.unsafe_push(create_level_info(1,1u));
}
label_merger<pq_test_file, std::less<>, 1> merger;
merger.hook({f});
AssertThat(merger.pull(), Is().EqualTo(1u));
AssertThat(merger.peek(), Is().EqualTo(2u));
AssertThat(merger.pull(), Is().EqualTo(2u));
AssertThat(merger.peek(), Is().EqualTo(3u));
AssertThat(merger.pull(), Is().EqualTo(3u));
AssertThat(merger.pull(), Is().EqualTo(4u));
});
it("can pull from merge of two level_info streams, where one is empty [1]", [&]() {
pq_test_file f1;
pq_test_file f2;
{ // Garbage collect the writer
pq_test_writer fw1(f1);
fw1.unsafe_push(create_level_info(1,1u));
}
label_merger<pq_test_file, std::less<>, 2> merger;
merger.hook({f1, f2});
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(1u));
AssertThat(merger.can_pull(), Is().False());
});
it("can pull from merge of two level_info streams, where one is empty [2]", [&]() {
pq_test_file f1;
pq_test_file f2;
{ // Garbage collect the writer
pq_test_writer fw1(f1);
fw1.unsafe_push(create_level_info(1,1u));
fw1.unsafe_push(create_level_info(2,1u));
}
label_merger<pq_test_file, std::greater<>, 2> merger;
merger.hook({f1, f2});
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(2u));
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(1u));
AssertThat(merger.can_pull(), Is().False());
});
it("can pull from merge of two level_info streams [1]", [&]() {
pq_test_file f1;
pq_test_file f2;
{ // Garbage collect the writers
pq_test_writer fw1(f1);
fw1.unsafe_push(create_level_info(4,1u));
fw1.unsafe_push(create_level_info(2,2u));
fw1.unsafe_push(create_level_info(1,1u));
pq_test_writer fw2(f2);
fw2.unsafe_push(create_level_info(4,1u));
fw2.unsafe_push(create_level_info(3,1u));
}
label_merger<pq_test_file, std::less<>, 2> merger;
merger.hook({f1, f2});
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(1u));
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(2u));
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(3u));
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(4u));
AssertThat(merger.can_pull(), Is().False());
});
it("can pull from merge of two level_info streams [2] (std::less)", [&]() {
pq_test_file f1;
pq_test_file f2;
{ // Garbage collect the writers
pq_test_writer fw1(f1);
fw1.unsafe_push(create_level_info(2,1u));
pq_test_writer fw2(f2);
fw2.unsafe_push(create_level_info(1,1u));
}
label_merger<pq_test_file, std::less<>, 2> merger;
merger.hook({f1, f2});
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(1u));
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(2u));
AssertThat(merger.can_pull(), Is().False());
});
it("can pull from merge of two level_info streams [2] (std::greater)", [&]() {
pq_test_file f1;
pq_test_file f2;
{ // Garbage collect the writers
pq_test_writer fw1(f1);
fw1.unsafe_push(create_level_info(2,1u));
pq_test_writer fw2(f2);
fw2.unsafe_push(create_level_info(1,1u));
}
label_merger<pq_test_file, std::greater<>, 2> merger;
merger.hook({f1, f2});
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(2u));
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(1u));
AssertThat(merger.can_pull(), Is().False());
});
it("can peek merge of two level_info stream", [&]() {
pq_test_file f1;
pq_test_file f2;
{ // Garbage collect the writers
pq_test_writer fw1(f1);
fw1.unsafe_push(create_level_info(4,2u));
fw1.unsafe_push(create_level_info(2,1u));
pq_test_writer fw2(f2);
fw2.unsafe_push(create_level_info(4,3u));
fw2.unsafe_push(create_level_info(3,2u));
fw2.unsafe_push(create_level_info(1,1u));
}
label_merger<pq_test_file, std::less<>, 2> merger;
merger.hook({f1, f2});
AssertThat(merger.peek(), Is().EqualTo(1u));
AssertThat(merger.pull(), Is().EqualTo(1u));
AssertThat(merger.peek(), Is().EqualTo(2u));
AssertThat(merger.pull(), Is().EqualTo(2u));
AssertThat(merger.peek(), Is().EqualTo(3u));
AssertThat(merger.pull(), Is().EqualTo(3u));
AssertThat(merger.peek(), Is().EqualTo(4u));
AssertThat(merger.pull(), Is().EqualTo(4u));
});
it("can pull, even after the original files have been deleted", [&]() {
pq_test_file* f1 = new pq_test_file();
pq_test_file* f2 = new pq_test_file();
{ // Garbage collect the writers
pq_test_writer fw1(*f1);
fw1.unsafe_push(create_level_info(4,2u));
fw1.unsafe_push(create_level_info(2,1u));
pq_test_writer fw2(*f2);
fw2.unsafe_push(create_level_info(4,1u));
fw2.unsafe_push(create_level_info(3,2u));
fw2.unsafe_push(create_level_info(1,1u));
}
label_merger<pq_test_file, std::less<>, 2> merger;
merger.hook({*f1, *f2});
delete f1;
delete f2;
AssertThat(merger.pull(), Is().EqualTo(1u));
AssertThat(merger.pull(), Is().EqualTo(2u));
AssertThat(merger.pull(), Is().EqualTo(3u));
AssertThat(merger.pull(), Is().EqualTo(4u));
});
it("can use a single label_file", [&]() {
label_file f;
{ // Garbage collect the writers
label_writer w(f);
w << 0 << 2 << 3;
}
label_merger<label_file, std::less<>, 1> merger;
merger.hook({f});
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(0u));
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(2u));
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(3u));
AssertThat(merger.can_pull(), Is().False());
});
it("can merge two label_files", [&]() {
label_file f1;
label_file f2;
{ // Garbage collect the writers
label_writer w1(f1);
w1 << 0 << 2 << 3;
label_writer w2(f2);
w2 << 0 << 1 << 3;
}
label_merger<label_file, std::less<>, 2> merger;
merger.hook({f1, f2});
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(0u));
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(1u));
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(2u));
AssertThat(merger.can_pull(), Is().True());
AssertThat(merger.pull(), Is().EqualTo(3u));
AssertThat(merger.can_pull(), Is().False());
});
});
////////////////////////////////////////////////////////////////////////////
// TODO: All the 'set up' tests should be removed. Instead, move this
// initialisation cases into some simple pushing and pulling tests.
//
// TODO: Most level files should be replaced with a simpler label_file (and
// use the << operator). Yet, we of course need one test or two with a
// meta file.
//
// TODO: Are we not missing some unit tests for the very simple accessors?
describe("levelized_priority_queue<..., INIT_LEVEL=1, LOOK_AHEAD=1>", [&]() {
//////////////////////////////////////////////////////////////////////////
// initialisation //
it("initialises #levels = 0", [&]() {
pq_test_file f;
test_priority_queue<pq_test_file, 1> pq({f});
AssertThat(pq.can_pull(), Is().False());
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().False());
});
it("initialises with #levels = 1 (which is skipped)", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 2;
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.can_pull(), Is().False());
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().False());
});
it("initialises with #levels = 2 (#buckets = 1)", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 << 2;
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.can_pull(), Is().False());
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
});
it("initialises with #buckets == #levels", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 3 << 4; // buckets
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.can_pull(), Is().False());
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(3u));
});
it("initialises with #buckets < #levels", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 4 // buckets
<< 5; // overflow
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.can_pull(), Is().False());
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
});
//////////////////////////////////////////////////////////////////////////
// level state //
// TODO: allow us to forward with no elements within? If so, then we might
// want to consider simplifying these unit tests.
describe(".setup_next_level()", [&]() {
it("can forward until the first non-empty bucket [1]", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 0 // skipped
<< 2 << 3 // buckets
<< 4; // overflow
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
pq.push(pq_test_data {2, 1});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
pq.setup_next_level();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(2u));
AssertThat(pq.empty_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(3u));
});
it("can forward until the first non-empty bucket [2]", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 3 // buckets
<< 4; // overflow
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
pq.push(pq_test_data {3, 1});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
pq.setup_next_level();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(3u));
AssertThat(pq.empty_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(4u));
});
it("can forward up until the overflow queue", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 3 // buckets
<< 4; // overflow
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
pq.push(pq_test_data {4, 1});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
pq.setup_next_level();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(4u));
AssertThat(pq.empty_level(), Is().False());
AssertThat(pq.has_next_level(), Is().False());
});
it("can forward until next bucket", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 3 // buckets
<< 4; // overflow
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
pq.push(pq_test_data {2, 1});
pq.push(pq_test_data {3, 1});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
pq.setup_next_level();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(2u));
AssertThat(pq.empty_level(), Is().False());
pq.pop();
AssertThat(pq.empty_level(), Is().True());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(3u));
pq.setup_next_level();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(3u));
AssertThat(pq.empty_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(4u));
});
it("can forward past buckets until top of overflow queue", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 3 // buckets
<< 4 << 5; // overflow
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
pq.push(pq_test_data {2, 1});
pq.push(pq_test_data {4, 1});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
pq.setup_next_level();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(2u));
AssertThat(pq.empty_level(), Is().False());
pq.pop();
AssertThat(pq.empty_level(), Is().True());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(3u));
pq.setup_next_level();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(4u));
AssertThat(pq.empty_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(5u));
});
it("can relabel buckets until top of overflow queue [1]", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 3 // buckets
<< 4 << 5 // overflow that turn into buckets
<< 6 << 7 << 8 << 9; // overflow that will relabel
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
pq.push(pq_test_data {8, 1});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
pq.setup_next_level();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(8u));
AssertThat(pq.empty_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(9u));
});
it("can relabel buckets until top of overflow queue [2]", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 3 << 4 // buckets (after element in 2)
<< 5 << 6 // overflow that turn into buckets
<< 7 // overflow that is skipped
<< 8 << 9 << 10; // overflow that will relabel
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
pq.push(pq_test_data {8, 1});
pq.push(pq_test_data {2, 2});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
pq.setup_next_level();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(2u));
AssertThat(pq.empty_level(), Is().False());
pq.pop();
AssertThat(pq.empty_level(), Is().True());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(3u));
pq.setup_next_level();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(8u));
AssertThat(pq.empty_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(9u));
});
it("can relabel fewer levels than buckets", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 3 << 4 // buckets (after element in 2)
<< 5 << 6 // overflow that turn into buckets
<< 7 // overflow that is skipped
<< 8; // overflow that will relabel
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
pq.push(pq_test_data {8, 1});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
pq.setup_next_level();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(8u));
AssertThat(pq.has_next_level(), Is().False());
});
});
describe(".setup_next_level(stop_label)", [&]() {
it("forward to known level of first bucket", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 3 // buckets
<< 4; // overflow
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
pq.push(pq_test_data {3, 1});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
pq.setup_next_level(2u);
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(2u));
AssertThat(pq.empty_level(), Is().True());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(3u));
});
it("forwards to known level of second bucket", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 3 // buckets
<< 4; // overflow
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
pq.push(pq_test_data {4, 1});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
pq.setup_next_level(3u);
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(3u));
AssertThat(pq.empty_level(), Is().True());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(4u));
});
it("forwards to known level of next bucket with content", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 3 // buckets
<< 4; // overflow
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
pq.push(pq_test_data {3, 1});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
pq.setup_next_level(2u);
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(2u));
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(3u));
pq.setup_next_level(3u);
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(3u));
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(4u));
});
it("forwards to known level of next bucket without content", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 3 // buckets
<< 4; // overflow
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
pq.setup_next_level(2u);
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(2u));
pq.push(pq_test_data {4, 1});
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(3u));
pq.setup_next_level(3u);
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(3u));
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(4u));
});
it("stops early at bucket with content", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 3 // buckets
<< 4; // overflow
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
pq.push(pq_test_data {4, 1});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
pq.setup_next_level(2u);
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(2u));
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(3u));
pq.setup_next_level(3u);
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(3u));
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(4u));
});
it("stops at known level of prior to content of overflow queue", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 3 // buckets
<< 4; // overflow
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
pq.push(pq_test_data {4, 1});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
pq.setup_next_level(3u);
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(3u));
AssertThat(pq.empty_level(), Is().True());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(4u));
});
it("stops early at content of overflow queue", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 3 // buckets
<< 4 << 5 << 6; // overflow
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {4, 1});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
pq.setup_next_level(6u);
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(4u));
AssertThat(pq.empty_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(5u));
});
it("does nothing when given unknown level prior to first bucket", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 3 << 4 // buckets
<< 5; // overflow
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
pq.push(pq_test_data {3, 1});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(3u));
pq.setup_next_level(2u);
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(3u));
});
it("forward to first bucket for unknown level prior to second bucket", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 4 // buckets
<< 5; // overflow
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
pq.push(pq_test_data {4, 1});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
pq.setup_next_level(3u);
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(2u));
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(4u));
});
it("does nothing for unknown level prior to next bucket", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 // read bucket
<< 4 // next buckets
<< 5; // overflow
}
test_priority_queue<label_file, 1> pq({f});
pq.push(pq_test_data {2, 1});
pq.setup_next_level();
pq.pop();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(2u));
pq.push(pq_test_data {4, 2});
pq.setup_next_level(3u);
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(2u));
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(4u));
});
it("forward to next bucket for unknown level after it", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 3 // buckets
<< 5; // overflow
}
test_priority_queue<label_file, 1> pq({f});
pq.push(pq_test_data {2, 1});
pq.setup_next_level();
pq.pop();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(2u));
pq.push(pq_test_data {5, 2});
pq.setup_next_level(4u);
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(3u));
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(5u));
});
it("can relabel for unknown level", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 3 << 4 // buckets (after element in 2)
<< 5 << 6 // overflow that turn into buckets
<< 7 // overflow that is skipped
<< 8 << 10 << 11; // overflow that will relabel
}
test_priority_queue<label_file, 1> pq({f});
pq.push(pq_test_data {2, 1});
pq.setup_next_level();
pq.pop();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(2u));
pq.push(pq_test_data {10, 2});
pq.setup_next_level(9u);
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(8u));
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(10u));
});
});
//////////////////////////////////////////////////////////////////////////
// .push / pull //
describe(".push(elem_t &) + pull()", [&]{
it("can push when there are fewer levels than buckets", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 1> pq({f});
pq.push(pq_test_data {2, 1});
pq.push(pq_test_data {2, 2});
pq.setup_next_level(); // 2
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {2, 1}));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {2, 2}));
AssertThat(pq.can_pull(), Is().False());
});
it("can push to buckets", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(4,2u)); // overflow
fw.unsafe_push(create_level_info(3,3u)); // bucket
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 1> pq({f});
pq.push(pq_test_data {2, 1});
pq.push(pq_test_data {2, 2});
pq.setup_next_level(); // 2
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {2, 1}));
pq.push(pq_test_data {3, 2});
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {2, 2}));
pq.push(pq_test_data {3, 1});
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 3
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 1}));
pq.push(pq_test_data {4, 1});
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 2}));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 4
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 1}));
AssertThat(pq.can_pull(), Is().False());
});
it("can push to overflow queue [1]", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(4,1u)); // overflow
fw.unsafe_push(create_level_info(3,3u)); // bucket
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 1> pq({f});
pq.push(pq_test_data {4, 1});
pq.setup_next_level(); // 4
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 1}));
AssertThat(pq.can_pull(), Is().False());
});
it("can push to overflow queue [2]", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(4,2u)); // overflow
fw.unsafe_push(create_level_info(3,3u)); // bucket
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // bucket
}
test_priority_queue<pq_test_file, 1> pq({f});
pq.push(pq_test_data {3, 1});
pq.push(pq_test_data {4, 1});
pq.setup_next_level(); // 3
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 1}));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 4
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 1}));
AssertThat(pq.can_pull(), Is().False());
});
it("can push to overflow queue [3]", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(5,1u)); // .
fw.unsafe_push(create_level_info(4,2u)); // overflow
fw.unsafe_push(create_level_info(3,3u)); // bucket
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // bucket
}
test_priority_queue<pq_test_file, 1> pq({f});
pq.push(pq_test_data {5, 2});
pq.push(pq_test_data {5, 1});
pq.push(pq_test_data {3, 3});
pq.setup_next_level(); // 3
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 3}));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 5
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {5, 1}));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {5, 2}));
AssertThat(pq.can_pull(), Is().False());
});
it("can merge content of bucket with overflow queue", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(5,2u)); // .
fw.unsafe_push(create_level_info(4,2u)); // overflow
fw.unsafe_push(create_level_info(3,3u)); // bucket
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 1> pq({f});
pq.push(pq_test_data {5, 2}); // overflow
pq.push(pq_test_data {4, 1}); // overflow
pq.setup_next_level(); // read: 4, write: 5
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 1}));
pq.push(pq_test_data {5, 1}); // bucket
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // read: 5
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {5, 1}));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {5, 2}));
AssertThat(pq.can_pull(), Is().False());
});
/////////////////////////////////////////////////////////////
// TODO //
it("can set up next level with a stop_label [1]", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(4,2u));
fw.unsafe_push(create_level_info(3,4u));
fw.unsafe_push(create_level_info(2,2u));
fw.unsafe_push(create_level_info(1,1));
}
test_priority_queue<pq_test_file, 1> pq({f});
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {4, 1});
pq.setup_next_level(3u); // 3
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 4
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 1}));
AssertThat(pq.can_pull(), Is().False());
});
it("can set up next level with a stop_label [2]", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(5,2u));
fw.unsafe_push(create_level_info(4,4u));
fw.unsafe_push(create_level_info(3,4u));
fw.unsafe_push(create_level_info(2,2u));
fw.unsafe_push(create_level_info(1,1u));
}
test_priority_queue<pq_test_file, 1> pq({f});
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {5, 1});
pq.setup_next_level(4u); // 3
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 5
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {5, 1}));
AssertThat(pq.can_pull(), Is().False());
});
it("can use buckets after relabelling", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(16,2u)); // .
fw.unsafe_push(create_level_info(15,3u)); // .
fw.unsafe_push(create_level_info(14,5u)); // .
fw.unsafe_push(create_level_info(12,8u)); // .
fw.unsafe_push(create_level_info(10,8u)); // .
fw.unsafe_push(create_level_info(9,7u)); // .
fw.unsafe_push(create_level_info(8,3u)); // . (bucket)
fw.unsafe_push(create_level_info(6,3u)); // overflow (bucket)
fw.unsafe_push(create_level_info(5,3u)); // bucket
fw.unsafe_push(create_level_info(4,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 1> pq({f});
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {10, 2}); // overflow
pq.push(pq_test_data {12, 3}); // overflow
pq.setup_next_level(); // 10
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {10,2}));
pq.push(pq_test_data {12, 1}); // bucket
pq.push(pq_test_data {14, 1}); // overflow
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 12
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {12,1}));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {12,3}));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 14
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {14,1}));
AssertThat(pq.can_pull(), Is().False());
});
it("can set up next level with a stop_label prior to the level of next bucket)", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer w(f);
w << 0 // Skipped
<< 2 // Bucket
<< 3 // Bucket
<< 4 // Overflow
;
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {2, 1});
pq.setup_next_level(1u); // not changed
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {2, 2});
pq.setup_next_level(); // 2
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {2, 1}));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {2, 2}));
AssertThat(pq.can_pull(), Is().False());
});
it("can set up next level with a stop_label for prior to second next bucket", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer w(f);
w << 0 // Skipped
<< 1 // Bucket
<< 3 // Bucket
<< 4 // Overflow
;
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {3, 1});
pq.setup_next_level(2u); // 1
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {3, 2});
pq.setup_next_level(); // 3
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 1}));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 2}));
AssertThat(pq.can_pull(), Is().False());
});
it("can set up next level with a stop_label prior to the level of the overflow queue", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer w(f);
w << 0 // Skipped
<< 1 // Bucket
<< 2 // Bucket
<< 4 // Overflow
<< 5 // .
;
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {4, 1});
pq.setup_next_level(3u); // 2
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {4, 2});
pq.setup_next_level(); // 4
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 1}));
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 2}));
AssertThat(pq.can_pull(), Is().False());
});
it("can relabel buckets with a stop_label for an unknown level", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer w(f);
w << 0 // Skipped
<< 1 // Bucket
<< 2 // Bucket
<< 3 // Overflow
<< 5 // .
<< 6 // .
;
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {5, 1});
pq.setup_next_level(4u); // 3
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {5, 2});
pq.setup_next_level(); // 5
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {5, 1}));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {5, 2}));
AssertThat(pq.can_pull(), Is().False());
});
});
describe(".pop()", [&]{
// TODO
});
//////////////////////////////////////////////////////////////////////////
// .can_pull() //
describe(".empty_level() / .can_pull()", [&]{
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 // skipped
<< 2 << 3 // buckets
<< 4 << 5 << 6; // overflow
}
it("cannot pull after initialisation", [&]() {
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.can_pull(), Is().False());
});
it("shows element after forwarding to level", [&]() {
test_priority_queue<label_file, 1> pq({f});
pq.push(pq_test_data { 2,1 });
pq.setup_next_level(); // 2
AssertThat(pq.can_pull(), Is().True());
});
it("shows a level becomes empty", [&]() {
test_priority_queue<label_file, 1> pq({f});
pq.push(pq_test_data { 2,1 });
pq.setup_next_level(); // 2
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.empty_level(), Is().False());
AssertThat(pq.can_pull(), Is().True());
pq.pop();
AssertThat(pq.empty_level(), Is().True());
AssertThat(pq.can_pull(), Is().False());
});
it("shows forwarding to an empty level", [&]() {
test_priority_queue<label_file, 1> pq({f});
pq.push(pq_test_data { 3,1 });
pq.setup_next_level(2); // 2
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.empty_level(), Is().True());
AssertThat(pq.can_pull(), Is().False());
});
});
describe(".top() / .peek()", [&]{
it("can look into bucket without side-effects", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(6,2u)); // .
fw.unsafe_push(create_level_info(5,4u)); // .
fw.unsafe_push(create_level_info(4,5u)); // overflow
fw.unsafe_push(create_level_info(3,4u)); // bucket
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 1> pq({f});
AssertThat(pq.size(), Is().EqualTo(0u));
pq.push(pq_test_data {2, 42}); // bucket
AssertThat(pq.size(), Is().EqualTo(1u));
pq.setup_next_level();
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.peek(), Is().EqualTo(pq_test_data {2, 42}));
AssertThat(pq.size(), Is().EqualTo(1u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {2, 42}));
AssertThat(pq.size(), Is().EqualTo(0u));
AssertThat(pq.can_pull(), Is().False());
});
it("can look into overflow priority queue without side-effects", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(6,2u)); // .
fw.unsafe_push(create_level_info(5,2u)); // .
fw.unsafe_push(create_level_info(4,3u)); // overflow
fw.unsafe_push(create_level_info(3,2u)); // bucket
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 1> pq({f});
pq.push(pq_test_data {5, 3}); // overflow
AssertThat(pq.size(), Is().EqualTo(1u));
pq.setup_next_level();
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.peek(), Is().EqualTo(pq_test_data {5, 3}));
AssertThat(pq.size(), Is().EqualTo(1u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {5, 3}));
AssertThat(pq.size(), Is().EqualTo(0u));
AssertThat(pq.can_pull(), Is().False());
});
// TODO: peek -> push -> peek
});
describe(".size()", [&]{
it("increments on push to bucket [1]", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 0 // skipped
<< 1 << 2; // buckets
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.size(), Is().EqualTo(0u));
pq.push(pq_test_data {1, 1});
AssertThat(pq.size(), Is().EqualTo(1u));
pq.push(pq_test_data {2, 1});
AssertThat(pq.size(), Is().EqualTo(2u));
});
it("increments on push to bucket [2]", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 0 // skipped
<< 1 << 2; // buckets
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.size(), Is().EqualTo(0u));
pq.push(pq_test_data {1, 1});
AssertThat(pq.size(), Is().EqualTo(1u));
pq.setup_next_level();
pq.push(pq_test_data {2, 1});
AssertThat(pq.size(), Is().EqualTo(2u));
});
it("increments on push to overflow queue", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 0 // skipped
<< 1 << 2 // buckets
<< 3 << 4; // overflow
}
test_priority_queue<label_file, 1> pq({f});
AssertThat(pq.size(), Is().EqualTo(0u));
pq.push(pq_test_data {4, 1});
AssertThat(pq.size(), Is().EqualTo(1u));
pq.push(pq_test_data {5, 1});
AssertThat(pq.size(), Is().EqualTo(2u));
});
it("decrements on pull from bucket", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 0 // skipped
<< 1 << 2; // buckets
}
test_priority_queue<label_file, 1> pq({f});
pq.push(pq_test_data {1, 1});
pq.push(pq_test_data {1, 2});
pq.setup_next_level();
AssertThat(pq.size(), Is().EqualTo(2u));
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {1, 1}));
AssertThat(pq.size(), Is().EqualTo(1u));
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {1, 2}));
AssertThat(pq.size(), Is().EqualTo(0u));
});
it("decrements on pull from overflow queue", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 0 // skipped
<< 1 << 2 // buckets
<< 3 << 4; // overflow
}
test_priority_queue<label_file, 1> pq({f});
pq.push(pq_test_data {4, 1});
pq.push(pq_test_data {4, 2});
pq.setup_next_level();
AssertThat(pq.size(), Is().EqualTo(2u));
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 1}));
AssertThat(pq.size(), Is().EqualTo(1u));
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 2}));
AssertThat(pq.size(), Is().EqualTo(0u));
});
it("decrements on pull from bucket", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 0 // skipped
<< 1 << 2; // buckets
}
test_priority_queue<label_file, 1> pq({f});
pq.push(pq_test_data {1, 1});
pq.push(pq_test_data {1, 2});
pq.setup_next_level();
AssertThat(pq.size(), Is().EqualTo(2u));
pq.pop();
AssertThat(pq.size(), Is().EqualTo(1u));
pq.pop();
AssertThat(pq.size(), Is().EqualTo(0u));
});
it("decrements on pull from overflow queue", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 0 // skipped
<< 1 << 2 // buckets
<< 3 << 4; // overflow
}
test_priority_queue<label_file, 1> pq({f});
pq.push(pq_test_data {4, 1});
pq.push(pq_test_data {4, 2});
pq.setup_next_level();
AssertThat(pq.size(), Is().EqualTo(2u));
pq.pop();
AssertThat(pq.size(), Is().EqualTo(1u));
pq.pop();
AssertThat(pq.size(), Is().EqualTo(0u));
});
it("is unchanged on top from bucket", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 0 // skipped
<< 1 << 2; // buckets
}
test_priority_queue<label_file, 1> pq({f});
pq.push(pq_test_data {1, 1});
pq.push(pq_test_data {1, 2});
pq.setup_next_level();
AssertThat(pq.size(), Is().EqualTo(2u));
AssertThat(pq.top(), Is().EqualTo(pq_test_data {1, 1}));
AssertThat(pq.size(), Is().EqualTo(2u));
});
it("is unchanged on top from overflow queue", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 0 // skipped
<< 1 << 2 // buckets
<< 3 << 4; // overflow
}
test_priority_queue<label_file, 1> pq({f});
pq.push(pq_test_data {4, 1});
pq.push(pq_test_data {4, 2});
pq.setup_next_level();
AssertThat(pq.size(), Is().EqualTo(2u));
AssertThat(pq.top(), Is().EqualTo(pq_test_data {4, 1}));
AssertThat(pq.size(), Is().EqualTo(2u));
});
});
});
describe("levelized_priority_queue<..., pq_test_gt, ..., std::greater<label_g>, ...>", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 3 // skipped
<< 2 << 1 // buckets
<< 0 // overflow
;
}
it("can sort elements from buckets", [&]() {
levelized_priority_queue<pq_test_data, pq_test_label_ext, pq_test_gt,
label_file, 1u, std::greater<label_t>,
1u,
1u>
pq({f});
pq.push(pq_test_data {2, 1});
pq.push(pq_test_data {1, 1});
pq.push(pq_test_data {2, 2});
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 2
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {2,2}));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {2,1}));
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {1, 2});
pq.setup_next_level(); // 1
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {1,2}));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {1,1}));
AssertThat(pq.can_pull(), Is().False());
});
it("can sort elements in overflow priority queue", [&]() {
levelized_priority_queue<pq_test_data, pq_test_label_ext, pq_test_gt,
label_file, 1u, std::greater<label_t>,
1u,
1u>
pq({f});
pq.push(pq_test_data {0, 1});
pq.push(pq_test_data {0, 2});
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 0
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {0,2}));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {0,1}));
AssertThat(pq.can_pull(), Is().False());
});
it("can merge elements from buckets and overflow", [&]() {
levelized_priority_queue<pq_test_data, pq_test_label_ext, pq_test_gt,
label_file, 1u, std::greater<label_t>,
1u,
1u>
pq({f});
AssertThat(pq.has_current_level(), Is().False());
pq.push(pq_test_data {2, 1}); // bucket
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 2
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {2,1}));
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {1,1}); // bucket
pq.push(pq_test_data {0,2}); // overflow
pq.setup_next_level(); // 1
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {1,1}));
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {0,1}); // bucket
pq.setup_next_level(); // 0
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {0,2}));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {0,1}));
AssertThat(pq.can_pull(), Is().False());
});
});
describe("levelized_priority_queue<..., INIT_LEVEL=0, LOOK_AHEAD=1>", [&]() {
it("initialises #levels = 0", [&]() {
label_file f;
levelized_priority_queue<pq_test_data, pq_test_label_ext, pq_test_lt,
label_file, 1u, std::less<label_t>,
0u,
1u>
pq({f});
AssertThat(pq.can_pull(), Is().False());
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.can_push(), Is().False());
AssertThat(pq.has_next_level(), Is().False());
});
it("initialises with #levels = 1 < #buckets", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 2;
}
levelized_priority_queue<pq_test_data, pq_test_label_ext, pq_test_lt,
label_file, 1u, std::less<label_t>,
0u,
1u>
pq({f});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.can_push(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
});
it("initialises #buckets <= #levels", [&]() {
label_file f;
{ // Garbage collect the writer early
label_writer fw(f);
fw << 1 << 3 << 4;
}
levelized_priority_queue<pq_test_data, pq_test_label_ext, pq_test_lt,
label_file, 1u, std::less<label_t>,
0u,
1u>
pq({f});
AssertThat(pq.can_pull(), Is().False());
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.can_push(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(1u));
});
it("can push into and pull from root level bucket [1]", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(1,1u)); // bucket
}
levelized_priority_queue<pq_test_data, pq_test_label_ext, pq_test_lt,
pq_test_file, 1u, std::less<label_t>,
0u,
1u>
pq({f});
AssertThat(pq.size(), Is().EqualTo(0u));
pq.push(pq_test_data {1, 1});
AssertThat(pq.size(), Is().EqualTo(1u));
pq.push(pq_test_data {1, 2});
AssertThat(pq.size(), Is().EqualTo(2u));
pq.setup_next_level(); // 1
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {1, 1}));
AssertThat(pq.size(), Is().EqualTo(1u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {1, 2}));
AssertThat(pq.size(), Is().EqualTo(0u));
AssertThat(pq.has_next_level(), Is().False());
});
it("can push into and pull from root level bucket [2]", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(4,2u)); // .
fw.unsafe_push(create_level_info(3,3u)); // overflow
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // bucket
}
levelized_priority_queue<pq_test_data, pq_test_label_ext, pq_test_lt,
pq_test_file, 1u, std::less<label_t>,
0u,
1u>
pq({f});
AssertThat(pq.size(), Is().EqualTo(0u));
pq.push(pq_test_data {1, 1});
AssertThat(pq.size(), Is().EqualTo(1u));
pq.push(pq_test_data {1, 2});
AssertThat(pq.size(), Is().EqualTo(2u));
pq.setup_next_level(); // 1
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {1, 1}));
AssertThat(pq.size(), Is().EqualTo(1u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {1, 2}));
AssertThat(pq.size(), Is().EqualTo(0u));
AssertThat(pq.has_next_level(), Is().True());
});
});
describe("levelized_priority_queue<..., FILES=2, ...>", [&]() {
it("can push into and pull from merge of two meta files' levels", [&]() {
pq_test_file f1;
pq_test_file f2;
{ // Garbage collect the writer early
pq_test_writer fw1(f1);
fw1.unsafe_push(create_level_info(4,2u));
fw1.unsafe_push(create_level_info(3,3u));
fw1.unsafe_push(create_level_info(1,1u));
pq_test_writer fw2(f2);
fw2.unsafe_push(create_level_info(2,1u));
fw2.unsafe_push(create_level_info(1,2u));
}
levelized_priority_queue<pq_test_data, pq_test_label_ext, pq_test_lt,
pq_test_file, 2u, std::less<label_t>,
0u,
1u>
pq({f1,f2});
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.size(), Is().EqualTo(0u));
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {1, 1});
AssertThat(pq.size(), Is().EqualTo(1u));
pq.push(pq_test_data {1, 2});
AssertThat(pq.size(), Is().EqualTo(2u));
pq.push(pq_test_data {2, 3});
AssertThat(pq.size(), Is().EqualTo(3u));
AssertThat(pq.can_pull(), Is().False());
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
pq.setup_next_level();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(1u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {1, 1}));
AssertThat(pq.size(), Is().EqualTo(2u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {1, 2}));
AssertThat(pq.size(), Is().EqualTo(1u));
AssertThat(pq.can_pull(), Is().False());
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(1u));
AssertThat(pq.has_next_level(), Is().True());
pq.setup_next_level();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(2u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {2, 3}));
AssertThat(pq.size(), Is().EqualTo(0u));
AssertThat(pq.has_next_level(), Is().True());
});
});
describe("levelized_priority_queue<..., INIT_LEVEL=1, LOOK_AHEAD=3>", [&]() {
it("initialises with #levels = 0", [&]() {
pq_test_file f;
test_priority_queue<pq_test_file, 3> pq({f});
AssertThat(pq.can_pull(), Is().False());
AssertThat(pq.has_next_level(), Is().False());
AssertThat(pq.can_pull(), Is().False());
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().False());
});
it("initialises with #levels = 1", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 3> pq({f});
AssertThat(pq.can_pull(), Is().False());
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().False());
});
it("initialises with 1 < #levels < #buckets", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(4,1u)); // bucket
fw.unsafe_push(create_level_info(3,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 3> pq({f});
AssertThat(pq.can_pull(), Is().False());
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(3u));
});
it("initialises with #buckets < #levels", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(8,1u)); // .
fw.unsafe_push(create_level_info(7,3u)); // .
fw.unsafe_push(create_level_info(6,4u)); // .
fw.unsafe_push(create_level_info(5,6u)); // .
fw.unsafe_push(create_level_info(4,5u)); // overflow
fw.unsafe_push(create_level_info(3,4u)); // bucket
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 3> pq({f});
AssertThat(pq.can_pull(), Is().False());
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
AssertThat(pq.next_level(), Is().EqualTo(2u));
});
describe(".push(elem_t &) + pull()", [&]{
it("can push into and pull from buckets", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(7,2u)); // .
fw.unsafe_push(create_level_info(6,3u)); // overflow
fw.unsafe_push(create_level_info(5,6u)); // bucket
fw.unsafe_push(create_level_info(4,8u)); // bucket
fw.unsafe_push(create_level_info(3,4u)); // bucket
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 3> pq({f});
AssertThat(pq.size(), Is().EqualTo(0u));
pq.push(pq_test_data {2, 1});
pq.push(pq_test_data {2, 2});
pq.push(pq_test_data {3, 42});
pq.push(pq_test_data {3, 21});
pq.push(pq_test_data {5, 3});
AssertThat(pq.size(), Is().EqualTo(5u));
pq.setup_next_level(); // 2
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {2, 1}));
AssertThat(pq.size(), Is().EqualTo(4u));
pq.push(pq_test_data {3, 2});
pq.push(pq_test_data {6, 2});
pq.push(pq_test_data {4, 2});
AssertThat(pq.size(), Is().EqualTo(7u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {2, 2}));
AssertThat(pq.size(), Is().EqualTo(6u));
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {3, 3});
pq.push(pq_test_data {5, 2});
pq.push(pq_test_data {3, 1});
AssertThat(pq.size(), Is().EqualTo(9u));
pq.setup_next_level(); // 3
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 1}));
AssertThat(pq.size(), Is().EqualTo(8u));
pq.push(pq_test_data {5, 1});
pq.push(pq_test_data {4, 3});
AssertThat(pq.size(), Is().EqualTo(10u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 2}));
AssertThat(pq.size(), Is().EqualTo(9u));
pq.push(pq_test_data {6, 3});
AssertThat(pq.size(), Is().EqualTo(10u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 3}));
AssertThat(pq.size(), Is().EqualTo(9u));
pq.push(pq_test_data {7, 4});
AssertThat(pq.size(), Is().EqualTo(10u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 21}));
AssertThat(pq.size(), Is().EqualTo(9u));
pq.push(pq_test_data {6, 1});
pq.push(pq_test_data {7, 3});
AssertThat(pq.size(), Is().EqualTo(11u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 42}));
AssertThat(pq.size(), Is().EqualTo(10u));
pq.push(pq_test_data {7, 5});
pq.push(pq_test_data {4, 1});
AssertThat(pq.size(), Is().EqualTo(12u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 4
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 1}));
AssertThat(pq.size(), Is().EqualTo(11u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 2}));
AssertThat(pq.size(), Is().EqualTo(10u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 3}));
AssertThat(pq.size(), Is().EqualTo(9u));
pq.push(pq_test_data {7, 1});
pq.push(pq_test_data {7, 2});
AssertThat(pq.size(), Is().EqualTo(11u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 5
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {5, 1}));
AssertThat(pq.size(), Is().EqualTo(10u));
pq.push(pq_test_data {6, 4});
AssertThat(pq.size(), Is().EqualTo(11u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {5, 2}));
AssertThat(pq.size(), Is().EqualTo(10u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {5, 3}));
AssertThat(pq.size(), Is().EqualTo(9u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 6
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {6, 1}));
AssertThat(pq.size(), Is().EqualTo(8u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {6, 2}));
AssertThat(pq.size(), Is().EqualTo(7u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {6, 3}));
AssertThat(pq.size(), Is().EqualTo(6u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {6, 4}));
AssertThat(pq.size(), Is().EqualTo(5u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 7
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {7, 1}));
AssertThat(pq.size(), Is().EqualTo(4u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {7, 2}));
AssertThat(pq.size(), Is().EqualTo(3u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {7, 3}));
AssertThat(pq.size(), Is().EqualTo(2u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {7, 4}));
AssertThat(pq.size(), Is().EqualTo(1u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {7, 5}));
AssertThat(pq.size(), Is().EqualTo(0u));
AssertThat(pq.can_pull(), Is().False());
});
it("can push into overflow queue [1]", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(8,1u)); // .
fw.unsafe_push(create_level_info(7,4u)); // .
fw.unsafe_push(create_level_info(6,7u)); // overflow
fw.unsafe_push(create_level_info(5,10u)); // bucket
fw.unsafe_push(create_level_info(4,8u)); // bucket
fw.unsafe_push(create_level_info(3,4u)); // bucket
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 3> pq({f});
AssertThat(pq.size(), Is().EqualTo(0u));
pq.push(pq_test_data {6, 4});
pq.push(pq_test_data {8, 2});
AssertThat(pq.size(), Is().EqualTo(2u));
pq.setup_next_level(); // 6
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {6, 4}));
AssertThat(pq.size(), Is().EqualTo(1u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 8
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {8,2}));
AssertThat(pq.size(), Is().EqualTo(0u));
AssertThat(pq.can_pull(), Is().False());
});
it("can push into overflow queue [2]", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(8,2u)); // .
fw.unsafe_push(create_level_info(7,3u)); // .
fw.unsafe_push(create_level_info(6,4u)); // overflow
fw.unsafe_push(create_level_info(5,5u)); // bucket
fw.unsafe_push(create_level_info(4,3u)); // bucket
fw.unsafe_push(create_level_info(3,2u)); // bucket
fw.unsafe_push(create_level_info(2,1u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 3> pq({f});
AssertThat(pq.size(), Is().EqualTo(0u));
pq.push(pq_test_data {8, 2});
AssertThat(pq.size(), Is().EqualTo(1u));
pq.setup_next_level(); // 8
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {8,2}));
AssertThat(pq.size(), Is().EqualTo(0u));
AssertThat(pq.can_pull(), Is().False());
});
it("can push into overflow queue [3]", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(12,2u)); // .
fw.unsafe_push(create_level_info(11,4u)); // .
fw.unsafe_push(create_level_info(10,8u)); // .
fw.unsafe_push(create_level_info(9,16u)); // .
fw.unsafe_push(create_level_info(8,32u)); // .
fw.unsafe_push(create_level_info(7,64u)); // .
fw.unsafe_push(create_level_info(6,32u)); // overflow
fw.unsafe_push(create_level_info(5,16u)); // bucket
fw.unsafe_push(create_level_info(4,8u)); // bucket
fw.unsafe_push(create_level_info(3,4u)); // bucket
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 3> pq({f});
AssertThat(pq.size(), Is().EqualTo(0u));
pq.push(pq_test_data {10, 2});
pq.push(pq_test_data {12, 3});
pq.push(pq_test_data {10, 1});
AssertThat(pq.size(), Is().EqualTo(3u));
pq.setup_next_level(); // 10
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {10,1}));
AssertThat(pq.size(), Is().EqualTo(2u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {10,2}));
AssertThat(pq.size(), Is().EqualTo(1u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 12
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {12,3}));
AssertThat(pq.size(), Is().EqualTo(0u));
AssertThat(pq.can_pull(), Is().False());
});
it("can skip unpushed levels until stop_label [1]", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(8,1u)); // .
fw.unsafe_push(create_level_info(7,1u)); // .
fw.unsafe_push(create_level_info(6,2u)); // overflow
fw.unsafe_push(create_level_info(5,3u)); // bucket
fw.unsafe_push(create_level_info(4,4u)); // bucket
fw.unsafe_push(create_level_info(3,3u)); // bucket
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 3> pq({f});
AssertThat(pq.size(), Is().EqualTo(0u));
pq.push(pq_test_data {8, 2});
AssertThat(pq.size(), Is().EqualTo(1u));
pq.setup_next_level(3u); // 3
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 8
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {8,2}));
AssertThat(pq.size(), Is().EqualTo(0u));
AssertThat(pq.can_pull(), Is().False());
});
it("can skip nonempty levels until stop_label [2]", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(8,1)); // .
fw.unsafe_push(create_level_info(7,2u)); // .
fw.unsafe_push(create_level_info(6,3u)); // overflow
fw.unsafe_push(create_level_info(5,2u)); // bucket
fw.unsafe_push(create_level_info(4,3u)); // bucket
fw.unsafe_push(create_level_info(3,1u)); // bucket
fw.unsafe_push(create_level_info(2,1u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 3> pq({f});
AssertThat(pq.size(), Is().EqualTo(0u));
pq.push(pq_test_data {8, 2});
AssertThat(pq.size(), Is().EqualTo(1u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(7u); // 7
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 8
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {8,2}));
AssertThat(pq.size(), Is().EqualTo(0u));
AssertThat(pq.can_pull(), Is().False());
});
it("can merge content of bucket with overflow queue", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(8,2u)); // .
fw.unsafe_push(create_level_info(7,2u)); // .
fw.unsafe_push(create_level_info(6,4u)); // overflow
fw.unsafe_push(create_level_info(5,3u)); // bucket
fw.unsafe_push(create_level_info(4,5u)); // bucket
fw.unsafe_push(create_level_info(3,4u)); // bucket
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 3> pq({f});
AssertThat(pq.can_pull(), Is().False());
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.size(), Is().EqualTo(0u));
// Push something into overflow
pq.push(pq_test_data {6, 4});
pq.push(pq_test_data {7, 1});
pq.push(pq_test_data {8, 2});
pq.push(pq_test_data {6, 2});
AssertThat(pq.size(), Is().EqualTo(4u));
// And into buckets
pq.push(pq_test_data {2, 1});
pq.push(pq_test_data {3, 2});
AssertThat(pq.size(), Is().EqualTo(6u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 2
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {2, 1}));
AssertThat(pq.size(), Is().EqualTo(5u));
pq.push(pq_test_data {3, 1}); // Bucket
AssertThat(pq.size(), Is().EqualTo(6u));
pq.push(pq_test_data {8, 1}); // Overflow
AssertThat(pq.size(), Is().EqualTo(7u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 3
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 1}));
AssertThat(pq.size(), Is().EqualTo(6u));
pq.push(pq_test_data {4, 1}); // Bucket
AssertThat(pq.size(), Is().EqualTo(7u));
pq.push(pq_test_data {5, 2}); // Bucket
AssertThat(pq.size(), Is().EqualTo(8u));
pq.push(pq_test_data {4, 2}); // Bucket
AssertThat(pq.size(), Is().EqualTo(9u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 2}));
AssertThat(pq.size(), Is().EqualTo(8u));
pq.push(pq_test_data {5, 1}); // Bucket
AssertThat(pq.size(), Is().EqualTo(9u));
pq.push(pq_test_data {4, 3}); // Bucket
AssertThat(pq.size(), Is().EqualTo(10u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 4
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 1}));
AssertThat(pq.size(), Is().EqualTo(9u));
pq.push(pq_test_data {5, 3}); // Bucket
AssertThat(pq.size(), Is().EqualTo(10u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 2}));
AssertThat(pq.size(), Is().EqualTo(9u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 3}));
AssertThat(pq.size(), Is().EqualTo(8u));
pq.push(pq_test_data {8, 4}); // Bucket
AssertThat(pq.size(), Is().EqualTo(9u));
pq.push(pq_test_data {7, 2}); // Bucket
AssertThat(pq.size(), Is().EqualTo(10u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 5
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {5, 1}));
AssertThat(pq.size(), Is().EqualTo(9u));
pq.push(pq_test_data {6, 3}); // Bucket
AssertThat(pq.size(), Is().EqualTo(10u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {5, 2}));
AssertThat(pq.size(), Is().EqualTo(9u));
pq.push(pq_test_data {6, 1}); // Bucket
AssertThat(pq.size(), Is().EqualTo(10u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {5, 3}));
AssertThat(pq.size(), Is().EqualTo(9u));
pq.push(pq_test_data {7, 3}); // Bucket
AssertThat(pq.size(), Is().EqualTo(10u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level();// 6
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {6, 1}));
AssertThat(pq.size(), Is().EqualTo(9u));
pq.push(pq_test_data {8, 3}); // Bucket
AssertThat(pq.size(), Is().EqualTo(10u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {6, 2}));
AssertThat(pq.size(), Is().EqualTo(9u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {6, 3}));
AssertThat(pq.size(), Is().EqualTo(8u));
pq.push(pq_test_data {7, 6}); // Bucket
AssertThat(pq.size(), Is().EqualTo(9u));
pq.push(pq_test_data {7, 5}); // Bucket
AssertThat(pq.size(), Is().EqualTo(10u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {6, 4}));
AssertThat(pq.size(), Is().EqualTo(9u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 7
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {7, 1}));
AssertThat(pq.size(), Is().EqualTo(8u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {7, 2}));
AssertThat(pq.size(), Is().EqualTo(7u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {7, 3}));
AssertThat(pq.size(), Is().EqualTo(6u));
pq.push(pq_test_data {8, 5}); // Bucket
AssertThat(pq.size(), Is().EqualTo(7u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {7, 5}));
AssertThat(pq.size(), Is().EqualTo(6u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {7, 6}));
AssertThat(pq.size(), Is().EqualTo(5u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 8
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {8, 1}));
AssertThat(pq.size(), Is().EqualTo(4u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {8, 2}));
AssertThat(pq.size(), Is().EqualTo(3u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {8, 3}));
AssertThat(pq.size(), Is().EqualTo(2u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {8, 4}));
AssertThat(pq.size(), Is().EqualTo(1u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {8, 5}));
AssertThat(pq.size(), Is().EqualTo(0u));
});
it("can deal with exactly as many levels as buckets", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(4,2u)); // bucket
fw.unsafe_push(create_level_info(3,3u)); // bucket
fw.unsafe_push(create_level_info(2,4u)); // bucket
fw.unsafe_push(create_level_info(1,2u)); // bucket
fw.unsafe_push(create_level_info(0,1u)); // skipped
}
test_priority_queue<pq_test_file, 3> pq({f});
AssertThat(pq.size(), Is().EqualTo(0u));
pq.push(pq_test_data {4, 3});
pq.push(pq_test_data {2, 1});
AssertThat(pq.size(), Is().EqualTo(2u));
pq.setup_next_level(); // 2
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {2, 1}));
AssertThat(pq.size(), Is().EqualTo(1u));
pq.push(pq_test_data {3, 2});
pq.push(pq_test_data {3, 1});
AssertThat(pq.size(), Is().EqualTo(3u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 3
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 1}));
AssertThat(pq.size(), Is().EqualTo(2u));
pq.push(pq_test_data {4, 1});
AssertThat(pq.size(), Is().EqualTo(3u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 2}));
AssertThat(pq.size(), Is().EqualTo(2u));
pq.push(pq_test_data {4, 2});
AssertThat(pq.size(), Is().EqualTo(3u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 4
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 1}));
AssertThat(pq.size(), Is().EqualTo(2u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 2}));
AssertThat(pq.size(), Is().EqualTo(1u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {4, 3}));
AssertThat(pq.size(), Is().EqualTo(0u));
AssertThat(pq.can_pull(), Is().False());
});
it("can deal with fewer levels than buckets", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,2u)); // bucket
fw.unsafe_push(create_level_info(0,1u)); // skipped
}
test_priority_queue<pq_test_file, 3> pq({f});
AssertThat(pq.size(), Is().EqualTo(0u));
pq.push(pq_test_data {2, 1});
pq.push(pq_test_data {1, 1});
AssertThat(pq.size(), Is().EqualTo(2u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 1
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {1, 1}));
AssertThat(pq.size(), Is().EqualTo(1u));
pq.push(pq_test_data {2, 2});
AssertThat(pq.size(), Is().EqualTo(2u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 2
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {2, 1}));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {2, 2}));
AssertThat(pq.can_pull(), Is().False());
});
it("can forward to stop_label with an empty overflow queue", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(8,2u)); // .
fw.unsafe_push(create_level_info(7,4u)); // .
fw.unsafe_push(create_level_info(6,2u)); // overflow
fw.unsafe_push(create_level_info(5,6u)); // bucket
fw.unsafe_push(create_level_info(4,8u)); // bucket
fw.unsafe_push(create_level_info(3,4u)); // bucket
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(0,1u)); // skipped
}
test_priority_queue<pq_test_file, 3> pq({f});
AssertThat(pq.size(), Is().EqualTo(0u));
pq.push(pq_test_data {3, 3});
pq.push(pq_test_data {3, 1});
AssertThat(pq.size(), Is().EqualTo(2u));
pq.setup_next_level(2u); // 2
AssertThat(pq.can_pull(), Is().False());
pq.push(pq_test_data {3, 2});
AssertThat(pq.size(), Is().EqualTo(3u));
pq.setup_next_level(4u); // 3
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 1}));
AssertThat(pq.size(), Is().EqualTo(2u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 2}));
AssertThat(pq.size(), Is().EqualTo(1u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 3}));
AssertThat(pq.size(), Is().EqualTo(0u));
AssertThat(pq.can_pull(), Is().False());
});
it("can push into buckets after bucket level rewrite", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(17,2u)); // .
fw.unsafe_push(create_level_info(16,4u)); // .
fw.unsafe_push(create_level_info(15,8u)); // .
fw.unsafe_push(create_level_info(14,11u)); // .
fw.unsafe_push(create_level_info(13,13u)); // .
fw.unsafe_push(create_level_info(12,17u)); // .
fw.unsafe_push(create_level_info(11,19u)); // .
fw.unsafe_push(create_level_info(10,23u)); // .
fw.unsafe_push(create_level_info(9,19u)); // .
fw.unsafe_push(create_level_info(8,17u)); // .
fw.unsafe_push(create_level_info(7,13u)); // .
fw.unsafe_push(create_level_info(6,11u)); // overflow
fw.unsafe_push(create_level_info(5,7u)); // bucket
fw.unsafe_push(create_level_info(4,5u)); // bucket
fw.unsafe_push(create_level_info(3,3u)); // bucket
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 3> pq({f});
AssertThat(pq.size(), Is().EqualTo(0u));
pq.push(pq_test_data {9, 2});
pq.push(pq_test_data {10, 3});
AssertThat(pq.size(), Is().EqualTo(2u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 9
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {9,2}));
AssertThat(pq.size(), Is().EqualTo(1u));
pq.push(pq_test_data {10, 1}); // write bucket
pq.push(pq_test_data {11, 1}); // write bucket
pq.push(pq_test_data {12, 1}); // write bucket
pq.push(pq_test_data {13, 1}); // write bucket
pq.push(pq_test_data {14, 1}); // overflow
AssertThat(pq.size(), Is().EqualTo(6u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 10
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {10,1}));
AssertThat(pq.size(), Is().EqualTo(5u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {10,3}));
AssertThat(pq.size(), Is().EqualTo(4u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 1
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {11,1}));
AssertThat(pq.size(), Is().EqualTo(3u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 12
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {12,1}));
AssertThat(pq.size(), Is().EqualTo(2u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 13
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {13,1}));
AssertThat(pq.size(), Is().EqualTo(1u));
pq.push(pq_test_data {14, 2}); // write bucket (same as the {14,1} in overflow above)
AssertThat(pq.size(), Is().EqualTo(2u));
AssertThat(pq.can_pull(), Is().False());
pq.setup_next_level(); // 14
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {14,1}));
AssertThat(pq.size(), Is().EqualTo(1u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {14,2}));
AssertThat(pq.size(), Is().EqualTo(0u));
AssertThat(pq.can_pull(), Is().False());
});
});
describe(".top() / .peek()", [&]{
it("can pull after a peek in bucket", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(6,1u)); // overflow
fw.unsafe_push(create_level_info(5,2u)); // bucket
fw.unsafe_push(create_level_info(4,4u)); // bucket
fw.unsafe_push(create_level_info(3,4u)); // bucket
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 3> pq({f});
pq.push(pq_test_data {3, 42}); // bucket
AssertThat(pq.can_pull(), Is().False());
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
pq.setup_next_level();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(3u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.peek(), Is().EqualTo(pq_test_data {3, 42}));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {3, 42}));
AssertThat(pq.can_pull(), Is().False());
});
it("can pull after a peek in overflow", [&]() {
pq_test_file f;
{ // Garbage collect the writer early
pq_test_writer fw(f);
fw.unsafe_push(create_level_info(8,1u)); // .
fw.unsafe_push(create_level_info(7,2u)); // .
fw.unsafe_push(create_level_info(6,4u)); // overflow
fw.unsafe_push(create_level_info(5,8u)); // bucket
fw.unsafe_push(create_level_info(4,4u)); // bucket
fw.unsafe_push(create_level_info(3,2u)); // bucket
fw.unsafe_push(create_level_info(2,2u)); // bucket
fw.unsafe_push(create_level_info(1,1u)); // skipped
}
test_priority_queue<pq_test_file, 3> pq({f});
pq.push(pq_test_data {7, 3}); // overflow
AssertThat(pq.can_pull(), Is().False());
AssertThat(pq.has_current_level(), Is().False());
AssertThat(pq.has_next_level(), Is().True());
pq.setup_next_level();
AssertThat(pq.has_current_level(), Is().True());
AssertThat(pq.current_level(), Is().EqualTo(7u));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.peek(), Is().EqualTo(pq_test_data {7, 3}));
AssertThat(pq.can_pull(), Is().True());
AssertThat(pq.pull(), Is().EqualTo(pq_test_data {7, 3}));
AssertThat(pq.can_pull(), Is().False());
});
});
});
});
});
| 32.744122 | 106 | 0.522982 | logsem |
806d669014ed04684d2d427201fa98c268a344c5 | 179 | cpp | C++ | lib/world/villager.cpp | julienlopez/QCityBuilder | fe61a56bcdeda301211d49a9e358258eefafa14c | [
"MIT"
] | 1 | 2019-03-19T03:14:22.000Z | 2019-03-19T03:14:22.000Z | lib/world/villager.cpp | julienlopez/QCityBuilder | fe61a56bcdeda301211d49a9e358258eefafa14c | [
"MIT"
] | 11 | 2015-01-27T17:35:12.000Z | 2018-08-13T07:48:35.000Z | lib/world/villager.cpp | julienlopez/QCityBuilder | fe61a56bcdeda301211d49a9e358258eefafa14c | [
"MIT"
] | null | null | null | #include "villager.hpp"
namespace World
{
Villager::Villager(const City& city)
: m_city(city)
{
}
auto Villager::state() const -> State
{
return m_state;
}
} // World
| 10.529412 | 37 | 0.648045 | julienlopez |
80715ff3ed17de53c7c5b8feac35970bdcf6f490 | 638 | cpp | C++ | modules/renders/rendergl/src/editor/rhiwrapper.cpp | thunder-engine/thunder | 14a70d46532b8b78635835fc05c0ac2f33a12d8b | [
"Apache-2.0"
] | 162 | 2020-09-18T19:42:43.000Z | 2022-03-30T20:27:42.000Z | modules/renders/rendergl/src/editor/rhiwrapper.cpp | thunder-engine/thunder | 14a70d46532b8b78635835fc05c0ac2f33a12d8b | [
"Apache-2.0"
] | 162 | 2020-10-10T11:16:52.000Z | 2022-03-30T17:09:11.000Z | modules/renders/rendergl/src/editor/rhiwrapper.cpp | thunder-engine/thunder | 14a70d46532b8b78635835fc05c0ac2f33a12d8b | [
"Apache-2.0"
] | 12 | 2020-10-18T09:16:35.000Z | 2022-01-08T11:23:17.000Z | #include "editor/rhiwrapper.h"
#include "editor/openglwindow.h"
#include <QOpenGLContext>
#include <QOffscreenSurface>
QWindow *createWindow() {
return new OpenGLWindow();
}
void makeCurrent() {
static QOffscreenSurface *surface = nullptr;
static QOpenGLContext *context = nullptr;
if(surface == nullptr) {
surface = new QOffscreenSurface();
surface->create();
context = new QOpenGLContext();
context->setShareContext(QOpenGLContext::globalShareContext());
context->setFormat(surface->requestedFormat());
context->create();
}
context->makeCurrent(surface);
}
| 22.785714 | 71 | 0.675549 | thunder-engine |
8072f7cd2f0189a57e555a737f4337886e133df0 | 9,165 | hpp | C++ | Peridigm/Code/Energy_damage_criterion/src/materials/Peridigm_Material.hpp | oldninja/PeriDoX | f31bccc7b8ea60cd814d00732aebdbbe876a2ac7 | [
"BSD-3-Clause"
] | null | null | null | Peridigm/Code/Energy_damage_criterion/src/materials/Peridigm_Material.hpp | oldninja/PeriDoX | f31bccc7b8ea60cd814d00732aebdbbe876a2ac7 | [
"BSD-3-Clause"
] | null | null | null | Peridigm/Code/Energy_damage_criterion/src/materials/Peridigm_Material.hpp | oldninja/PeriDoX | f31bccc7b8ea60cd814d00732aebdbbe876a2ac7 | [
"BSD-3-Clause"
] | null | null | null | /*! \file Peridigm_Material.hpp */
//@HEADER
// ************************************************************************
//
// Peridigm
// Copyright (2011) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions?
// David J. Littlewood djlittl@sandia.gov
// John A. Mitchell jamitch@sandia.gov
// Michael L. Parks mlparks@sandia.gov
// Stewart A. Silling sasilli@sandia.gov
//
// ************************************************************************
//@HEADER
#ifndef PERIDIGM_MATERIAL_HPP
#define PERIDIGM_MATERIAL_HPP
#include <Teuchos_RCP.hpp>
#include <Teuchos_ParameterList.hpp>
#include <Epetra_Vector.h>
#include <Epetra_Map.h>
#include <vector>
#include <string>
#include <float.h>
#include "Peridigm_DataManager.hpp"
#include "Peridigm_SerialMatrix.hpp"
#include "Peridigm_ScratchMatrix.hpp"
#include "Peridigm_InfluenceFunction.hpp"
namespace PeridigmNS {
//! Base class defining the Peridigm material model interface.
class Material{
public:
//! Standard constructor.
Material(const Teuchos::ParameterList & params) : m_finiteDifferenceProbeLength(DBL_MAX) {
if(params.isParameter("Finite Difference Probe Length"))
m_finiteDifferenceProbeLength = params.get<double>("Finite Difference Probe Length");
}
//! Destructor.
virtual ~Material(){}
//! Return name of material type
virtual std::string Name() const = 0;
//! Returns a vector of field IDs corresponding to the variables associated with the material.
//virtual std::vector<int> FieldIds() const { return m_fieldIds; }
//! Returns the density of the material.
virtual double Density() const = 0;
//! Returns the bulk modulus of the material.
virtual double BulkModulus() const = 0;
//! Returns the shear modulus of the material.
virtual double ShearModulus() const = 0;
//! Returns material property value for a given key
// Only implemented for multiphysics elastic material
virtual double lookupMaterialProperty(const std::string keyname) const {
std::string errorMsg = "**Error, Material::lookupMaterialProperty() called for ";
errorMsg += Name();
errorMsg += " but this function is not implemented.\n";
TEUCHOS_TEST_FOR_EXCEPT_MSG(true, errorMsg);
return 0.0;
}
//! Returns a vector of field IDs corresponding to the variables associated with the material.
virtual std::vector<int> FieldIds() const = 0;
//! Initialize the material model.
virtual void
initialize(const double dt,
const int numOwnedPoints,
const int* ownedIDs,
const int* neighborhoodList,
PeridigmNS::DataManager& dataManager) {}
//! Evaluate the internal force.
virtual void
computeForce(const double dt,
const int numOwnedPoints,
const int* ownedIDs,
const int* neighborhoodList,
PeridigmNS::DataManager& dataManager) const = 0;
/// \enum JacobianType
/// \brief Whether to compute the full tangent stiffness matrix or just its block diagonal entries
///
/// The Peridigm Material base class provides a computeJacobian method that all materials inherit
/// to compute the tangent stiffness matrix. This base class uses a finite difference method (it provides both
/// forward and centered) to numerically approximate the jacobian. Derived classes may override this method
/// to compute the jacobian via another approach (for example, automatic differentiation) or may simply
/// inherit and use the finite difference Jacobian, which will work for all derived mateiral classes.
///
/// The default behavior of this
/// method is to compute the full tangent stiffness matrix. However, is it occasionally useful to compute
/// and store only the block diagonal entries -- specifically, the only the entries of the matrix that
/// describe interactions between different dofs for an individual node. This manifests as a block-diagonal
/// with each block of dimension 3x3, and one block for each node. This block-diagonal matrix is useful,
/// for example, as a preconditioner for the full Jacobian matrix. The 3x3 blocks are also the "P" matrices
/// used by the ComputeStabilityIndex compute class. See that class for more information.
///
/// \note The default behavior is to compute the full tangent stiffness matrix. This enum is useful to only
/// if you need to efficiently compute only the block diagonal entries of the full tangent stiffness matrix.
enum JacobianType { UNDEFINED=0, NONE=1, FULL_MATRIX=2, BLOCK_DIAGONAL=3 };
//! Evaluate the jacobian.
virtual void
computeJacobian(const double dt,
const int numOwnedPoints,
const int* ownedIDs,
const int* neighborhoodList,
PeridigmNS::DataManager& dataManager,
PeridigmNS::SerialMatrix& jacobian,
PeridigmNS::Material::JacobianType jacobianType = PeridigmNS::Material::FULL_MATRIX) const;
//! Compute stored elastic energy density
virtual void
computeStoredElasticEnergyDensity(const double dt,
const int numOwnedPoints,
const int* ownedIDs,
const int* neighborhoodList,
PeridigmNS::DataManager& dataManager) const {}
//! Compute the bulk modulus given any two elastic constants from among: bulk modulus, shear modulus, Young's modulus, Poisson's ratio.
double calculateBulkModulus(const Teuchos::ParameterList & params) const;
//! Compute the shear modulus given any two elastic constants from among: bulk modulus, shear modulus, Young's modulus, Poisson's ratio.
double calculateShearModulus(const Teuchos::ParameterList & params) const;
enum FiniteDifferenceScheme { FORWARD_DIFFERENCE=0, CENTRAL_DIFFERENCE=1 };
// computeDilatation is needed as function to update the dilatation before the damage routine
// this is needed to guarantee the correct deformation for the damage evaluation
virtual void
computeDilatation(
const int numOwnedPoints,
const int* ownedIDs,
const int* neighborhoodList,
const double BM,
const double SM,
PeridigmNS::DataManager& dataManager) const;
protected:
//! Evaluate the jacobian via finite difference (probing)
void
computeFiniteDifferenceJacobian(const double dt,
const int numOwnedPoints,
const int* ownedIDs,
const int* neighborhoodList,
PeridigmNS::DataManager& dataManager,
PeridigmNS::SerialMatrix& jacobian,
FiniteDifferenceScheme finiteDifferenceScheme,
PeridigmNS::Material::JacobianType jacobianType = PeridigmNS::Material::FULL_MATRIX) const;
//! Scratch matrix.
mutable ScratchMatrix scratchMatrix;
//! Finite-difference probe length
double m_finiteDifferenceProbeLength;
//std::vector<int> m_fieldIds;
//Teuchos::ParameterList params;
private:
//! Default constructor with no arguments, private to prevent use.
Material(){}
};
}
#endif // PERIDIGM_MATERIAL_HPP
| 43.851675 | 141 | 0.674741 | oldninja |
807335be0edef7d01fc69aefcf24a7337161344e | 15,585 | cpp | C++ | libyangrtc2/src/yangaudiodev/linux/YangAlsaDeviceHandle.cpp | yangxinghai/yangrtc | 92cc28ade5af6cbe22c151cd1220ab12816694e7 | [
"MIT"
] | 23 | 2021-09-13T06:24:34.000Z | 2022-03-24T10:05:12.000Z | libyangrtc2/src/yangaudiodev/linux/YangAlsaDeviceHandle.cpp | yangxinghai/yangrtc | 92cc28ade5af6cbe22c151cd1220ab12816694e7 | [
"MIT"
] | null | null | null | libyangrtc2/src/yangaudiodev/linux/YangAlsaDeviceHandle.cpp | yangxinghai/yangrtc | 92cc28ade5af6cbe22c151cd1220ab12816694e7 | [
"MIT"
] | 9 | 2021-09-13T06:27:44.000Z | 2022-03-02T00:23:17.000Z | #include <yangaudiodev/linux/YangAlsaDeviceHandle.h>
#ifndef _WIN32
#include <stdlib.h>
#include <malloc.h>
YangAlsaDeviceHandle::YangAlsaDeviceHandle(YangContext *pcontext) {
m_context = pcontext;
m_ahandle = new YangAudioCaptureHandle(pcontext);
m_audioPlayCacheNum = m_context->audio.audioPlayCacheNum;
aIndex = 0;
m_ret = 0;
m_size = 0;
m_loops = 0;
//m_in_audioBuffer = NULL;
m_buffer = NULL;
m_isInit = 0;
m_dev = NULL;
m_frames = 1024;
m_channel = pcontext->audio.channel;
m_sample = pcontext->audio.sample;
m_preProcess = NULL;
m_audioData.initPlay(m_sample,m_channel);
m_audioData.initRender(m_sample,m_channel);
m_audioData.setInAudioBuffers(pcontext->streams.m_playBuffers);
//m_resample=NULL;
}
YangAlsaDeviceHandle::~YangAlsaDeviceHandle() {
// m_in_audioBuffer = NULL;
if (m_loops) {
stop();
while (m_isStart) {
yang_usleep(1000);
}
}
alsa_device_close();
m_preProcess = NULL;
yang_delete(m_buffer);
yang_delete(m_ahandle);
}
void YangAlsaDeviceHandle::setCatureStart() {
m_ahandle->isBuf = 1;
}
void YangAlsaDeviceHandle::setCatureStop() {
m_ahandle->isBuf = 0;
}
void YangAlsaDeviceHandle::setOutAudioBuffer(YangAudioBuffer *pbuffer) {
m_ahandle->setOutAudioBuffer(pbuffer);
}
void YangAlsaDeviceHandle::setPlayAudoBuffer(YangAudioBuffer *pbuffer) {
m_ahandle->m_aecPlayBuffer = pbuffer;
}
void YangAlsaDeviceHandle::setAec(YangAecBase *paec) {
m_ahandle->m_aec = paec;
}
void YangAlsaDeviceHandle::setPreProcess(YangPreProcess *pp) {
m_preProcess = pp;
m_audioData.m_preProcess=pp;
}
int32_t YangAlsaDeviceHandle::alsa_device_open(char *device_name,
uint32_t rate, int32_t channels, int32_t period) {
int32_t dir;
int32_t err;
snd_pcm_hw_params_t *hw_params;
snd_pcm_sw_params_t *sw_params;
snd_pcm_uframes_t period_size = period;
snd_pcm_uframes_t buffer_size = 2 * period;
static snd_output_t *jcd_out;
m_dev = (YangAlsaDevice*) malloc(
(unsigned long) sizeof(YangAlsaDevice));
if (!m_dev)
return ERROR_SYS_NoAudioDevice;
m_dev->device_name = (char*) malloc(1 + strlen(device_name));
if (!m_dev->device_name) {
free(m_dev);
return ERROR_SYS_NoAudioDevice;
}
strcpy(m_dev->device_name, device_name);
m_dev->channels = channels;
m_dev->period = period;
err = snd_output_stdio_attach(&jcd_out, stdout, 0);
if ((err = snd_pcm_open(&m_dev->capture_handle, m_dev->device_name,
SND_PCM_STREAM_CAPTURE, 0)) < 0) {
yang_error("cannot open audio device %s (%s)", m_dev->device_name,
snd_strerror(err));
catpureDeviceState = 0;
//_exit(1);
}
if (catpureDeviceState) {
if ((err = snd_pcm_hw_params_malloc(&hw_params)) < 0) {
yang_error("cannot allocate hardware parameter structure (%s)",
snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_hw_params_any(m_dev->capture_handle, hw_params))
< 0) {
yang_error("cannot initialize hardware parameter structure (%s)",
snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_hw_params_set_access(m_dev->capture_handle,
hw_params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) {
yang_error("cannot set access type (%s)", snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_hw_params_set_format(m_dev->capture_handle,
hw_params, SND_PCM_FORMAT_S16_LE)) < 0) {
yang_error("cannot set sample format (%s)", snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_hw_params_set_rate_near(m_dev->capture_handle,
hw_params, &rate, 0)) < 0) {
yang_error("cannot set sample rate (%s)", snd_strerror(err));
_exit(1);
}
/* yang_error( "rate = %d", rate);*/
if ((err = snd_pcm_hw_params_set_channels(m_dev->capture_handle,
hw_params, channels)) < 0) {
yang_error("cannot set channel count (%s)", snd_strerror(err));
_exit(1);
}
period_size = period;
dir = 0;
if ((err = snd_pcm_hw_params_set_period_size_near(m_dev->capture_handle,
hw_params, &period_size, &dir)) < 0) {
yang_error("cannot set period size (%s)", snd_strerror(err));
_exit(1);
}
// if ((err = snd_pcm_hw_params_set_periods(m_dev->capture_handle, hw_params,2, 0)) < 0) {
// yang_error( "cannot set number of periods (%s)",snd_strerror(err));
// _exit(1);
// }
buffer_size = period_size * 2;
dir = 0;
if ((err = snd_pcm_hw_params_set_buffer_size_near(m_dev->capture_handle,
hw_params, &buffer_size)) < 0) {
yang_error("cannot set buffer time (%s)", snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_hw_params(m_dev->capture_handle, hw_params)) < 0) {
yang_error("cannot set capture parameters (%s)", snd_strerror(err));
_exit(1);
}
/*snd_pcm_dump_setup(dev->capture_handle, jcd_out);*/
snd_pcm_hw_params_free(hw_params);
if ((err = snd_pcm_sw_params_malloc(&sw_params)) < 0) {
yang_error("cannot allocate software parameters structure (%s)",
snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_sw_params_current(m_dev->capture_handle, sw_params))
< 0) {
yang_error("cannot initialize software parameters structure (%s)",
snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_sw_params_set_avail_min(m_dev->capture_handle,
sw_params, period)) < 0) {
yang_error("cannot set minimum available count (%s)",
snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_sw_params(m_dev->capture_handle, sw_params)) < 0) {
yang_error("cannot set software parameters (%s)",
snd_strerror(err));
_exit(1);
}
}
if ((err = snd_pcm_open(&m_dev->playback_handle, m_dev->device_name,
SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
yang_error("cannot open audio device %s (%s)", m_dev->device_name, snd_strerror(err));
playDeviceState=0;
}
if(playDeviceState){
if ((err = snd_pcm_hw_params_malloc(&hw_params)) < 0) {
yang_error("cannot allocate hardware parameter structure (%s)",
snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_hw_params_any(m_dev->playback_handle, hw_params)) < 0) {
yang_error("cannot initialize hardware parameter structure (%s)",
snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_hw_params_set_access(m_dev->playback_handle, hw_params,
SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) {
yang_error("cannot set access type (%s)", snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_hw_params_set_format(m_dev->playback_handle, hw_params,
SND_PCM_FORMAT_S16_LE)) < 0) {
yang_error("cannot set sample format (%s)", snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_hw_params_set_rate_near(m_dev->playback_handle,
hw_params, &rate, 0)) < 0) {
yang_error("cannot set sample rate (%s)", snd_strerror(err));
_exit(1);
}
/* yang_error( "rate = %d", rate);*/
if ((err = snd_pcm_hw_params_set_channels(m_dev->playback_handle, hw_params,
channels)) < 0) {
yang_error("cannot set channel count (%s)", snd_strerror(err));
_exit(1);
}
period_size = period;
dir = 0;
if ((err = snd_pcm_hw_params_set_period_size_near(m_dev->playback_handle,
hw_params, &period_size, &dir)) < 0) {
yang_error("cannot set period size (%s)", snd_strerror(err));
_exit(1);
}
// if ((err = snd_pcm_hw_params_set_periods(m_dev->playback_handle, hw_params, 2, 0)) < 0) {
// yang_error( "cannot set number of periods (%s)", snd_strerror(err));
// _exit(1);
// }
buffer_size = period_size * 2;
dir = 0;
if ((err = snd_pcm_hw_params_set_buffer_size_near(m_dev->playback_handle,
hw_params, &buffer_size)) < 0) {
yang_error("cannot set buffer time (%s)", snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_hw_params(m_dev->playback_handle, hw_params)) < 0) {
yang_error("cannot set playback parameters (%s)", snd_strerror(err));
_exit(1);
}
/*snd_pcm_dump_setup(dev->playback_handle, jcd_out);*/
snd_pcm_hw_params_free(hw_params);
if ((err = snd_pcm_sw_params_malloc(&sw_params)) < 0) {
yang_error("cannot allocate software parameters structure (%s)",
snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_sw_params_current(m_dev->playback_handle, sw_params))
< 0) {
yang_error("cannot initialize software parameters structure (%s)",
snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_sw_params_set_avail_min(m_dev->playback_handle,
sw_params, period)) < 0) {
yang_error("cannot set minimum available count (%s)",
snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_sw_params_set_start_threshold(m_dev->playback_handle,
sw_params, period)) < 0) {
yang_error("cannot set start mode (%s)", snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_sw_params(m_dev->playback_handle, sw_params)) < 0) {
yang_error("cannot set software parameters (%s)", snd_strerror(err));
_exit(1);
}
snd_pcm_link(m_dev->capture_handle, m_dev->playback_handle);
if ((err = snd_pcm_prepare(m_dev->capture_handle)) < 0) {
yang_error("cannot prepare audio interface for use (%s)",
snd_strerror(err));
_exit(1);
}
if ((err = snd_pcm_prepare(m_dev->playback_handle)) < 0) {
yang_error("cannot prepare audio interface for use (%s)",
snd_strerror(err));
_exit(1);
}
}
if(catpureDeviceState){
m_dev->readN = snd_pcm_poll_descriptors_count(m_dev->capture_handle);
m_dev->read_fd = (pollfd*) malloc(m_dev->readN * sizeof(*m_dev->read_fd));
if (snd_pcm_poll_descriptors(m_dev->capture_handle, m_dev->read_fd,
m_dev->readN) != m_dev->readN) {
yang_error("cannot obtain capture file descriptors (%s)",
snd_strerror(err));
_exit(1);
}
}
if(playDeviceState){
m_dev->writeN = snd_pcm_poll_descriptors_count(m_dev->playback_handle);
m_dev->write_fd = (pollfd*) malloc(m_dev->writeN * sizeof(*m_dev->read_fd));
if (snd_pcm_poll_descriptors(m_dev->playback_handle, m_dev->write_fd,
m_dev->writeN) != m_dev->writeN) {
yang_error("cannot obtain playback file descriptors (%s)",
snd_strerror(err));
_exit(1);
}
}
if(!catpureDeviceState&&!playDeviceState){
return ERROR_SYS_NoAudioDevice;
}else if(!catpureDeviceState){
return ERROR_SYS_NoAudioCaptureDevice;
}else if(!playDeviceState){
return ERROR_SYS_NoAudioPlayDevice;
}
return Yang_Ok;
}
void YangAlsaDeviceHandle::alsa_device_close() {
if (m_dev) {
snd_pcm_close(m_dev->capture_handle);
snd_pcm_close(m_dev->playback_handle);
free(m_dev->device_name);
free(m_dev);
m_dev = NULL;
}
}
int32_t YangAlsaDeviceHandle::alsa_device_read(short *pcm, int32_t len) {
if ((m_ret = snd_pcm_readi(m_dev->capture_handle, pcm, len)) != len) {
if (m_ret < 0) {
if (m_ret == -EPIPE) {
yang_error("An overrun has occured, reseting capture");
} else {
yang_error("read from audio interface failed (%s)",
snd_strerror(m_ret));
//m_ret = snd_pcm_recover(m_dev->capture_handle, m_ret, 0);
}
if ((m_ret = snd_pcm_prepare(m_dev->capture_handle)) < 0) {
yang_error("cannot prepare audio interface for use (%s)",
snd_strerror(m_ret));
}
if ((m_ret = snd_pcm_start(m_dev->capture_handle)) < 0) {
yang_error("cannot prepare audio interface for use (%s)",
snd_strerror(m_ret));
}
} else {
yang_error(
"Couldn't read as many samples as I wanted (%d instead of %d)",
m_ret, len);
}
return 1;
}
return Yang_Ok;
}
int32_t YangAlsaDeviceHandle::alsa_device_write(const short *pcm, int32_t len) {
if ((m_ret = snd_pcm_writei(m_dev->playback_handle, pcm, len)) != len) {
if (m_ret < 0) {
if (m_ret == -EPIPE) {
// yang_usleep(1000);
yang_error("An underrun has occured, reseting playback, len=%d",len);
} else {
yang_error("write to audio interface failed (%s)",
snd_strerror(m_ret));
}
if ((m_ret = snd_pcm_prepare(m_dev->playback_handle)) < 0) {
yang_error("cannot prepare audio interface for use (%s)",
snd_strerror(m_ret));
}
} else {
yang_error(
"Couldn't write as many samples as I wanted (%d instead of %d)",
m_ret, len);
}
return 1;
}
return Yang_Ok;
}
int32_t YangAlsaDeviceHandle::alsa_device_capture_ready(struct pollfd *pfds,
uint32_t nfds) {
unsigned short revents = 0;
if ((m_ret = snd_pcm_poll_descriptors_revents(m_dev->capture_handle, pfds,
m_dev->readN, &revents)) < 0) {
yang_error("error in alsa_device_capture_ready: %s",
snd_strerror(m_ret));
return pfds[0].revents & POLLIN;
}
return revents & POLLIN;
}
int32_t YangAlsaDeviceHandle::alsa_device_playback_ready(struct pollfd *pfds,
uint32_t nfds) {
unsigned short revents = 0;
//int32_t err;
if ((m_ret = snd_pcm_poll_descriptors_revents(m_dev->playback_handle,
pfds + m_dev->readN, m_dev->writeN, &revents)) < 0) {
yang_error("error in alsa_device_playback_ready: %s",
snd_strerror(m_ret));
return pfds[1].revents & POLLOUT;
}
//cerr << (revents & POLLERR) << endl;
return revents & POLLOUT;
}
int32_t YangAlsaDeviceHandle::alsa_device_nfds() {
return m_dev->writeN + m_dev->readN;
}
void YangAlsaDeviceHandle::alsa_device_getfds(struct pollfd *pfds,
uint32_t nfds) {
int32_t i;
//assert(nfds >= m_dev->writeN + m_dev->readN);
for (i = 0; i < m_dev->readN; i++)
pfds[i] = m_dev->read_fd[i];
for (i = 0; i < m_dev->writeN; i++)
pfds[i + m_dev->readN] = m_dev->write_fd[i];
}
void YangAlsaDeviceHandle::setInAudioBuffer(vector<YangAudioPlayBuffer*> *pal) {
//m_in_audioBuffer = pal;
}
void YangAlsaDeviceHandle::stopLoop() {
m_loops = 0;
}
void YangAlsaDeviceHandle::run() {
startLoop();
}
int32_t YangAlsaDeviceHandle::init() {
if (m_isInit)
return Yang_Ok;
if (m_context->audio.usingMono) {
m_channel = 1;
m_sample = 16000;
}
m_frames=m_sample*m_channel/50;
if (m_preProcess) {
m_preProcess->init(m_frames, m_sample, m_channel);
}
int32_t ret = alsa_device_open((char*)"default", m_sample, m_channel, m_frames);
m_size = m_frames * 2 * m_channel; // 2 bytes/sample, 2 channels
m_buffer = (uint8_t*) malloc(m_size);
m_isInit = 1;
return ret;
}
void YangAlsaDeviceHandle::startLoop() {
m_loops = 1;
int32_t nfds = alsa_device_nfds();
pollfd *pfds = (pollfd*) malloc(sizeof(*pfds) * nfds);
alsa_device_getfds(pfds, nfds);
int32_t audiolen = m_frames * m_channel * 2;
short* pcm_short=new short[audiolen/2];
uint8_t *pcm_write = (uint8_t*)pcm_short;//new uint8_t[audiolen];
uint8_t *tmp = NULL;
int32_t readStart = 0;
YangFrame frame;
while (m_loops) {
poll(pfds, nfds, -1);
if (playDeviceState&&alsa_device_playback_ready(pfds, nfds)) {
tmp=m_audioData.getRenderAudioData(audiolen);
if(tmp){
memcpy(pcm_write, tmp, audiolen);
if (!readStart) readStart = 1;
}else{
memset(pcm_write, 0, audiolen);
}
/**
if (m_in_audioBuffer && hasData()) {
for (size_t i = 0; i < m_in_audioBuffer->size(); i++) {
if (m_in_audioBuffer->at(i)
&& m_in_audioBuffer->at(i)->size() > 0) {
tmp = m_in_audioBuffer->at(i)->getAudios(&frame);
if (tmp) {
if (m_preProcess)
m_preProcess->preprocess_run((short*) tmp);
if (i == 0) {
memcpy(pcm_write, tmp, audiolen);
} else {
m_mix.yangMix1(pcm_write, tmp, audiolen, 128);
}
}
tmp = NULL;
if (m_in_audioBuffer->at(i)->size()
> m_audioPlayCacheNum)
m_in_audioBuffer->at(i)->resetIndex();
}
}
if (!readStart) readStart = 1;
}**/
alsa_device_write( pcm_short, m_frames);
if (readStart)
m_ahandle->putEchoPlay(pcm_short,audiolen);
}
if (catpureDeviceState&&alsa_device_capture_ready(pfds, nfds)) {
alsa_device_read((short*) m_buffer, m_frames);
if (readStart)
m_ahandle->putEchoBuffer(m_buffer,audiolen);
else
m_ahandle->putBuffer1(m_buffer,audiolen);
}
}
free(pfds);
pfds = NULL;
yang_deleteA(pcm_short);
pcm_write=NULL;
}
#endif
| 26.824441 | 92 | 0.690728 | yangxinghai |
80765c8617c2b91c1ece9ab1e8924507cf5fb583 | 3,125 | cc | C++ | core/map_recognise.cc | Arpan-2109/caroline | 23aba9ac9a35697c02358aeb88ed121d3d97a99c | [
"MIT"
] | 1 | 2017-07-27T15:08:19.000Z | 2017-07-27T15:08:19.000Z | core/map_recognise.cc | Arpan-2109/caroline | 23aba9ac9a35697c02358aeb88ed121d3d97a99c | [
"MIT"
] | null | null | null | core/map_recognise.cc | Arpan-2109/caroline | 23aba9ac9a35697c02358aeb88ed121d3d97a99c | [
"MIT"
] | 1 | 2020-10-01T08:46:10.000Z | 2020-10-01T08:46:10.000Z | // Copyright (c) 2014 The Caroline authors. All rights reserved.
// Use of this source file is governed by a MIT license that can be found in the
// LICENSE file.
/// @author Sirotkin Dmitry <dmitriy.v.sirotkin@gmail.com
#include "core/depth_map.h"
#include "core/map_recognise.h"
#include "core/median_map_filter.h"
namespace core {
MapRecognise::MapRecognise() :
object_map_(0, 0),
new_map_(0, 0)
{}
DepthMap MapRecognise::filter(const DepthMap &map) {
MedianMapFilter myfilter;
myfilter.SetKernel(1);
object_map_ = DepthMap(map.width(), map.height());
new_map_ = DepthMap(map.width(), map.height());
new_map_ = myfilter.filter(map);
for (int i = 0; i < map.width(); i++) {
for (int j = 0; j < map.height(); j++) {
object_map_.SetDepth(i, j, 0);
}
}
int NumberCounter = 0;
for (int i = 0; i < map.width(); i++) {
for (int j = 0; j < map.height(); j++) {
if (object_map_.Depth(i, j) == 0) {
++NumberCounter;
dfs(i, j, NumberCounter);
}
}
}
return object_map_;
}
void MapRecognise::SetPrecision(float Precision) {
precision_ = Precision; // Precision>=1
}
int MapRecognise::NeighbourDepth(int i, int j, int direction) {
if ((direction == 0) && (i > 0))
return object_map_.Depth(--i, j);
if ((direction == 1) && (i < (object_map_.width()-1)))
return object_map_.Depth(++i, j);
if ((direction == 2) && (j > 0))
return object_map_.Depth(i, --j);
if ((direction == 3) && (j < (object_map_.height()-1)))
return object_map_.Depth(i, ++j);
return (-1);
}
void MapRecognise::dfs(int i, int j, int NumberCounter) {
object_map_.SetDepth(i, j, NumberCounter);
for (int direction = 0; direction < 4; direction++) {
if ((SmoothNeighbourhood(i, j, direction, precision_) == true) &&
(NeighbourDepth(i, j, direction) == 0)) {
if ((direction == 0) && (i > 0)) {
dfs(--i, j, NumberCounter);
}
if ((direction == 1) && (i < (object_map_.width()-1))) {
dfs(++i, j, NumberCounter);
}
if ((direction == 2) && (j > 0)) {
dfs(i, --j, NumberCounter);
}
if ((direction == 3) && (j < (object_map_.height()-1))) {
dfs(i, ++j, NumberCounter);
}
}
}
}
bool MapRecognise::SmoothNeighbourhood(int w, int h,
int direction, float precision_) {
float Special;
if ((direction == 0) && (w > 0)) {
Special = static_cast<float>
(new_map_.Depth(w, h) / new_map_.Depth(w - 1, h));
--w;
}
if ((direction == 1) && (w < (new_map_.width() - 1))) {
Special = static_cast<float>
(new_map_.Depth(w, h) / new_map_.Depth(w + 1, h));
++w;
}
if ((direction == 2) && (h > 0)) {
Special = static_cast<float>
(new_map_.Depth(w, h) / new_map_.Depth(w, h - 1));
--h;
}
if ((direction == 3) && (h < (new_map_.height() - 1))) {
Special = static_cast<float>
(new_map_.Depth(w, h) / new_map_.Depth(w, h + 1));
++h;
}
return ((Special <= precision_) && (Special >= (1 / precision_)));
}
} // namespace core
| 29.761905 | 80 | 0.5616 | Arpan-2109 |
8076a6b0de61ebadc7e63e94a179d2d0fdaf19cd | 1,184 | cc | C++ | src/zone-container-base-test.cc | emptyland/mio | 77ec9737b4002820c31fca241aaa6711a7391285 | [
"BSD-2-Clause"
] | null | null | null | src/zone-container-base-test.cc | emptyland/mio | 77ec9737b4002820c31fca241aaa6711a7391285 | [
"BSD-2-Clause"
] | null | null | null | src/zone-container-base-test.cc | emptyland/mio | 77ec9737b4002820c31fca241aaa6711a7391285 | [
"BSD-2-Clause"
] | null | null | null | #include "zone-container-base.h"
#include "gtest/gtest.h"
namespace mio {
class ZoneLinkedArrayTest : public ::testing::Test {
public:
virtual void SetUp() override {
zone_ = new Zone;
}
virtual void TearDown() override {
delete zone_;
}
protected:
Zone *zone_;
};
TEST_F(ZoneLinkedArrayTest, Sanity) {
ZoneLinkedArray<int> array(zone_);
ASSERT_EQ(0, array.size());
ASSERT_EQ(ZoneLinkedArray<int>::kDefaultCapacity, array.capacity());
ASSERT_EQ(251, array.segment_max_capacity());
}
TEST_F(ZoneLinkedArrayTest, Pointer) {
ZoneLinkedArray<void *> array(zone_);
ASSERT_EQ(0, array.size());
ASSERT_EQ(ZoneLinkedArray<void *>::kDefaultCapacity, array.capacity());
ASSERT_EQ(251, array.segment_max_capacity());
}
TEST_F(ZoneLinkedArrayTest, Advance) {
ZoneLinkedArray<int> array(zone_);
for (int i = 0; i < ZoneLinkedArray<int>::kDefaultCapacity + 1; ++i) {
array.Add(i);
}
ASSERT_EQ(ZoneLinkedArray<int>::kDefaultCapacity * 2, array.capacity());
for (int i = 0; i < ZoneLinkedArray<int>::kDefaultCapacity + 1; ++i) {
ASSERT_EQ(i, array.Get(i));
}
}
} // namespace mio
| 23.68 | 76 | 0.663851 | emptyland |
807e172268f05730d2f9ebe7bd6555ac2a29c5b5 | 7,332 | cpp | C++ | test/blackbox/implementations/ImplementationsTest.cpp | rockstarartist/DDS-Router | 245099e5e1be584e9d37e9b16648183ab383d727 | [
"Apache-2.0"
] | null | null | null | test/blackbox/implementations/ImplementationsTest.cpp | rockstarartist/DDS-Router | 245099e5e1be584e9d37e9b16648183ab383d727 | [
"Apache-2.0"
] | null | null | null | test/blackbox/implementations/ImplementationsTest.cpp | rockstarartist/DDS-Router | 245099e5e1be584e9d37e9b16648183ab383d727 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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>
#include <iostream>
#include <gtest_aux.hpp>
#include <gtest/gtest.h>
#include <TestLogHandler.hpp>
#include <ddsrouter/core/DDSRouter.hpp>
#include <ddsrouter/exceptions/ConfigurationException.hpp>
#include <ddsrouter/exceptions/InitializationException.hpp>
#include <ddsrouter/participant/implementations/auxiliar/DummyParticipant.hpp>
#include <ddsrouter/types/configuration_tags.hpp>
#include <ddsrouter/types/utils.hpp>
#include <ddsrouter/types/Log.hpp>
using namespace eprosima::ddsrouter;
void set_allowed_topic(
RawConfiguration& configuration,
std::string topic_name = "__test_topic_ddsrouter__",
std::string topic_type = "__test_topic_type_ddsrouter__")
{
RawConfiguration topic;
topic[TOPIC_NAME_TAG] = topic_name;
topic[TOPIC_TYPE_NAME_TAG] = topic_type;
RawConfiguration allow_list;
allow_list.push_back(topic);
configuration[ALLOWLIST_TAG] = allow_list;
}
void set_domain(
RawConfiguration& configuration,
uint16_t seed = 0)
{
configuration[DOMAIN_ID_TAG] = seed;
}
RawConfiguration participant_configuration(
ParticipantType type,
uint16_t value = 0)
{
RawConfiguration participant_configuration;
RawConfiguration address;
address[ADDRESS_IP_TAG] = "127.0.0.1";
address[ADDRESS_PORT_TAG] = 11666 + value;
participant_configuration[PARTICIPANT_TYPE_TAG] = type.to_string();
switch (type())
{
case ParticipantType::SIMPLE_RTPS:
set_domain(participant_configuration);
break;
case ParticipantType::LOCAL_DISCOVERY_SERVER:
participant_configuration[LISTENING_ADDRESSES_TAG].push_back(address); // TODO: make it from method
break;
case ParticipantType::WAN:
participant_configuration[LISTENING_ADDRESSES_TAG].push_back(address); // TODO: make it from method
break;
// Add cases where Participants need specific arguments
default:
break;
}
static_cast<void>(value);
return participant_configuration;
}
/**
* Test that tries to create a DDSRouter with only one Participant.
*
* It expects to receive an exception
*/
TEST(ImplementationsTest, solo_participant_implementation)
{
// For each Participant Type
for (ParticipantType type : ParticipantType::all_valid_participant_types())
{
// Generate configuration
RawConfiguration configuration;
// Add two participants
configuration["participant_1"] = participant_configuration(1);
// Create DDSRouter entity
ASSERT_THROW(DDSRouter router(configuration), InitializationException);
}
}
/**
* Test that creates a DDSRouter with a Pair of Participants of same type.
* It creates a DDSRouter with two Participants of same kind, starts it, then stops it and finally destroys it.
*
* This test will fail if it crashes.
*/
TEST(ImplementationsTest, pair_implementation)
{
test::TestLogHandler test_log_handler;
// For each Participant Type
for (ParticipantType type : ParticipantType::all_valid_participant_types())
{
// Generate configuration
RawConfiguration configuration;
// Add two participants
configuration["participant_1"] = participant_configuration(1);
configuration["participant_2"] = participant_configuration(2);
// Create DDSRouter entity
DDSRouter router(configuration);
// Start DDSRouter
router.start();
// Stop DDS Router
router.stop();
// Let DDSRouter object destroy for the next iteration
}
}
/**
* Test that creates a DDSRouter with a Pair of Participants of same type.
* It creates a DDSRouter with two Participants of same kind, starts it with an active topic,
* then stops it and finally destroys it.
*
* This test will fail if it crashes.
*/
TEST(ImplementationsTest, pair_implementation_with_topic)
{
test::TestLogHandler test_log_handler;
// For each Participant Type
for (ParticipantType type : ParticipantType::all_valid_participant_types())
{
// Generate configuration
RawConfiguration configuration;
// Add two participants
configuration["participant_1"] = participant_configuration(1);
configuration["participant_2"] = participant_configuration(2);
// Set topic to active
set_allowed_topic(configuration);
// Create DDSRouter entity
DDSRouter router(configuration);
// Start DDSRouter
router.start();
// Stop DDS Router
router.stop();
// Let DDSRouter object destroy for the next iteration
}
}
/**
* Test that creates a DDSRouter with several Participants, one of each type
* It creates a DDSRouter with a Participant of each kind,
* starts it with an active topic, then stops it and finally destroys it.
*
* This test will fail if it crashes.
*/
TEST(ImplementationsTest, all_implementations)
{
test::TestLogHandler test_log_handler;
{
// Generate configuration
RawConfiguration configuration;
uint16_t participant_number = 1;
// For each Participant Type set it in configuration
for (ParticipantType type : ParticipantType::all_valid_participant_types())
{
// Add participant
std::string participant_name = "participant_" + type.to_string();
configuration[participant_name] = participant_configuration(type, ++participant_number);
}
// Set topic to active
set_allowed_topic(configuration);
// Create DDSRouter entity
DDSRouter router(configuration);
// Start DDSRouter
router.start();
// Stop DDS Router
router.stop();
// Let DDSRouter object destroy for the next iteration
}
}
/**
* Test that creates a DDSRouter with 3 simple configurations, 2 of them with same id, fails
*
* There is no easy way to test this case as the yaml will be ill-formed with two keys.
* Thus, it must be implemented from a yaml in string format.
*/
TEST(ImplementationsTest, duplicated_ids)
{
const char* yaml_str =
R"(
participant_1:
type: simple
domain: 0
participant_2:
type: simple
domain: 1
participant_2:
type: simple
domain: 2
)";
RawConfiguration configuration(yaml_str);
ASSERT_THROW(DDSRouter ddsrouter(configuration), ConfigurationException);
}
int main(
int argc,
char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 28.529183 | 111 | 0.688625 | rockstarartist |
807e4e4e0a3406f942bcf8cc76f36db159b39101 | 997 | cpp | C++ | src/nomad/Application.cpp | manning390/Nomad | d2a7aabb9bd4cfe56cc37bd786533634f019c02a | [
"MIT"
] | null | null | null | src/nomad/Application.cpp | manning390/Nomad | d2a7aabb9bd4cfe56cc37bd786533634f019c02a | [
"MIT"
] | null | null | null | src/nomad/Application.cpp | manning390/Nomad | d2a7aabb9bd4cfe56cc37bd786533634f019c02a | [
"MIT"
] | null | null | null | #include "Application.hpp"
#include "State/IntroState.hpp"
#include <SFML/Graphics/Image.hpp>
Application::Application() {
initConfig();
};
void Application::run() {
// Output so we know we're running
std::cout << config["ver"] << std::endl;
// Create window
window.create(sf::VideoMode{config.getUInt("windowX"), config.getUInt("windowY")}, config["ver"], sf::Style::Titlebar | sf::Style::Close);
// Set Icon
sf::Image icon;
if(!icon.loadFromFile("assets/icon.png"))
std::cout << "Icon did not load" << std::endl;
else
window.setIcon(icon.getSize().x, icon.getSize().y, icon.getPixelsPtr());
// Init engine
machine.run(StateMachine::build<IntroState>(machine, window, true));
// Main Loop
while(machine.isRunning()) {
machine.nextState();
machine.update();
machine.draw();
}
};
void Application::initConfig() {
std::ifstream f("config");
f >> config; // load configs
f.close();
} | 24.925 | 142 | 0.617854 | manning390 |
808044210e72f46f116c150299614c5845714d76 | 4,499 | cpp | C++ | src/core/view-access-interface.cpp | nenad/wayfire | 9b36acf0c032da39477f60214a7ba1cd549da44c | [
"MIT"
] | null | null | null | src/core/view-access-interface.cpp | nenad/wayfire | 9b36acf0c032da39477f60214a7ba1cd549da44c | [
"MIT"
] | null | null | null | src/core/view-access-interface.cpp | nenad/wayfire | 9b36acf0c032da39477f60214a7ba1cd549da44c | [
"MIT"
] | null | null | null | #include "wayfire/condition/access_interface.hpp"
#include "wayfire/output.hpp"
#include "wayfire/view.hpp"
#include "wayfire/view-access-interface.hpp"
#include "wayfire/workspace-manager.hpp"
#include <algorithm>
#include <iostream>
#include <string>
#include <wlr/util/edges.h>
#include "config.h"
#if WF_HAS_XWAYLAND
extern "C"
{
#define static
#define class class_t
#define namespace namespace_t
#include <wlr/xwayland.h>
#undef static
#undef class
#undef namespace
}
#endif
namespace wf
{
view_access_interface_t::view_access_interface_t()
{}
view_access_interface_t::view_access_interface_t(wayfire_view view) : _view(view)
{}
view_access_interface_t::~view_access_interface_t()
{}
variant_t view_access_interface_t::get(const std::string & identifier, bool & error)
{
variant_t out = std::string(""); // Default to empty string as output.
error = false; // Assume things will go well.
// Cannot operate if no view is set.
if (_view == nullptr)
{
error = true;
return out;
}
if (identifier == "app_id")
{
out = _view->get_app_id();
} else if (identifier == "title")
{
out = _view->get_title();
} else if (identifier == "role")
{
switch (_view->role)
{
case VIEW_ROLE_TOPLEVEL:
out = std::string("TOPLEVEL");
break;
case VIEW_ROLE_UNMANAGED:
out = std::string("UNMANAGED");
break;
case VIEW_ROLE_DESKTOP_ENVIRONMENT:
out = std::string("DESKTOP_ENVIRONMENT");
break;
default:
std::cerr <<
"View access interface: View has unsupported value for role: " <<
static_cast<int>(_view->role) << std::endl;
error = true;
break;
}
} else if (identifier == "fullscreen")
{
out = _view->fullscreen;
} else if (identifier == "activated")
{
out = _view->activated;
} else if (identifier == "minimized")
{
out = _view->minimized;
} else if (identifier == "visible")
{
out = _view->is_visible();
} else if (identifier == "focusable")
{
out = _view->is_focuseable();
} else if (identifier == "mapped")
{
out = _view->is_mapped();
} else if (identifier == "tiled-left")
{
out = (_view->tiled_edges & WLR_EDGE_LEFT) > 0;
} else if (identifier == "tiled-right")
{
out = (_view->tiled_edges & WLR_EDGE_RIGHT) > 0;
} else if (identifier == "tiled-top")
{
out = (_view->tiled_edges & WLR_EDGE_TOP) > 0;
} else if (identifier == "tiled-bottom")
{
out = (_view->tiled_edges & WLR_EDGE_BOTTOM) > 0;
} else if (identifier == "maximized")
{
out = _view->tiled_edges == TILED_EDGES_ALL;
} else if (identifier == "floating")
{
out = _view->tiled_edges == 0;
} else if (identifier == "type")
{
do {
if (_view->role == VIEW_ROLE_TOPLEVEL)
{
out = std::string("toplevel");
break;
}
if (_view->role == VIEW_ROLE_UNMANAGED)
{
#if WF_HAS_XWAYLAND
auto surf = _view->get_wlr_surface();
if (surf && wlr_surface_is_xwayland_surface(surf))
{
out = std::string("x-or");
break;
}
#endif
out = std::string("unmanaged");
break;
}
if (!_view->get_output())
{
out = std::string("unknown");
break;
}
uint32_t layer = _view->get_output()->workspace->get_view_layer(_view);
if ((layer == LAYER_BACKGROUND) || (layer == LAYER_BOTTOM))
{
out = std::string("background");
} else if (layer == LAYER_TOP)
{
out = std::string("panel");
} else if (layer == LAYER_LOCK)
{
out = std::string("overlay");
}
break;
out = std::string("unknown");
} while (false);
} else
{
std::cerr << "View access interface: Get operation triggered to" <<
" unsupported view property " << identifier << std::endl;
}
return out;
}
void view_access_interface_t::set_view(wayfire_view view)
{
_view = view;
}
} // End namespace wf.
| 25.856322 | 84 | 0.537008 | nenad |
808364c83cec32ecfb0275686edcb9964d5dcc65 | 10,120 | cpp | C++ | HN_CSS/HN_StringCSS.cpp | Jusdetalent/JT_Network | 9af82a158be0fea1dbe2bcbc32bfac5ab54cdeba | [
"MIT"
] | 1 | 2019-09-01T05:10:01.000Z | 2019-09-01T05:10:01.000Z | HN_CSS/HN_StringCSS.cpp | Jusdetalent/JT_Network | 9af82a158be0fea1dbe2bcbc32bfac5ab54cdeba | [
"MIT"
] | null | null | null | HN_CSS/HN_StringCSS.cpp | Jusdetalent/JT_Network | 9af82a158be0fea1dbe2bcbc32bfac5ab54cdeba | [
"MIT"
] | null | null | null |
/*
* Style source file
* Henock @ Comedac :: 18/ 02/ 2017
*/
#include "HN_StringCSS.hpp"
#include <iostream>
bool isNextCharacter(const char *buffer, int c, int &cur_pos_t)
{
int cur_pos = cur_pos_t;
int i;
for(i = buffer[cur_pos_t]; i != '\0'; i = buffer[cur_pos_t])
{
cur_pos_t++;
if(i == c)
{
cur_pos_t = cur_pos;
return true;
}
else if(i != '\n' && i != '\t')
{
cur_pos_t = cur_pos;
return false;
}
}
cur_pos_t = cur_pos;
return false;
}
int getStyleValue(const char *buffer, std::string &value, int &cur_pos_t)
{
int li, i;
while((i = buffer[cur_pos_t]) != '\0')
{
// Take character
cur_pos_t++;
if(i != ';' && i != '}' && i != '\n'
&& i != '\t')
{
value+= i;
}
// Catch the end
if(i == ';' || i == '}')
{
break;
}
// In case of special character
else if(i == '(' || i == '['
|| i == '"' || i == '\'')
{
// Fix end character
if(i == '('){li = ')';}
else if(i == '['){li = ']';}
else{li = i;}
// Loop
while((i = buffer[cur_pos_t]) != '\0')
{
// Take character
cur_pos_t++;
if(i != ';' && i != '}' && i != '\n'
&& i != '\t')
{
value+= i;
}
// Avoid infinite loop
if(li == i)
{
break;
}
}
}
}
return i;
}
int getStyleName(const char *buffer, std::string &name, int &cur_pos_t)
{
int li, i;
bool yes = false;
while((i = buffer[cur_pos_t]) != '\0')
{
// Take character
cur_pos_t++;
if(i != '\n' && i != '\t' && i != '{')
{
name+= i;
}
// Catch the end
if(i == '{' || i == ';')
{
return i;
}
// In case of new line
if(i == '\n')
{
if(!isNextCharacter(buffer, '{', cur_pos_t) && !yes)
return i;
yes = false;
}
// In case of quote
else if(i == ',')
{
if(isNextCharacter(buffer, '\n', cur_pos_t))
yes = true;
}
// In case of special character
else if(i == '(' || i == '['
|| i == '"' || i == '\'')
{
// Fix end character
if(i == '('){li = ')';}
else if(i == '['){li = ']';}
else{li = i;}
// Loop
while((i = buffer[cur_pos_t]) != '\0')
{
// Take character
cur_pos_t++;
if(i != '\n' && i != '\t' && i != '{')
{
name+= i;
}
// Avoid infinite loop
if(li == i)
{
break;
}
}
}
}
return i;
}
std::vector<struct HN_Attribute *> *takeStyleAttributes(struct HN_Node *parent_node,
const char *buffer, int &cur_pos_t)
{
// Allocate data
std::vector<struct HN_Attribute *>
*attributes = new std::vector<struct HN_Attribute *>;
// Read data
int i = 0;
std::string attr_name, attr_value;
while((i = buffer[cur_pos_t]) != '\0')
{
cur_pos_t++;
switch(i)
{
/*
In case of value begin
or node style end
*/
case ':':
case '}':
{
// Treat data
if(strlen(attr_name.c_str()) > 0)
{
// Get value and work on data
i = getStyleValue(buffer, attr_value, cur_pos_t);
// By default :: add attribute
struct HN_Attribute *attr = new struct HN_Attribute;
attr->name = attr_name;
attr->value = attr_value;
attributes->push_back(attr);
// Reset data
attr_name.clear();
attr_value.clear();
}
// If end of style :: return
if(i == '}'){return attributes;}
}
break;
/*
In case of invalid
character
*/
case '\n': case '\t': case '\b': case ' ':
break;
// In case of comment
case '/': i = JumpComment(buffer, cur_pos_t);
break;
// If another node
case '{':
{
struct HN_Node *__node = new HN_Node;
if(__node != NULL)
{
__node->name = attr_name;
__node->simple = true;
__node->attributes = takeStyleAttributes(__node, buffer, cur_pos_t);
parent_node->simple = false;
parent_node->children.push_back(__node);
}
attr_name.clear();
}
break;
// In default
default :
attr_name+= i;
break;
}
}
// Return attributes
return attributes;
}
struct HN_StyleNode findSelector(const char *buffer, int &cur_pos_t)
{
// node to return
struct HN_Node *b_node = new struct HN_Node;
struct HN_StyleNode r_node = {-1, b_node};
r_node.node->name = "style";
int i = 0;
std::string selector;
while((i = buffer[cur_pos_t]) != '\0')
{
cur_pos_t++;
switch(i)
{
case 123: // '{'
{
r_node.node->content = selector;
r_node.type = 0;
return r_node;
}
break;
case 47: i = JumpComment(buffer, cur_pos_t); // '/'
break;
case '\n': case '\t':
break;
case 64: // '@'
{
// Generate data
selector+= i;
i = getStyleName(buffer, selector, cur_pos_t);
r_node.node->content = selector;
// Return style node
if(i == '\n')
{
r_node.type = 1;
return r_node;
}
else{
r_node.type = 0;
return r_node;
}
}
break;
case 60: // '<'
{
// Break reading
delete r_node.node;
r_node.node = NULL;
r_node.type = -1;
while(((i = buffer[cur_pos_t]) != '>') && i != 62)
{
cur_pos_t++;
if(i == '\0'){break;}
}
// Return node
return r_node;
}
break;
default : selector+= i;
break;
}
}
// Return node
return r_node;
}
struct HN_Node *takeStyle(const char *buffer)
{
// Build data pointer
struct HN_StyleNode s_node = {0, NULL};
struct HN_Node *b_node = new struct HN_Node;
b_node->name = "style";
bool isData = false;
int cur_pos_t = 0;
// Loop reading data
while(s_node.type != -1)
{
// Read style
s_node = findSelector(buffer, cur_pos_t);
// Get data
if(s_node.type == 0)
{
// Read attributes
s_node.node->attributes = takeStyleAttributes(s_node.node,
buffer, cur_pos_t);
}
// In case of empty data
else if(s_node.type == -1)
{
break;
}
// Delete node
b_node->children.push_back(s_node.node);
isData = true;
}
// Verify if data loaded
if(!isData)
{
delete b_node;
b_node = NULL;
}
// Return data
return b_node;
}
bool harvestStyle(struct HN_Node *b_node, const char *buffer,
int &cur_pos_t)
{
// Build data pointer
struct HN_StyleNode s_node = {0, NULL};
bool isData = false;
// Loop reading data
while(s_node.type != -1)
{
// Get selector
s_node = findSelector(buffer, cur_pos_t);
// Get data
if(s_node.type == 0)
{
// Read attributes
s_node.node->attributes = takeStyleAttributes(s_node.node,
buffer, cur_pos_t);
}
// In case of empty data
else if(s_node.type == -1)
{
break;
}
// Delete node
b_node->children.push_back(s_node.node);
isData = true;
}
// Verify if data loaded
if(!isData){return false;}
// Return data
return true;
}
| 26.149871 | 94 | 0.356719 | Jusdetalent |
808583063727d07dfa1b91b21b9a72831e9264e1 | 2,382 | cpp | C++ | Kernel/Filesystem/fat.cpp | foragerDev/GevOS | f21c8432dd63ab583d9132422bf313ebf60557e8 | [
"Unlicense"
] | null | null | null | Kernel/Filesystem/fat.cpp | foragerDev/GevOS | f21c8432dd63ab583d9132422bf313ebf60557e8 | [
"Unlicense"
] | null | null | null | Kernel/Filesystem/fat.cpp | foragerDev/GevOS | f21c8432dd63ab583d9132422bf313ebf60557e8 | [
"Unlicense"
] | null | null | null | #include "fat.hpp"
/*Read only*/
void ReadBiosBlock(AdvancedTechnologyAttachment* hd, uint32_t partitionOffset)
{
BiosParameterBlock32 bpb;
hd->Read28(partitionOffset, (uint8_t*)&bpb, sizeof(BiosParameterBlock32));
printf("sectors per cluster: ");
printf("%x", bpb.sectorsPerCluster);
printf("\n");
uint32_t fatStart = partitionOffset + bpb.reservedSectors;
uint32_t fatSize = bpb.tableSize;
uint32_t dataStart = fatStart + fatSize * bpb.fatCopies;
uint32_t rootStart = dataStart + bpb.sectorsPerCluster * (bpb.rootCluster - 2);
DirectoryEntryFat32 dirent[16];
hd->Read28(rootStart, (uint8_t*)&dirent[0], 16 * sizeof(DirectoryEntryFat32));
int zindex = 0;
uint8_t fdata[512];
for (int i = 0; i < 16; i++) {
if (dirent[i].name[0] == 0x00)
break;
if ((dirent[i].attributes & 0x0F) == 0x0F)
continue;
printf((char*)dirent[i].name, "\n");
if ((dirent[i].attributes & 0x10) == 0x10)
continue;
uint32_t firstFileCluster = ((uint32_t)dirent[i].firstClusterHi) << 16
| ((uint32_t)dirent[i].firstClusterLow);
int32_t SIZE = dirent[i].size;
int32_t nextFileCluster = firstFileCluster;
uint8_t buffer[513];
uint8_t fatbuffer[513];
uint8_t* file_data = 0;
//int y = 0;
while (SIZE > 0) {
uint32_t fileSector = dataStart + bpb.sectorsPerCluster * (nextFileCluster - 2);
int sectorOffset = 0;
for (; SIZE > 0; SIZE -= 512) {
hd->Read28(fileSector + sectorOffset, buffer, 512);
if (++sectorOffset > bpb.sectorsPerCluster)
break;
buffer[SIZE > 512 ? 512 : SIZE] = '\0';
/*Find way to save buffer and store it in a VFS*/
strcat((char*)file_data, (char*)buffer);
file_data += '\0';
printf((char*)file_data);
}
uint32_t fatSectorForCurrentCluster = nextFileCluster / (512 / sizeof(uint32_t));
hd->Read28(fatStart + fatSectorForCurrentCluster, fatbuffer, 512);
uint32_t fatOffsetInSectorForCurrentCluster = nextFileCluster % (512 / sizeof(uint32_t));
nextFileCluster = ((uint32_t*)&fatbuffer)[fatOffsetInSectorForCurrentCluster] & 0x0FFFFFFF;
}
}
}
| 35.552239 | 103 | 0.594458 | foragerDev |
808602874830dbaf5c0699b132f5e0f26c9a950e | 300 | cpp | C++ | Classes/ShopScene.cpp | JungSeBin/YAS | f94370e183b7458f2b5a281f76df2ff537e74652 | [
"MIT"
] | null | null | null | Classes/ShopScene.cpp | JungSeBin/YAS | f94370e183b7458f2b5a281f76df2ff537e74652 | [
"MIT"
] | null | null | null | Classes/ShopScene.cpp | JungSeBin/YAS | f94370e183b7458f2b5a281f76df2ff537e74652 | [
"MIT"
] | null | null | null | #include "ShopScene.h"
USING_NS_CC;
Scene* ShopScene::createScene()
{
auto scene = Scene::create();
auto layer = ShopScene::create();
scene->addChild(layer);
return scene;
}
bool ShopScene::init()
{
if (!Layer::init())
{
return false;
}
return true;
}
| 11.538462 | 37 | 0.583333 | JungSeBin |
8086b4dfc34392b92cf27de43fe6068403a34e8c | 2,815 | hh | C++ | src/hsd/deps/hitman/sat/inc/alg.hh | alexeyignatiev/mbd-mobs | 20aee8de147387f61d48777c3949e2ab00aa954e | [
"MIT"
] | null | null | null | src/hsd/deps/hitman/sat/inc/alg.hh | alexeyignatiev/mbd-mobs | 20aee8de147387f61d48777c3949e2ab00aa954e | [
"MIT"
] | null | null | null | src/hsd/deps/hitman/sat/inc/alg.hh | alexeyignatiev/mbd-mobs | 20aee8de147387f61d48777c3949e2ab00aa954e | [
"MIT"
] | null | null | null | /*******************************************************************************************[Alg.h]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
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.
**************************************************************************************************/
#ifndef Minisat_Alg_h
#define Minisat_Alg_h
#include "vec.hh"
namespace Minisat {
//=================================================================================================
// Useful functions on vector-like types:
//=================================================================================================
// Removing and searching for elements:
//
template<class V, class T>
static inline void remove(V& ts, const T& t)
{
int j = 0;
for (; j < ts.size() && ts[j] != t; j++);
assert(j < ts.size());
for (; j < ts.size()-1; j++) ts[j] = ts[j+1];
ts.pop();
}
template<class V, class T>
static inline bool find(V& ts, const T& t)
{
int j = 0;
for (; j < ts.size() && ts[j] != t; j++);
return j < ts.size();
}
//=================================================================================================
// Copying vectors with support for nested vector types:
//
// Base case:
template<class T>
static inline void copy(const T& from, T& to)
{
to = from;
}
// Recursive case:
template<class T>
static inline void copy(const vec<T>& from, vec<T>& to, bool append = false)
{
if (!append)
to.clear();
for (int i = 0; i < from.size(); i++){
to.push();
copy(from[i], to.last());
}
}
template<class T>
static inline void append(const vec<T>& from, vec<T>& to){ copy(from, to, true); }
//=================================================================================================
}
#endif
| 33.117647 | 99 | 0.547425 | alexeyignatiev |
808a403ca23ed302345ed42bfc79d18d9951d6e9 | 6,728 | cpp | C++ | source/Graphics/texture_opengl.cpp | deadmann/cerberus | 749f8e90bd87b2d8737c57a599979939b2774916 | [
"BSD-2-Clause"
] | null | null | null | source/Graphics/texture_opengl.cpp | deadmann/cerberus | 749f8e90bd87b2d8737c57a599979939b2774916 | [
"BSD-2-Clause"
] | null | null | null | source/Graphics/texture_opengl.cpp | deadmann/cerberus | 749f8e90bd87b2d8737c57a599979939b2774916 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2010 Steven Noonan <steven@uplinklabs.net>
* and Miah Clayton <miah@ferrousmoon.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR 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 "universal_include.h"
#include "Graphics/opengl.h"
#include "Graphics/texture_opengl.h"
OpenGLTexture::OpenGLTexture ()
: Texture(),
m_textureID(INVALID_SURFACE_ID)
{
}
OpenGLTexture::OpenGLTexture ( SDL_Surface *_surface )
: Texture(_surface),
m_textureID(INVALID_SURFACE_ID)
{
}
OpenGLTexture::~OpenGLTexture()
{
}
void OpenGLTexture::Dispose()
{
if ( m_textureID != INVALID_SURFACE_ID &&
m_textureID != SCREEN_SURFACE_ID )
{
glEnable(g_openGL->GetTextureTarget());
Bind();
glTexImage2D ( g_openGL->GetTextureTarget(), 0, g_openGL->GetInternalFormat32(), 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL );
ASSERT_OPENGL_ERRORS;
g_openGL->FreeTexture ( m_textureID );
m_textureID = INVALID_SURFACE_ID;
}
Texture::Dispose();
}
bool OpenGLTexture::Create ( Uint16 _width, Uint16 _height )
{
CrbReleaseAssert ( m_textureID != SCREEN_SURFACE_ID );
CrbReleaseAssert ( _width > 0 ); CrbReleaseAssert ( _height > 0 );
Uint32 oldWidth = _width, oldHeight = _height;
if ( !g_openGL->GetSetting ( OPENGL_TEX_ALLOW_NPOT, false ) ) {
if ( !isPowerOfTwo ( _width ) )
_width = nearestPowerOfTwo ( _width );
if ( !isPowerOfTwo ( _height ) )
_height = nearestPowerOfTwo ( _height );
CrbReleaseAssert ( isPowerOfTwo ( _width * _height ) );
}
Uint32 rmask, gmask, bmask, amask;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
rmask = 0xff000000;
gmask = 0x00ff0000;
bmask = 0x0000ff00;
amask = 0x000000ff;
#else
rmask = 0x000000ff;
gmask = 0x0000ff00;
bmask = 0x00ff0000;
amask = 0xff000000;
#endif
m_sdlSurface = SDL_CreateRGBSurface ( SDL_SWSURFACE, _width, _height, 32, rmask, gmask, bmask, amask );
CrbReleaseAssert ( m_sdlSurface != NULL );
SDL_SetAlpha ( m_sdlSurface, 0, SDL_ALPHA_OPAQUE );
m_textureID = g_openGL->GetFreeTexture();
CrbReleaseAssert ( m_textureID != 0 );
ASSERT_OPENGL_ERRORS;
Bind();
#if 0
glTexParameteri ( g_openGL->GetTextureTarget(), GL_TEXTURE_MIN_FILTER, GL_LINEAR ); // set up for linear scaling
ASSERT_OPENGL_ERRORS;
glTexParameteri ( g_openGL->GetTextureTarget(), GL_TEXTURE_MAG_FILTER, GL_LINEAR );
ASSERT_OPENGL_ERRORS;
#else
glTexParameteri ( g_openGL->GetTextureTarget(), GL_TEXTURE_MIN_FILTER, GL_NEAREST );
ASSERT_OPENGL_ERRORS;
glTexParameteri ( g_openGL->GetTextureTarget(), GL_TEXTURE_MAG_FILTER, GL_NEAREST );
ASSERT_OPENGL_ERRORS;
#endif
g_openGL->VertexArrayStateTexture();
m_originalWidth = oldWidth;
m_originalHeight = oldHeight;
Damage ();
return true;
}
void OpenGLTexture::Bind()
{
CrbReleaseAssert ( m_textureID != SCREEN_SURFACE_ID );
g_openGL->BindTexture ( m_textureID );
}
bool OpenGLTexture::Upload()
{
CrbReleaseAssert ( m_textureID != SCREEN_SURFACE_ID );
if ( !m_damaged ) return false;
CrbReleaseAssert ( m_sdlSurface != NULL );
CrbReleaseAssert ( m_textureID != 0 );
if ( !g_openGL->GetSetting ( OPENGL_TEX_ALLOW_NPOT, false ) )
{
if ( !isPowerOfTwo ( m_sdlSurface->w ) ) {
g_console->SetColour ( IO::Console::FG_YELLOW | IO::Console::FG_INTENSITY );
g_console->WriteLine ( "WARNING: OpenGLTexture has a width of %u (NOT a power of two)", m_sdlSurface->w );
g_console->SetColour ();
}
if ( !isPowerOfTwo ( m_sdlSurface->h ) ) {
g_console->SetColour ( IO::Console::FG_YELLOW | IO::Console::FG_INTENSITY );
g_console->WriteLine ( "WARNING: OpenGLTexture has a height of %u (NOT a power of two)", m_sdlSurface->h );
g_console->SetColour ();
}
}
#ifdef _DEBUG
if ( m_sdlSurface->w > g_graphics->GetMaximumTextureSize() )
{
g_console->SetColour ( IO::Console::FG_YELLOW | IO::Console::FG_INTENSITY );
g_console->WriteLine ( "WARNING: Uploading texture with width larger than hardware supported size." );
g_console->SetColour ();
}
if ( m_sdlSurface->h > g_graphics->GetMaximumTextureSize() )
{
g_console->SetColour ( IO::Console::FG_YELLOW | IO::Console::FG_INTENSITY );
g_console->WriteLine ( "WARNING: Uploading texture with height larger than hardware supported size." );
g_console->SetColour ();
}
#endif
glEnable(g_openGL->GetTextureTarget());
Bind();
glPixelStorei ( GL_UNPACK_ROW_LENGTH, m_sdlSurface->pitch / m_sdlSurface->format->BytesPerPixel );
ASSERT_OPENGL_ERRORS;
switch ( m_sdlSurface->format->BytesPerPixel )
{
case 1: // palette-based sprite!?
CrbReleaseAssert(false);
break;
case 2: // VERY low quality
CrbReleaseAssert(false);
break;
case 3:
glTexImage2D ( g_openGL->GetTextureTarget(), 0, g_openGL->GetInternalFormat24(),
m_sdlSurface->w, m_sdlSurface->h, 0, GL_RGB, GL_UNSIGNED_BYTE, m_sdlSurface->pixels );
break;
case 4:
glTexImage2D ( g_openGL->GetTextureTarget(), 0, g_openGL->GetInternalFormat32(),
m_sdlSurface->w, m_sdlSurface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_sdlSurface->pixels );
break;
}
CrbDebugAssert ( glIsTexture ( m_textureID ) );
ASSERT_OPENGL_ERRORS;
m_damaged = false;
return true;
}
| 33.64 | 132 | 0.682224 | deadmann |
808e1fc31bc897d034394976621d1496590ca6f7 | 2,527 | cpp | C++ | cv/cvfilter.cpp | hoozh/emcv | e61b1d5ad16c255f0306d0e9feb8f32e3a92d97f | [
"BSD-3-Clause"
] | null | null | null | cv/cvfilter.cpp | hoozh/emcv | e61b1d5ad16c255f0306d0e9feb8f32e3a92d97f | [
"BSD-3-Clause"
] | null | null | null | cv/cvfilter.cpp | hoozh/emcv | e61b1d5ad16c255f0306d0e9feb8f32e3a92d97f | [
"BSD-3-Clause"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License For Embedded Computer Vision Library
//
// Copyright (c) 2008, EMCV Project,
// Copyright (c) 2000-2007, Intel Corporation,
// All rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of the copyright holders nor the names of their 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.
//
// Contributors:
// * Shiqi Yu (Shenzhen Institute of Advanced Technology, Chinese Academy of Sciences)
#include "_cv.h"
/****************************************************************************************\
Base Image Filter
\****************************************************************************************/
/* End of file. */
| 48.596154 | 90 | 0.650574 | hoozh |
80908fb70407131cce0adf25991b2980aa567349 | 6,466 | cpp | C++ | examples/multithreading/game/roomstorageloader.cpp | mamontov-cpp/saddy | f20a0030e18af9e0714fe56c19407fbeacc529a7 | [
"BSD-2-Clause"
] | 58 | 2015-08-09T14:56:35.000Z | 2022-01-15T22:06:58.000Z | examples/multithreading/game/roomstorageloader.cpp | mamontov-cpp/saddy-graphics-engine-2d | e25a6637fcc49cb26614bf03b70e5d03a3a436c7 | [
"BSD-2-Clause"
] | 245 | 2015-08-08T08:44:22.000Z | 2022-01-04T09:18:08.000Z | examples/multithreading/game/roomstorageloader.cpp | mamontov-cpp/saddy | f20a0030e18af9e0714fe56c19407fbeacc529a7 | [
"BSD-2-Clause"
] | 23 | 2015-12-06T03:57:49.000Z | 2020-10-12T14:15:50.000Z | #include <utility>
#include <utility>
#include "roomstorageloader.h"
#include <p2d/rectangle.h>
#include <geometry2d.h>
// ====================================== PUBLIC METHODS ======================================
game::RoomStorageLoader::RoomStorageLoader(
const sad::Vector<sad::Sprite2D*>& sprites,
double room_radius,
double detection_radius,
std::function<void(void*)> load_item,
std::function<void(void*)> unload_item
) : m_detection_radius(detection_radius), m_load_item(std::move(load_item)), m_unload_item(std::move(unload_item))
{
sad::Vector<sad::Rect2D> areas;
m_items.resize(sprites.size());
for(size_t i = 0; i < sprites.size(); i++)
{
if (sprites[i])
{
areas.push_back(sprites[i]->area());
m_items[i].Item = sprites[i];
m_items[i].Active = true;
m_items[i].Counter = 1;
m_items[i].Item->addRef();
m_items_to_vector_position.insert(sprites[i], i);
}
else
{
m_items[i].Item = nullptr;
m_items[i].Active = false;
m_items[i].Counter = 0;
}
}
this->splitIntoRooms(areas, room_radius);
}
game::RoomStorageLoader::RoomStorageLoader(
const sad::Vector<sad::p2d::Body*>& bodies,
double room_radius,
double detection_radius,
std::function<void(void*)> load_item,
std::function<void(void*)> unload_item
) : m_detection_radius(detection_radius), m_load_item(std::move(load_item)), m_unload_item(std::move(unload_item))
{
sad::Vector<sad::Rect2D> areas;
m_items.resize(bodies.size());
for(size_t i = 0; i < bodies.size(); i++)
{
if (bodies[i])
{
areas.push_back(static_cast<sad::p2d::Rectangle*>(bodies[i]->currentShape())->rect());
m_items[i].Item = bodies[i];
m_items[i].Active = true;
m_items[i].Counter = 1;
m_items[i].Item->addRef();
m_items_to_vector_position.insert(bodies[i], i);
}
else
{
m_items[i].Item = nullptr;
m_items[i].Active = false;
m_items[i].Counter = 0;
}
}
this->splitIntoRooms(areas, room_radius);
}
game::RoomStorageLoader::~RoomStorageLoader()
{
}
void game::RoomStorageLoader::removeItem(void* object)
{
if (m_items_to_vector_position.contains(object))
{
size_t pos = m_items_to_vector_position[object];
game::StoredObject& o = m_items[pos];
if (o.Active)
{
o.Item->delRef();
o.Item = nullptr;
o.Active = false;
}
}
}
void game::RoomStorageLoader::loadRoom(int index)
{
if (index > -1)
{
assert(static_cast<size_t>(index) < m_room_number_to_items.size());
const sad::Vector<size_t>& indexes = m_room_number_to_items[index];
for(size_t i = 0; i < indexes.size(); i++)
{
if (m_items[indexes[i]].Active)
{
m_items[indexes[i]].Counter++;
if (m_items[indexes[i]].Counter > 0)
{
m_load_item(m_items[indexes[i]].Item);
}
}
}
}
}
void game::RoomStorageLoader::unloadRoom(int index)
{
if (index > -1)
{
assert(static_cast<size_t>(index) < m_room_number_to_items.size());
const sad::Vector<size_t>& indexes = m_room_number_to_items[index];
for(size_t i = 0; i < indexes.size(); i++)
{
if (m_items[indexes[i]].Active)
{
m_items[indexes[i]].Counter++;
if (m_items[indexes[i]].Counter <= 0)
{
m_unload_item(m_items[indexes[i]].Item);
}
}
}
}
}
int game::RoomStorageLoader::roomCount() const
{
return m_room_number_to_items.size();
}
void game::RoomStorageLoader::setRoomCount(int room_count)
{
while (static_cast<int>(m_room_number_to_items.size()) < room_count)
{
m_room_number_to_items.push_back(sad::Vector<size_t>());
}
}
void game::RoomStorageLoader::incrementCounterForRoom(int index)
{
if (index > -1)
{
assert(static_cast<unsigned int>(index) < m_room_number_to_items.size());
const sad::Vector<size_t>& indexes = m_room_number_to_items[index];
for(size_t i = 0; i < indexes.size(); i++)
{
if (m_items[indexes[i]].Active)
{
m_items[indexes[i]].Counter++;
}
}
}
}
void game::RoomStorageLoader::unloadIfCounterIsZeroExceptFor(int min, int max)
{
for(size_t index = 0; index < m_room_number_to_items.size(); index++)
{
const sad::Vector<size_t>& indexes = m_room_number_to_items[index];
if ((static_cast<int>(index) != min) && (static_cast<int>(index) != max))
{
for(size_t i = 0; i < indexes.size(); i++)
{
if (m_items[indexes[i]].Active)
{
if (m_items[indexes[i]].Counter <= 0)
{
m_unload_item(m_items[indexes[i]].Item);
}
}
}
}
}
}
// ====================================== PRIVATE METHODS ======================================
void game::RoomStorageLoader::splitIntoRooms(const sad::Vector<sad::Rect2D>& areas, double room_radius)
{
int max_index = -1;
for(size_t area_num = 0; area_num < areas.size(); area_num++)
{
max_index = std::max(max_index, static_cast<int>(areas[area_num].p2().x() / m_detection_radius));
}
for(int i = 0; i <= max_index; i++)
{
m_room_number_to_items.push_back(sad::Vector<size_t>());
}
for(size_t room_number = 0; room_number < m_room_number_to_items.size(); room_number++)
{
double min = room_number * m_detection_radius + m_detection_radius / 2.0 - room_radius / 2.0;
double max = room_number * m_detection_radius + m_detection_radius / 2.0 + room_radius / 2.0;
for(size_t area_num = 0; area_num < areas.size(); area_num++)
{
if (sad::collides1D(min, max, areas[area_num].p0().x(), areas[area_num].p2().x()))
{
m_room_number_to_items[room_number].push_back(area_num);
m_items[area_num].Rooms.push_back(room_number);
}
}
}
}
| 29.525114 | 114 | 0.549954 | mamontov-cpp |
8094c3ad77ff9ea9f5dd641c8448f06d736eb44e | 5,067 | hpp | C++ | include/graph/impl/voxel_grid_graph_builder.hpp | edlabbe/3d-tests | f78acc61d5dc5b73f0f645bcb89bc3b8e4e7bb6a | [
"BSD-2-Clause"
] | null | null | null | include/graph/impl/voxel_grid_graph_builder.hpp | edlabbe/3d-tests | f78acc61d5dc5b73f0f645bcb89bc3b8e4e7bb6a | [
"BSD-2-Clause"
] | null | null | null | include/graph/impl/voxel_grid_graph_builder.hpp | edlabbe/3d-tests | f78acc61d5dc5b73f0f645bcb89bc3b8e4e7bb6a | [
"BSD-2-Clause"
] | null | null | null | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2014-, Open Perception, 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 copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PCL_GRAPH_IMPL_VOXEL_GRID_GRAPH_BUILDER_HPP
#define PCL_GRAPH_IMPL_VOXEL_GRID_GRAPH_BUILDER_HPP
#include <boost/unordered_map.hpp>
#include <pcl/common/io.h>
#include <pcl/common/common.h>
#include <pcl/common/centroid.h>
#include <pcl/octree/octree_impl.h>
#include "graph/voxel_grid_graph_builder.h"
/* The function below is required in order to use boost::unordered_map with
* pcl::octree::OctreeKey key type. It simply hashes the x, y, z array of
* indices, because it uniquely defines the key. */
namespace pcl
{
namespace octree
{
static size_t hash_value (const OctreeKey& b)
{
return boost::hash_value (b.key_);
}
}
}
template <typename PointT, typename GraphT> void
pcl::graph::VoxelGridGraphBuilder<PointT, GraphT>::compute (GraphT& graph)
{
if (!initCompute ())
{
graph = GraphT ();
deinitCompute ();
return;
}
typename pcl::PointCloud<PointT>::Ptr transformed (new pcl::PointCloud<PointT>);
pcl::copyPointCloud (*input_, *transformed);
for (size_t i = 0; i < transformed->size (); ++i)
{
PointT& p = transformed->points[i];
p.x /= p.z;
p.y /= p.z;
p.z = std::log (p.z);
}
Eigen::Vector4f min, max;
pcl::getMinMax3D (*transformed, *indices_, min, max);
// Create and initialize an Octree that stores point indices
typedef pcl::octree::OctreePointCloud<PointT> Octree;
Octree octree (voxel_resolution_);
octree.defineBoundingBox (min (0), min (1), min (2), max (0), max (1), max (2));
octree.setInputCloud (transformed, indices_);
octree.addPointsFromInputCloud ();
graph = GraphT (octree.getLeafCount ());
typedef boost::unordered_map<pcl::octree::OctreeKey, VertexId> KeyVertexMap;
KeyVertexMap key_to_vertex_map;
point_to_vertex_map_.clear ();
point_to_vertex_map_.resize (transformed->size (), std::numeric_limits<VertexId>::max ());
typename Octree::LeafNodeIterator leaf_itr = octree.leaf_begin ();
for (VertexId v = 0; leaf_itr != octree.leaf_end (); ++leaf_itr, ++v)
{
// Step 1: compute leaf centroid and fill in corresponding elements of the
// point to vertex map.
pcl::CentroidPoint<PointInT> centroid;
std::vector<int>& indices = leaf_itr.getLeafContainer ().getPointIndicesVector ();
for (size_t i = 0; i < indices.size (); ++i)
{
centroid.add (input_->operator[] (indices[i]));
point_to_vertex_map_[indices[i]] = v;
}
centroid.get (graph[v]);
// Step 2: fill in octree key to vertex map.
octree::OctreeKey key = leaf_itr.getCurrentOctreeKey ();
key_to_vertex_map[key] = v;
// Step 2: find neighbors and insert edges.
octree::OctreeKey neighbor_key;
for (int dx = (key.x > 0) ? -1 : 0; dx <= 1; ++dx)
{
neighbor_key.x = static_cast<uint32_t> (key.x + dx);
for (int dy = (key.y > 0) ? -1 : 0; dy <= 1; ++dy)
{
neighbor_key.y = static_cast<uint32_t> (key.y + dy);
for (int dz = (key.z > 0) ? -1 : 0; dz <= 1; ++dz)
{
neighbor_key.z = static_cast<uint32_t> (key.z + dz);
typename KeyVertexMap::iterator f = key_to_vertex_map.find (neighbor_key);
if (f != key_to_vertex_map.end () && v != f->second)
boost::add_edge (v, f->second, graph);
}
}
}
}
}
#endif /* PCL_GRAPH_IMPL_VOXEL_GRID_GRAPH_BUILDER_HPP */
| 34.469388 | 92 | 0.685021 | edlabbe |
8094c62e2614d5eec849a5f35b2c0a3548be2ad8 | 15,204 | cpp | C++ | sources/lib/SG_Gas.cpp | Sphinkie/StarGen-II | acc23bdbeef564d9e538d26611cd92e4b5bb9634 | [
"MIT"
] | 7 | 2020-09-12T14:55:17.000Z | 2022-01-06T02:47:31.000Z | sources/lib/SG_Gas.cpp | Sphinkie/StarGen-II | acc23bdbeef564d9e538d26611cd92e4b5bb9634 | [
"MIT"
] | 1 | 2021-10-21T04:51:57.000Z | 2021-11-01T16:17:27.000Z | sources/lib/SG_Gas.cpp | Sphinkie/StarGen-II | acc23bdbeef564d9e538d26611cd92e4b5bb9634 | [
"MIT"
] | null | null | null | /* ------------------------------------------------------------------------- */
// File : SG_Gas.cpp
// Project : Star Gen
// Author C++ : David de Lorenzo
// Author C : Jim Burrows (see Credits.txt)
/* ------------------------------------------------------------------------- */
#include <math.h>
#include "SG_Gas.h"
#include "SG_Const.h"
/* ------------------------------------------------------------------------- */
/// Constructor.
/**
@param AtomicNumber The atomic number is the number of protons found in the nucleus of the atom. (ID key)
@param Symbol The chemical symbol of the gas.
@param AtomicWeight The atomic weigth is the average atomic mass of the chemical element.
@param MeltPoint The Melting temperature of the element at 1 bar (unit = Kelvin)
@param BoilingPoint The Boiling temperature of the element at 1 bar (unit = Kelvin)
@param Density The gas density of the element (unit = gram/cc)
@param Abunds The Aboundance of the element on the Solar System (unit = ??).
@param Reactivity This indicate how fast the gas will disapear with time (0 = no loss)
@param Toxicity Above this limit, the gas reaches a toxic ratio (unit = ppm).
@param Name The full name of the gas.
*/
/* ------------------------------------------------------------------------- */
SG_Gas::SG_Gas( int AtomicNumber, std::string Symbol,
long double AtomicWeight, long double MeltPoint, long double BoilingPoint,
long double Density, long double Abunds,
long double Reactivity, long double Toxicity, std::string Name)
{
// Gas description
mNum = AtomicNumber;
mSymbol = Symbol;
mName = Name;
mWeight = AtomicWeight;
mMelt = MeltPoint;
mBoil = BoilingPoint;
mDensity = Density;
mAbunds = Abunds;
mReactivity = Reactivity;
mMax_ipp = Toxicity * PPM_PRESSURE; // converted in IPP (Inspired Partial Pressure)
// Calculated parameters for this gas (in the atmosphere)
mAmount = 0;
mPartialPressure = 0;
mPartialPercentage= 0;
// Gas default colour: transparent white
mGasColour.r = 1;
mGasColour.g = 1;
mGasColour.b = 1;
mGasColour.a = 0;
}
/* ------------------------------------------------------------------------- */
/// Destructor
/* ------------------------------------------------------------------------- */
SG_Gas::~SG_Gas()
{
}
/* ------------------------------------------------------------------------- */
/// This function returns the Boiling Temperature of this gas, under a given pressure.
/**
The Boiling Point is the transition between a liquid state and a gas state.
@param pressure The pressure submitted to the gas. (Units = mB)
@return The Boiling point of the gaz (Units = K)
*/
/* ------------------------------------------------------------------------- */
long double SG_Gas::getBoilingPoint(long double pressure)
{
long double pressureB = pressure / MILLIBARS_PER_BAR; // unit = bar
long double bp = mBoil /(373. * ((log((pressureB) + 0.001) / -5050.5) + (1.0 / 373.)));
return bp;
}
/* ------------------------------------------------------------------------- */
/// This function returns the Melting Temperature of this gas, under a given pressure.
/**
The Boiling Point is the transition between a solid state and a liquid state.
@param pressure The pressure submitted to the gas. (Units = mB)
@return The Melting Point of the gaz (Units = K)
*/
/* ------------------------------------------------------------------------- */
long double SG_Gas::getMeltingPoint(long double pressure)
{
/// Note: we consider here that the Melt Point is the same for all pressure.
/// A better calculation can be done.
return mMelt;
}
/* ------------------------------------------------------------------------- */
/// This function return the state of the element at certain conditions.
/**
@param temperature The temperature submitted to the element.
@param pressure The pressure submitted to the element.
@return The state of the element (solid, liquid, or gas)
*/
/* ------------------------------------------------------------------------- */
int SG_Gas::getState(long double temperature, long double pressure)
{
long double BP = this->getBoilingPoint(pressure);
long double MP = this->getMeltingPoint(pressure);
if (temperature<MP) return SOLID;
if (temperature<BP) return LIQUID;
return GAS;
}
/* ------------------------------------------------------------------------- */
/// This function returns the aboundance of the Gas in the Sun.
/** @return the solar aboundance of the Gas. */
/* ------------------------------------------------------------------------- */
long double SG_Gas::getAbound()
{
return mAbunds;
}
/* ------------------------------------------------------------------------- */
/// This function calculate how the gas will slowly diseapear under some atmospheric conditions.
/**
@param temperature The temperature submitted to the gas
@param pressure The pressure submitted to the gas (unit = mB)
@param years The elapsed time (unit = years)
@return The remaining fraction of the gas.
@sa getPres2
*/
/* ------------------------------------------------------------------------- */
long double SG_Gas::getReact(long double temperature, long double pressure, long double years)
{
long double bil_years = years*1e-9;
long double pres2 = this->getPres2(temperature, pressure, years);
// Argon
if (mSymbol == "Ar")
{
return (0.19 * bil_years/4.0);
}
// Oxygen
else if (((mSymbol == "O") || (mSymbol=="O2")) && (bil_years>2) && (temperature>270) && (temperature<400))
{
return pow(1 / (1 + mReactivity), pow1_4(bil_years/2.0) * pres2);
}
// Carbon Dioxid
else if ((mSymbol == "CO2") && (bil_years>2) && (temperature>270) && (temperature<400))
{
return (1.5 * pow(1 / (1 + mReactivity), sqrt(bil_years/2.0) * pres2));
}
// Other gases
else
{
return pow(1 / (1 + mReactivity), bil_years/2.0 * pres2);
}
}
/* ------------------------------------------------------------------------- */
/// Calculations for getReac.
/**
@param temperature The temperature submitted to the gas
@param pressure The pressure submitted to the gas (unit = mB)
@param years The elapsed time (unit = years)
@return ????
@sa getReact
*/
/* ------------------------------------------------------------------------- */
long double SG_Gas::getPres2(long double temperature, long double pressure, long double years)
{
long double bil_years = years*1e-9;
long double pressureB = pressure / MILLIBARS_PER_BAR; // unit = bar
long double pres2;
// Argon
if (mSymbol == "Ar")
{
return (1.0);
}
// Oxygen
else if (((mSymbol=="O") || (mSymbol=="O2")) && (bil_years>2) && (temperature>270) && (temperature<400))
{
// /* pres2 = (0.65 + pressureB/2).0; // Breathable - M: 0.55-1.4 */
pres2 = 0.89 + (pressureB/4.0); // Breathable - M: 0.6-1.8
return (pres2);
}
// Carbon Dioxid
else if ((mSymbol == "CO2") && (bil_years>2) && (temperature>270) && (temperature<400))
{
pres2 = 0.75 + pressureB;
return (pres2);
}
// Other gases
else
{
pres2 = (0.75 + pressureB);
return pow(1 / (1 + mReactivity), bil_years/2.0 * pres2);
}
}
/*--------------------------------------------------------------------------*/
/// This function return the RMS velocity of a gas, under a certain temperature.
/** This is Fogg's eq.16. The molecular weight (usually assumed to be N2)
is used as the basis of the Root Mean Square (RMS) velocity of the
molecule or atom.
@param temperature The Temperature submitted to the gas.
@return The RMS velocity of the gas molecules (Units = cm/sec)
*/
/*--------------------------------------------------------------------------*/
long double SG_Gas::getRMSvelocity(long double temperature)
{
long double RT = 3.0 * MOLAR_GAS_CONST * temperature;
long double V = sqrt(RT / mWeight);
return(V * CM_PER_METER);
}
/* ------------------------------------------------------------------------- */
/// This function returns the ratio of the gas kept by the planet gravity and temperature.
/** This function calculate the ratio of gas escaped from the planet, due to a RMSvelocity
exceeding the Escape Velocity of the planet.
@param temperature The temperature submitted to the gas (unit = Kelvin)
@param Escape_velocity The Escape velocity of the planet (unit = cm/s)
@param years The elapsed time (unit = years)
@return The ratio of gas remaining.
*/
/* ------------------------------------------------------------------------- */
long double SG_Gas::getPVRMS(long double temperature,long double Escape_velocity, long double years)
{
long double bil_years = years*1e-9;
long double vrms = this->getRMSvelocity(temperature);
return pow(1 / (1 + vrms / Escape_velocity), bil_years);
}
/* ------------------------------------------------------------------------- */
/// Faction of the gas depending on the atomic mass.
/** The more the atomic mass of the gas is close of the minimum atomic mass
retained on the planet, the more the fraction will be close to 0.
On the other side, the more the gas is heavy, the more the fraction will
be close to 1, and the more the gas will be kept on the planet.
*/
/* ------------------------------------------------------------------------- */
long double SG_Gas::getFract(long double Molec_weight)
{
return (1 - (Molec_weight / mWeight));
}
/* ------------------------------------------------------------------------- */
/// This function returns the atomic weight for the gas molecule.
/* ------------------------------------------------------------------------- */
long double SG_Gas::getWeight()
{
return (mWeight);
}
/* ------------------------------------------------------------------------- */
/// This function returns the atomic number (AN) of the gas molecule.
/* ------------------------------------------------------------------------- */
int SG_Gas::getAtomicNumber()
{
return mNum;
}
/* ------------------------------------------------------------------------- */
/// Set the amount of the gas in the atmosphere.
/* ------------------------------------------------------------------------- */
void SG_Gas::setAmount(long double amount)
{
mAmount = amount;
}
/* ------------------------------------------------------------------------- */
/// Get the amount of the gas in the atmosphere.
/* ------------------------------------------------------------------------- */
long double SG_Gas::getAmount()
{
return mAmount;
}
/* ------------------------------------------------------------------------- */
/// This function return the chemical symbol of the gas.
/* ------------------------------------------------------------------------- */
std::string SG_Gas::getSymbol()
{
return mSymbol;
}
/* ------------------------------------------------------------------------- */
/// This function indicates if the element is radioactive or not.
/* ------------------------------------------------------------------------- */
bool SG_Gas::isRadioactive()
{
return (mWeight >= 84);
}
/* ------------------------------------------------------------------------- */
/// This function indicates if the gas a reached a toxical concentration in the atmosphere.
/* ------------------------------------------------------------------------- */
bool SG_Gas::isToxic(long double surf_pressure)
{
bool toxicity;
// If the IPP of the gas is higher than the Max IPP, it reaches a toxic level.
toxicity = (this->getInspiredPartialPressure(surf_pressure) > mMax_ipp);
if (mMax_ipp==0) toxicity=false;
return toxicity;
}
/* ------------------------------------------------------------------------- */
/// This function returns the name of the gas.
/* ------------------------------------------------------------------------- */
std::string SG_Gas::getName()
{
return mName;
}
/* ------------------------------------------------------------------------- */
/// This function returns the Maximal Inspired Partial Pressure of the gas.
/** Above this partial pressure, the gas reaches a toxic level.
*/
/* ------------------------------------------------------------------------- */
long double SG_Gas::getMaxIPP()
{
return mMax_ipp;
}
/*--------------------------------------------------------------------------*/
/// This function determine if the gas can be breathed by a human.
/**
Taking into account humidification of the air in the nasal passage and throat.
This formula is on Dole's p. 14
@param surf_pressure The pressure at the surface of the planet
@return The inspired partial pressure.
*/
/*--------------------------------------------------------------------------*/
long double SG_Gas::getInspiredPartialPressure(long double surf_pressure)
{
long double fraction = mPartialPressure / surf_pressure;
return (surf_pressure - H20_ASSUMED_PRESSURE) * fraction;
}
/*--------------------------------------------------------------------------*/
/// Set the Partial Pressure of the gas in the atmosphere.
/*--------------------------------------------------------------------------*/
void SG_Gas::setPartialPressure(long double Partial_pressure)
{
mPartialPressure = Partial_pressure;
}
/*--------------------------------------------------------------------------*/
/// This function returns the Partial Pressure of the gas in the atmosphere.
/*--------------------------------------------------------------------------*/
long double SG_Gas::getPartialPressure()
{
return mPartialPressure;
}
/*--------------------------------------------------------------------------*/
/// This function set the percentage of the gas in the atmosphere.
/** @param pourcentage The percentage should be a value in [0..1]. */
/*--------------------------------------------------------------------------*/
void SG_Gas::setPartialPercentage(long double pourcentage)
{
mPartialPercentage = pourcentage;
}
/*--------------------------------------------------------------------------*/
/// This function returns the percentage of the gas in the atmosphere.
/** @return The percentage is a value in [0..1]. */
/*--------------------------------------------------------------------------*/
long double SG_Gas::getPartialPercentage()
{
return mPartialPercentage;
}
/*--------------------------------------------------------------------------*/
/// This function memorize the colour of this gas.
/**
@param r The RED value of the color (0..1)
@param g The GREEN value of the color (0..1)
@param b The BLUE value of the color (0..1)
@param a The ALPHA value (transparency) of the color (0..1). 0=transparent.
*/
/*--------------------------------------------------------------------------*/
void SG_Gas::setGasColour(double r, double g, double b, double a)
{
mGasColour.r = r;
mGasColour.g = g;
mGasColour.b = b;
mGasColour.a = a;
}
/*--------------------------------------------------------------------------*/
/// This function returns the colour of this gas.
/**
@return The colour and transparency of the gas.
--------------------------------------------------------------------------*/
SG_Gas::SG_colour SG_Gas::getGasColour()
{
return mGasColour;
}
| 36.460432 | 110 | 0.496448 | Sphinkie |
809d6fb9ba55653c9e28f9585aaadf087d1800e8 | 180 | hpp | C++ | Toya-Core/src/CoreDrivers/ToyaCoreDrivers.hpp | Ahmed-YehiaGPEL/Toya-Engine | 16c8e170b2f5022ec56da4ee4223f351726665f3 | [
"MIT"
] | 2 | 2017-05-14T19:07:29.000Z | 2017-05-15T03:26:06.000Z | Toya-Core/src/CoreDrivers/ToyaCoreDrivers.hpp | Ahmed-YehiaGPEL/Toya-Engine | 16c8e170b2f5022ec56da4ee4223f351726665f3 | [
"MIT"
] | 1 | 2017-10-13T11:22:39.000Z | 2017-10-13T11:22:39.000Z | Toya-Core/src/CoreDrivers/ToyaCoreDrivers.hpp | Ahmed-YehiaGPEL/Toya-Engine | 16c8e170b2f5022ec56da4ee4223f351726665f3 | [
"MIT"
] | null | null | null | #pragma once
#include "../CoreDrivers/Time.hpp"
#include "../CoreDrivers/Screen.hpp"
#include "RenderDriver.hpp"
#include "src/Scenes/Scene.hpp"
#include "../CoreDrivers/Color.hpp" | 30 | 36 | 0.744444 | Ahmed-YehiaGPEL |
80a5f57cfc0b19172067086b853d0081e7fc1b45 | 963 | cpp | C++ | Number Theory/Big Mod-UVA - 374.cpp | Nazm-nahid/Code_Box-Topic-Wise- | 2066a9ec83b0500b7ba8be86fbe93cdf027a2da8 | [
"MIT"
] | null | null | null | Number Theory/Big Mod-UVA - 374.cpp | Nazm-nahid/Code_Box-Topic-Wise- | 2066a9ec83b0500b7ba8be86fbe93cdf027a2da8 | [
"MIT"
] | null | null | null | Number Theory/Big Mod-UVA - 374.cpp | Nazm-nahid/Code_Box-Topic-Wise- | 2066a9ec83b0500b7ba8be86fbe93cdf027a2da8 | [
"MIT"
] | null | null | null | // BISMILLAHIR_RAHMANIR_RAHIM
#include <bits/stdc++.h>
#define ll long long
#define sn1(a) scanf("%lld",&a)
#define sn2(a,b) scanf("%lld %lld",&a,&b)
#define pn1(a) printf("%lld\n", a)
#define pn2(a,b) printf("%lld %lld\n",a,b)
#define FOR(x,to) for(x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define PB push_back
#define F first
#define S second
#define MOD 1000000007
using namespace std;
ll bgm(ll a, ll b , ll c)
{
ll x,y;
if(b==0)
return 1;
else if(b%2==0)
{
y=bgm(a,b/2 , c);
return (y*y)%c;
}
else
{
x=a%c;
return (x*bgm(a,b-1,c))%c;
}
}
int main()
{
ll N,m,k,l,r,i,ans,T,j,result,B,P,M;
//(a * b) % MOD = ((a % MOD) * (b % MOD)) % MOD
while(cin>>B>>P>>M)
{
cout<<bgm(B,P,M)<<endl;
}
return 0;
}
// ALHAMDULLIAH
| 18.519231 | 52 | 0.502596 | Nazm-nahid |
80a63c366d8b85f99edee5e71be21f713fd3ff10 | 4,574 | cpp | C++ | osra-2.1.0-1/src/osra_java.cpp | CHEMeDATA/fixingmolfile | 07a96440f957a31cb555a92f46098e0ef87f27ae | [
"MIT"
] | null | null | null | osra-2.1.0-1/src/osra_java.cpp | CHEMeDATA/fixingmolfile | 07a96440f957a31cb555a92f46098e0ef87f27ae | [
"MIT"
] | 5 | 2020-04-01T16:05:15.000Z | 2020-04-02T07:40:10.000Z | osra-2.1.0-1/src/osra_java.cpp | CHEMeDATA/fixingmolfiles | 07a96440f957a31cb555a92f46098e0ef87f27ae | [
"MIT"
] | null | null | null | /******************************************************************************
OSRA: Optical Structure Recognition Application
Created by Igor Filippov, 2007-2013 (igor.v.filippov@gmail.com)
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
St, Fifth Floor, Boston, MA 02110-1301, USA
*****************************************************************************/
#include "config.h" // PACKAGE_VERSION
#ifdef OSRA_JAVA
/* Fix for jlong definition in jni.h on some versions of gcc on Windows */
#if defined(__GNUC__) && !defined(__INTEL_COMPILER)
typedef long long __int64;
#endif
#include <jni.h>
#include <stdlib.h> // calloc(), free()
#include <string> // std::string
#include <ostream> // std:ostream
#include <sstream> // std:ostringstream
#include "osra_lib.h"
extern "C" {
/*
* Class: net_sf_osra_OsraLib
* Method: processImage
* Signature: ([BLjava/io/Writer;Ljava/lang/String;Ljava/lang/String;ZZZ)I
*/
JNIEXPORT jint JNICALL Java_net_sf_osra_OsraLib_processImage(JNIEnv *, jclass, jbyteArray, jobject, jint, jboolean,jint,jdouble,jint, jboolean, jboolean,jstring, jstring, jboolean, jboolean,jboolean, jboolean, jboolean);
/*
* Class: net_sf_osra_OsraLib
* Method: getVersion
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_sf_osra_OsraLib_getVersion(JNIEnv *, jclass);
}
JNIEXPORT jint JNICALL Java_net_sf_osra_OsraLib_processImage(JNIEnv *j_env, jclass j_class,
jbyteArray j_image_data,
jobject j_writer,
jint j_rotate,
jboolean j_invert,
jint j_input_resolution,
jdouble j_threshold,
jint j_do_unpaper,
jboolean j_jaggy,
jboolean j_adaptive_option,
jstring j_output_format,
jstring j_embedded_format,
jboolean j_output_confidence,
jboolean j_show_resolution_guess,
jboolean j_show_page,
jboolean j_output_coordinates,
jboolean j_output_avg_bond_length)
{
const char *output_format = j_env->GetStringUTFChars(j_output_format, NULL);
const char *embedded_format = j_env->GetStringUTFChars(j_embedded_format, NULL);
const char *image_data = (char *) j_env->GetByteArrayElements(j_image_data, NULL);
int result = -1;
if (image_data != NULL)
{
// Perhaps there is a more optimal way to bridge from std:ostream to java.io.Writer.
// See http://stackoverflow.com/questions/524524/creating-an-ostream/524590#524590
std::ostringstream structure_output_stream;
result = osra_process_image(
image_data,
j_env->GetArrayLength(j_image_data),
structure_output_stream,
j_rotate,
j_invert,
j_input_resolution,
j_threshold,
j_do_unpaper,
j_jaggy,
j_adaptive_option,
output_format,
embedded_format,
j_output_confidence,
j_show_resolution_guess,
j_show_page,
j_output_coordinates,
j_output_avg_bond_length,
"."
);
j_env->ReleaseByteArrayElements(j_image_data, (jbyte *) image_data, JNI_ABORT);
// Locate java.io.Writer#write(String) method:
jclass j_writer_class = j_env->FindClass("java/io/Writer");
jmethodID write_method_id = j_env->GetMethodID(j_writer_class, "write", "(Ljava/lang/String;)V");
jstring j_string = j_env->NewStringUTF(structure_output_stream.str().c_str());
j_env->CallVoidMethod(j_writer, write_method_id, j_string);
j_env->DeleteLocalRef(j_writer_class);
j_env->DeleteLocalRef(j_string);
}
j_env->ReleaseStringUTFChars(j_output_format, output_format);
j_env->ReleaseStringUTFChars(j_embedded_format, embedded_format);
return result;
}
JNIEXPORT jstring JNICALL Java_net_sf_osra_OsraLib_getVersion(JNIEnv *j_env, jclass j_class)
{
return j_env->NewStringUTF(PACKAGE_VERSION);
}
#endif
| 34.651515 | 223 | 0.677525 | CHEMeDATA |
80a8013d8bb5935d7f26cd843284246fd23ff0c2 | 6,102 | cpp | C++ | client/lib/gain.cpp | sssssssuzuki/autd3-library-software | 9f8382d099a38c0feb48176896db2f4db251ce40 | [
"MIT"
] | null | null | null | client/lib/gain.cpp | sssssssuzuki/autd3-library-software | 9f8382d099a38c0feb48176896db2f4db251ce40 | [
"MIT"
] | null | null | null | client/lib/gain.cpp | sssssssuzuki/autd3-library-software | 9f8382d099a38c0feb48176896db2f4db251ce40 | [
"MIT"
] | null | null | null | // File: gain.cpp
// Project: lib
// Created Date: 01/06/2016
// Author: Seki Inoue
// -----
// Last Modified: 27/12/2020
// Modified By: Shun Suzuki (suzuki@hapis.k.u-tokyo.ac.jp)
// -----
// Copyright (c) 2020 Hapis Lab. All rights reserved.
//
#include "gain.hpp"
#include <memory>
#include <vector>
#include "consts.hpp"
namespace autd::gain {
inline Float PosMod(const Float a, const Float b) { return a - floor(a / b) * b; }
GainPtr Gain::Create() { return std::make_shared<Gain>(); }
Gain::Gain() noexcept : _built(false), _geometry(nullptr) {}
Gain::Gain(std::vector<AUTDDataArray> data) noexcept : _built(false), _geometry(nullptr), _data(std::move(data)) {}
void Gain::Build() {
if (this->built()) return;
auto geometry = this->geometry();
CheckAndInit(geometry, &this->_data);
for (size_t i = 0; i < geometry->num_devices(); i++) this->_data[i].fill(0x0000);
this->_built = true;
}
bool Gain::built() const noexcept { return this->_built; }
GeometryPtr Gain::geometry() const noexcept { return this->_geometry; }
void Gain::SetGeometry(const GeometryPtr& geometry) noexcept { this->_geometry = geometry; }
std::vector<AUTDDataArray>& Gain::data() { return this->_data; }
GainPtr PlaneWaveGain::Create(const Vector3& direction, const Float amp) {
const auto d = AdjustAmp(amp);
return Create(direction, d);
}
GainPtr PlaneWaveGain::Create(const Vector3& direction, uint8_t duty) {
GainPtr ptr = std::make_shared<PlaneWaveGain>(direction, duty);
return ptr;
}
void PlaneWaveGain::Build() {
if (this->built()) return;
auto geometry = this->geometry();
CheckAndInit(geometry, &this->_data);
const auto dir = this->_direction.normalized();
const auto ULTRASOUND_WAVELENGTH = geometry->wavelength();
const uint16_t duty = static_cast<uint16_t>(this->_duty) << 8 & 0xFF00;
for (size_t dev = 0; dev < geometry->num_devices(); dev++)
for (size_t i = 0; i < NUM_TRANS_IN_UNIT; i++) {
const auto trp = geometry->position(dev, i);
const auto dist = trp.dot(dir);
const auto f_phase = PosMod(dist, ULTRASOUND_WAVELENGTH) / ULTRASOUND_WAVELENGTH;
const auto phase = static_cast<uint16_t>(round(255 * (1 - f_phase)));
this->_data[dev][i] = duty | phase;
}
this->_built = true;
}
GainPtr FocalPointGain::Create(const Vector3& point, const Float amp) {
const auto d = AdjustAmp(amp);
return Create(point, d);
}
GainPtr FocalPointGain::Create(const Vector3& point, uint8_t duty) {
GainPtr gain = std::make_shared<FocalPointGain>(point, duty);
return gain;
}
void FocalPointGain::Build() {
if (this->built()) return;
auto geometry = this->geometry();
CheckAndInit(geometry, &this->_data);
const auto ULTRASOUND_WAVELENGTH = geometry->wavelength();
const uint16_t duty = static_cast<uint16_t>(this->_duty) << 8 & 0xFF00;
for (size_t dev = 0; dev < geometry->num_devices(); dev++)
for (size_t i = 0; i < NUM_TRANS_IN_UNIT; i++) {
const auto trp = geometry->position(dev, i);
const auto dist = (trp - this->_point).norm();
const auto f_phase = fmod(dist, ULTRASOUND_WAVELENGTH) / ULTRASOUND_WAVELENGTH;
const auto phase = static_cast<uint16_t>(round(255 * (1 - f_phase)));
this->_data[dev][i] = duty | phase;
}
this->_built = true;
}
GainPtr BesselBeamGain::Create(const Vector3& point, const Vector3& vec_n, const Float theta_z, const Float amp) {
const auto duty = AdjustAmp(amp);
return Create(point, vec_n, theta_z, duty);
}
GainPtr BesselBeamGain::Create(const Vector3& point, const Vector3& vec_n, Float theta_z, uint8_t duty) {
GainPtr gain = std::make_shared<BesselBeamGain>(point, vec_n, theta_z, duty);
return gain;
}
void BesselBeamGain::Build() {
if (this->built()) return;
auto geometry = this->geometry();
CheckAndInit(geometry, &this->_data);
if (_vec_n.norm() > 0) _vec_n = _vec_n.normalized();
const Vector3 v(_vec_n.y(), -_vec_n.x(), 0.);
const auto theta_w = asin(v.norm());
const auto ULTRASOUND_WAVELENGTH = geometry->wavelength();
const uint16_t duty = static_cast<uint16_t>(this->_duty) << 8 & 0xFF00;
for (size_t dev = 0; dev < geometry->num_devices(); dev++)
for (size_t i = 0; i < NUM_TRANS_IN_UNIT; i++) {
const auto trp = geometry->position(dev, i);
const auto r = trp - this->_point;
const auto v_x_r = r.cross(v);
const auto rr = cos(theta_w) * r + sin(theta_w) * v_x_r + v.dot(r) * (1 - cos(theta_w)) * v;
const auto f_phase =
fmod(sin(_theta_z) * sqrt(rr.x() * rr.x() + rr.y() * rr.y()) - cos(_theta_z) * rr.z(), ULTRASOUND_WAVELENGTH) / ULTRASOUND_WAVELENGTH;
const auto phase = static_cast<uint16_t>(round(255 * (1 - f_phase)));
this->_data[dev][i] = duty | phase;
}
this->_built = true;
}
GainPtr CustomGain::Create(const uint16_t* data, const size_t data_length) {
const auto dev_num = data_length / NUM_TRANS_IN_UNIT;
std::vector<AUTDDataArray> raw_data(dev_num);
size_t dev_idx = 0;
size_t tran_idx = 0;
for (size_t i = 0; i < data_length; i++) {
raw_data[dev_idx][tran_idx++] = data[i];
if (tran_idx == NUM_TRANS_IN_UNIT) {
dev_idx++;
tran_idx = 0;
}
}
GainPtr gain = std::make_shared<CustomGain>(raw_data);
return gain;
}
GainPtr CustomGain::Create(const std::vector<AUTDDataArray>& data) {
GainPtr gain = std::make_shared<CustomGain>(data);
return gain;
}
void CustomGain::Build() { this->_built = true; }
GainPtr TransducerTestGain::Create(const size_t transducer_index, const uint8_t duty, const uint8_t phase) {
GainPtr gain = std::make_shared<TransducerTestGain>(transducer_index, duty, phase);
return gain;
}
void TransducerTestGain::Build() {
if (this->built()) return;
auto geometry = this->geometry();
CheckAndInit(geometry, &this->_data);
const uint16_t d = static_cast<uint16_t>(this->_duty) << 8 & 0xFF00;
const uint16_t s = static_cast<uint16_t>(this->_phase) & 0x00FF;
this->_data[geometry->device_idx_for_trans_idx(_transducer_idx)][_transducer_idx % NUM_TRANS_IN_UNIT] = d | s;
this->_built = true;
}
} // namespace autd::gain
| 32.115789 | 144 | 0.677483 | sssssssuzuki |
80ab7d0bf4eadfa03ea248f27298c732eaea9196 | 3,104 | cpp | C++ | contests/leetcode-194/d.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 23 | 2020-03-30T05:44:56.000Z | 2021-09-04T16:00:57.000Z | contests/leetcode-194/d.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 1 | 2020-05-10T15:04:05.000Z | 2020-06-14T01:21:44.000Z | contests/leetcode-194/d.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 6 | 2020-03-30T05:45:04.000Z | 2020-08-13T10:01:39.000Z | #include <bits/stdc++.h>
#define INF 2000000000
using namespace std;
typedef long long ll;
int read(){
int f = 1, x = 0;
char c = getchar();
while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();}
while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar();
return f * x;
}
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool isLeaf(TreeNode* root) {
return root->left == NULL && root->right == NULL;
}
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
template<typename T>
ostream& operator << (ostream& os, const vector<T>& vec){
for (auto x: vec)
os << x << " ";
os << endl;
return os;
}
template<typename T>
ostream& operator << (ostream& os, const vector<vector<T>>& vec){
for (auto& v: vec){
for (auto x: v)
os << x << " ";
os << endl;
}
return os;
}
class Solution {
pair<int, pair<int, int> > pp[205], p[205];
int fa[105], m;
int Find(int x){
return (x == fa[x] ? x: (fa[x] = Find(fa[x])));
}
bool Union(int x, int y){
int u = Find(x), v = Find(y);
if (u == v) return false;
fa[u] = v;
return true;
}
int kruskal(int x, int n){
int cnt = n, cost = 0;
int tot = 0;
for (int i = 0; i < m; ++i){
if (i != x) p[tot++] = pp[i];
}
for (int i = 0; i < n; ++i)
fa[i] = i;
sort(p, p + tot);
for (int i = 0; i < tot; ++i){
if (Union(p[i].second.first, p[i].second.second))
--cnt, cost += p[i].first;
}
return cnt == 1 ? cost: INT_MAX;
}
int kruskal2(int x, int n){
int cnt = n, cost = 0;
int tot = 0;
for (int i = 0; i < n; ++i)
fa[i] = i;
for (int i = 0; i < m; ++i){
if (i != x) p[tot++] = pp[i];
else cost += pp[i].first, Union(pp[i].second.first, pp[i].second.second), --cnt;
}
sort(p, p + tot);
for (int i = 0; i < tot; ++i){
if (Union(p[i].second.first, p[i].second.second))
--cnt, cost += p[i].first;
}
return cnt == 1 ? cost: INT_MAX;
}
public:
vector<vector<int>> findCriticalAndPseudoCriticalEdges(int n, vector<vector<int>>& edges) {
vector<int> key, nkey;
m = edges.size();
for (int i = 0; i < m; ++i){
pp[i].first = edges[i][2],
pp[i].second.first = edges[i][0],
pp[i].second.second = edges[i][1];
}
int res = kruskal(-1, n);
for (int i = 0; i < m; ++i){
if (kruskal(i, n) != res) key.push_back(i);
else if (kruskal2(i, n) == res) nkey.push_back(i);
}
vector<vector<int> > vec;
vec.push_back(key);
vec.push_back(nkey);
return vec;
}
};
Solution sol;
void init(){
}
void solve(){
// sol.convert();
}
int main(){
init();
solve();
return 0;
}
| 25.235772 | 95 | 0.458119 | Nightwish-cn |
80b2ceeb3adcd248c3c09f0d18129740c95fb158 | 2,348 | cpp | C++ | examples/allocator.cpp | lyrahgames/buddy-system | c45fc44c95af566666f5b1d8780e2941b7c12869 | [
"MIT"
] | null | null | null | examples/allocator.cpp | lyrahgames/buddy-system | c45fc44c95af566666f5b1d8780e2941b7c12869 | [
"MIT"
] | null | null | null | examples/allocator.cpp | lyrahgames/buddy-system | c45fc44c95af566666f5b1d8780e2941b7c12869 | [
"MIT"
] | null | null | null | #include <iomanip>
#include <iostream>
#include <list>
#include <vector>
//
#include <lyrahgames/buddy_system/buddy_system.hpp>
using namespace std;
using namespace lyrahgames;
template <typename T>
using my_vector = vector<T, buddy_system::allocator<T>>;
template <typename T>
using my_list = list<T, buddy_system::allocator<T>>;
template <typename T>
ostream& operator<<(ostream& os, const my_vector<T>& v) {
for (const auto x : v) os << setw(10) << x;
return os << '\n';
}
template <typename T>
ostream& operator<<(ostream& os, const my_list<T>& v) {
for (const auto x : v) os << setw(10) << x;
return os << '\n';
}
int main() {
buddy_system::arena arena{size_t{1} << 12}; // 4096 B
cout << arena;
string input{};
getline(cin, input);
{
my_vector<int> v1{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
arena}; // buddy_system_arena can be implicitly casted to
// buddy_system_allocator
cout << v1 << arena;
getline(cin, input);
my_vector<int> v2{{10, 20, 30, 40, 50, 60}, arena};
cout << v1 << v2 << arena;
getline(cin, input);
v1.clear();
v1.shrink_to_fit();
cout << v1 << v2 << arena;
getline(cin, input);
v2.push_back(70);
v2.push_back(80);
v2.push_back(90);
v2.push_back(100);
v2.push_back(110);
v2.push_back(120);
v2.push_back(130);
v2.push_back(140);
v2.push_back(150);
v2.push_back(160);
cout << v1 << v2 << arena;
getline(cin, input);
}
cout << arena;
getline(cin, input);
{
my_list<int> v1{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
arena}; // buddy_system_arena can be implicitly
// casted to buddy_system_allocator
cout << v1 << arena;
getline(cin, input);
my_list<int> v2{{10, 20, 30, 40, 50, 60}, arena};
cout << v1 << v2 << arena;
getline(cin, input);
v1.clear();
cout << v1 << v2 << arena;
getline(cin, input);
v2.push_back(70);
v2.push_back(80);
v2.push_back(90);
v2.push_back(100);
v2.push_back(110);
v2.push_back(120);
v2.push_back(130);
v2.push_back(140);
v2.push_back(150);
v2.push_back(160);
cout << v1 << v2 << arena;
getline(cin, input);
}
cout << arena;
getline(cin, input);
} | 24.715789 | 80 | 0.57368 | lyrahgames |
80b75a26e512873a340f89fdbeb9065b1122f9f5 | 3,506 | tcc | C++ | ulmblas/level2/trumv.tcc | sneha0401/ulmBLAS | 2b7665c6abc1784fe4041febd9d12de519ef4f08 | [
"BSD-3-Clause"
] | 95 | 2015-05-14T15:21:44.000Z | 2022-03-17T08:02:08.000Z | ulmblas/level2/trumv.tcc | sneha0401/ulmBLAS | 2b7665c6abc1784fe4041febd9d12de519ef4f08 | [
"BSD-3-Clause"
] | 4 | 2020-06-25T14:59:49.000Z | 2022-02-16T12:45:00.000Z | ulmblas/level2/trumv.tcc | sneha0401/ulmBLAS | 2b7665c6abc1784fe4041febd9d12de519ef4f08 | [
"BSD-3-Clause"
] | 40 | 2015-09-14T02:43:43.000Z | 2021-12-26T11:43:36.000Z | #ifndef ULMBLAS_LEVEL2_TRUMV_TCC
#define ULMBLAS_LEVEL2_TRUMV_TCC 1
#include <ulmblas/auxiliary/conjugate.h>
#include <ulmblas/level1extensions/axpyf.h>
#include <ulmblas/level1extensions/dotxf.h>
#include <ulmblas/level2/gemv.h>
#include <ulmblas/level2/trumv.h>
namespace ulmBLAS {
template <typename IndexType, typename TA, typename TX>
void
trumv_unblk(IndexType n,
bool unitDiag,
bool conjA,
const TA *A,
IndexType incRowA,
IndexType incColA,
TX *x,
IndexType incX)
{
for (IndexType i=0; i<n; ++i) {
x[i*incX] = (!unitDiag)
? conjugate(A[i*incRowA+i*incColA], conjA)*x[i*incX]
: x[i*incX];
for (IndexType j=i+1; j<n; ++j) {
x[i*incX] += conjugate(A[i*incRowA+j*incColA], conjA)*x[j*incX];
}
}
}
template <typename IndexType, typename TA, typename TX>
void
trumv(IndexType n,
bool unitDiag,
bool conjA,
const TA *A,
IndexType incRowA,
IndexType incColA,
TX *x,
IndexType incX)
{
typedef decltype(TA(0)*TX(0)) T;
const IndexType UnitStride(1);
if (incRowA==UnitStride) {
const IndexType bf = FuseFactor<T>::axpyf;
const IndexType nb = (n/bf)*bf;
const IndexType nl = n % bf;
for (IndexType j=0; j<nb; j+=bf) {
gemv(j, bf,
T(1), conjA,
&A[0*UnitStride+j*incColA], UnitStride, incColA,
&x[j*incX], incX,
T(1),
&x[0*incX], incX);
trumv_unblk(bf, unitDiag, conjA,
&A[j*UnitStride+j*incColA], UnitStride, incColA,
&x[j*incX], incX);
}
if (nl) {
gemv(n-nl, nl,
T(1), conjA,
&A[0*UnitStride+(n-nl)*incColA], UnitStride, incColA,
&x[(n-nl)*incX], incX,
T(1),
&x[0*incX], incX);
trumv_unblk(nl, unitDiag, conjA,
&A[(n-nl)*UnitStride+(n-nl)*incColA], UnitStride, incColA,
&x[(n-nl)*incX], incX);
}
} else if (incColA==UnitStride) {
const IndexType bf = FuseFactor<T>::dotuxf;
const IndexType nb = (n/bf)*bf;
const IndexType nl = n % bf;
for (IndexType j=0; j<nb; j+=bf) {
trumv_unblk(bf, unitDiag, conjA,
&A[j*incRowA+j*UnitStride], incRowA, UnitStride,
&x[j*incX], incX);
gemv(bf, n-j-bf,
T(1), conjA,
&A[j*incRowA+(j+bf)*incColA], incRowA, UnitStride,
&x[(j+bf)*incX], incX,
T(1),
&x[j*incX], incX);
}
trumv_unblk(nl, unitDiag, conjA,
&A[(n-nl)*incRowA+(n-nl)*UnitStride], incRowA, UnitStride,
&x[(n-nl)*incX], incX);
} else {
trumv_unblk(n, unitDiag, conjA, A, incRowA, incColA, x, incX);
}
}
template <typename IndexType, typename TA, typename TX>
void
trumv(IndexType n,
bool unitDiag,
const TA *A,
IndexType incRowA,
IndexType incColA,
TX *x,
IndexType incX)
{
trumv(n, unitDiag, false, A, incRowA, incColA, x, incX);
}
} // namespace ulmBLAS
#endif // ULMBLAS_LEVEL2_TRUMV_TCC
| 28.737705 | 80 | 0.49401 | sneha0401 |
80b9a2ca90310bfbf6d33372dc0cc1a35696d402 | 8,526 | cxx | C++ | samples/mediafile/mediafile_test.cxx | sverdlin/opalvoip-ptlib | f6e144cba6a94c2978b9a4dbe0df2f5d53bed3be | [
"Beerware"
] | null | null | null | samples/mediafile/mediafile_test.cxx | sverdlin/opalvoip-ptlib | f6e144cba6a94c2978b9a4dbe0df2f5d53bed3be | [
"Beerware"
] | null | null | null | samples/mediafile/mediafile_test.cxx | sverdlin/opalvoip-ptlib | f6e144cba6a94c2978b9a4dbe0df2f5d53bed3be | [
"Beerware"
] | null | null | null | /*
* mediafile_test.cxx
*
* Test program for Media File abstraction.
*
* Portable Tools Library
*
* Copyright (c) 2017 Vox Lucida Pty. Ltd.
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is Portable Tools Library.
*
* The Initial Developer of the Original Code is Vox Lucida Pty. Ltd.
*
*/
#include <ptlib.h>
#include <ptlib/pprocess.h>
#include <ptclib/mediafile.h>
#include <ptclib/dtmf.h>
#include <ptclib/random.h>
class Test : public PProcess
{
PCLASSINFO(Test, PProcess)
public:
void Main();
void DoRead(const PFilePath & filename, bool native);
void DoWrite(const PFilePath & filename, const PStringArray & trackInfo, bool variableFPS);
};
PCREATE_PROCESS(Test)
void Test::Main()
{
cout << "Media File Test Utility" << endl;
PArgList & args = GetArguments();
if (!args.Parse("w-write: Write track\n"
"V-variable-fps. Test with variable frame rate\n"
"n-native. Use native format\n"
PTRACE_ARGLIST)) {
args.Usage(cerr, "[ args ] <media-file> ...");
return;
}
PTRACE_INITIALISE(args);
if (args.HasOption('w')) {
for (PINDEX i = 0; i < args.GetCount(); ++i)
DoWrite(args[i], args.GetOptionString('w').Lines(), args.HasOption('V'));
}
else {
for (PINDEX i = 0; i < args.GetCount(); ++i)
DoRead(args[i], args.HasOption('n'));
}
}
void Test::DoRead(const PFilePath & filename, bool native)
{
PSmartPtr<PMediaFile> file = PMediaFile::Create(filename);
if (file == NULL) {
cerr << "Could not create Media File for " << filename << endl;
return;
}
if (!file->OpenForReading(filename)) {
cerr << "Could not open " << filename << endl;
return;
}
PMediaFile::TracksInfo tracks;
if (!file->GetTracks(tracks)) {
cerr << "Could not get tracks for " << filename << endl;
return;
}
std::set<unsigned> activeTracks;
for (size_t i = 0; i < tracks.size(); ++i) {
const PMediaFile::TrackInfo & track = tracks[i];
cout << "Track " << i << ' ' << track.m_type << ' ' << track.m_format << "\n"
" size=" << track.m_size << " bytes\n"
" rate=" << track.m_rate << "\n"
" frames=" << track.m_frames << " frames\n"
" duration=" << PTimeInterval::Seconds(track.m_frames/track.m_rate) << "\n"
" channels=" << track.m_channels << "\n"
" resolution=" << track.m_width << 'x' << track.m_height << "\n"
<< track.m_options
<< endl;
activeTracks.insert(i);
}
if (native) {
for (size_t i = 0; i < tracks.size(); ++i) {
if (activeTracks.find(i) == activeTracks.end())
continue;
const PMediaFile::TrackInfo & track = tracks[i];
PBYTEArray buffer(std::max(100000U, track.m_size));
PINDEX size = buffer.GetSize();
unsigned frames = buffer.GetSize() / track.m_size;
if (file->ReadNative(i, buffer.GetPointer(), size, frames))
cout << "Read " << frames << " native frames, " << size << " bytes, from track " << i << endl;
else
activeTracks.erase(i);
}
return;
}
PTimeInterval audioOutputTime, videoOutputTime;
while (!activeTracks.empty()) {
for (size_t i = 0; i < tracks.size(); ++i) {
if (activeTracks.find(i) == activeTracks.end())
continue;
const PMediaFile::TrackInfo & track = tracks[i];
if (track.m_type == PMediaFile::Audio()) {
PShortArray buffer((PINDEX)(track.m_rate*track.m_channels)); // One second
while (audioOutputTime <= videoOutputTime) {
PINDEX length;
if (file->ReadAudio(i, buffer.GetPointer(), buffer.GetSize()*2, length)) {
cout << "Read " << length << " bytes of PCM" << endl;
audioOutputTime += PTimeInterval::Seconds(length/track.m_rate/2);
}
else {
activeTracks.erase(i);
audioOutputTime = PMaxTimeInterval;
break;
}
}
}
else if (track.m_type == PMediaFile::Video()) {
PBYTEArray buffer(track.m_width*track.m_height * 3 / 2);
while (videoOutputTime <= audioOutputTime) {
if (file->ReadVideo(i, buffer.GetPointer())) {
cout << "Read frame of YUV" << endl;
videoOutputTime += PTimeInterval::Frequency(track.m_rate);
}
else {
activeTracks.erase(i);
videoOutputTime = PMaxTimeInterval;
break;
}
}
}
else {
cout << "Track " << i << " (" << track.m_type << ") be read in native mode" << endl;
activeTracks.erase(i);
}
}
}
}
void Test::DoWrite(const PFilePath & filename, const PStringArray & trackInfo, bool variableFPS)
{
PSmartPtr<PMediaFile> file = PMediaFile::Create(filename);
if (file == NULL) {
cerr << "Could not create Media File for " << filename << endl;
return;
}
if (!file->OpenForWriting(filename)) {
cerr << "Could not open " << filename << endl;
return;
}
unsigned audioTrack = UINT_MAX, videoTrack = UINT_MAX;
PMediaFile::TracksInfo tracks(trackInfo.size());
for (PINDEX i = 0; i < trackInfo.GetSize(); ++i) {
PStringArray params = trackInfo[i].Tokenise(',');
if (params.size() == 1) {
if (!file->GetDefaultTrackInfo(params[0], tracks[i])) {
cerr << "Could not set get default " << params[0] << " track info for " << filename << endl;
return;
}
if (tracks[i].m_type == PMediaFile::Audio())
audioTrack = i;
else if (tracks[i].m_type == PMediaFile::Video())
videoTrack = i;
}
else {
tracks[i].m_type = params[0];
if (tracks[i].m_type == PMediaFile::Audio()) {
tracks[i].m_format = params[1];
tracks[i].m_rate = params[2].AsReal();
tracks[i].m_channels = params[3].AsUnsigned();
audioTrack = i;
}
else if (tracks[i].m_type == PMediaFile::Video()) {
tracks[i].m_format = params[1];
tracks[i].m_width = params[2].AsUnsigned();
tracks[i].m_height = params[3].AsUnsigned();
tracks[i].m_rate = params[4].AsReal();
videoTrack = i;
}
}
}
if (!file->SetTracks(tracks)) {
cerr << "Could not set tracks for " << filename << endl;
return;
}
if (audioTrack < tracks.size()) {
if (!file->ConfigureAudio(audioTrack, 1, 8000))
return;
#if P_DTMF
PTones tones("C:0.2/D:0.2/E:0.2/F:0.2/G:0.2/A:0.2/B:0.2/C5:0.2/"
"C5:0.2/B:0.2/A:0.2/G:0.2/F:0.2/E:0.2/D:0.2/C:2.0");
unsigned samplesPerBuffer = 320;
unsigned totalBuffers = (tones.GetSize()+samplesPerBuffer-1)/samplesPerBuffer;
for (unsigned i = 0; i < totalBuffers; ++i) {
PINDEX written;
if (!file->WriteAudio(audioTrack, tones.GetPointer() + i * samplesPerBuffer, samplesPerBuffer*2, written))
return;
}
#else
PBYTEArray silence(16000); // One second
PINDEX written;
file->WriteAudio(0, silence, silence.GetSize(), written);
#endif
}
if (videoTrack < tracks.size()) {
PAutoPtr<PVideoInputDevice> fake(PVideoInputDevice::CreateOpenedDevice(P_FAKE_VIDEO_BOUNCING_BOXES));
if (fake.get() == NULL)
return;
fake->SetFrameSize(tracks[videoTrack].m_width, tracks[videoTrack].m_height);
fake->SetFrameRate((unsigned)tracks[videoTrack].m_rate);
if (!file->ConfigureVideo(videoTrack, *fake))
return;
PBYTEArray frame(fake->GetMaxFrameBytes());
if (variableFPS) {
PTimeInterval ts;
PTimeInterval rate = PTimeInterval::Frequency(fake->GetFrameRate());
for (unsigned i = 0; i < fake->GetFrameRate() * 5; i++) {
fake->GetFrameDataNoDelay(frame.GetPointer());
if (PRandom::Number(2) == 0)
file->WriteVideo(videoTrack, frame, ts);
ts += rate;
}
}
else {
for (unsigned i = 0; i < fake->GetFrameRate() * 5; i++) {
fake->GetFrameDataNoDelay(frame.GetPointer());
file->WriteVideo(videoTrack, frame);
}
}
}
}
// End of file
| 31.116788 | 114 | 0.59125 | sverdlin |
80bb38c2890cc4e280f37b961fcae164c0f453d6 | 8,013 | cpp | C++ | azureeyemodule/app/model/objectdetector.cpp | RuinedStar/azure-percept-advanced-development | 17fb87aec364bcedbbe4dd6feb411065b8f160bb | [
"MIT"
] | null | null | null | azureeyemodule/app/model/objectdetector.cpp | RuinedStar/azure-percept-advanced-development | 17fb87aec364bcedbbe4dd6feb411065b8f160bb | [
"MIT"
] | null | null | null | azureeyemodule/app/model/objectdetector.cpp | RuinedStar/azure-percept-advanced-development | 17fb87aec364bcedbbe4dd6feb411065b8f160bb | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
// Standard library includes
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>
// Third party includes
#include <opencv2/gapi/mx.hpp>
#include <opencv2/gapi/core.hpp>
#include <opencv2/gapi/infer.hpp>
#include <opencv2/gapi/streaming/desync.hpp>
#include <opencv2/highgui.hpp>
// Local includes
#include "objectdetector.hpp"
#include "../iot/iot_interface.hpp"
#include "../streaming/rtsp.hpp"
#include "../util/helper.hpp"
#include "../util/labels.hpp"
namespace model {
ObjectDetector::ObjectDetector(const std::string &labelfpath, const std::vector<std::string> &modelfpaths, const std::string &mvcmd, const std::string &videofile, const cv::gapi::mx::Camera::Mode &resolution)
: AzureEyeModel{ modelfpaths, mvcmd, videofile, resolution }, labelfpath(labelfpath), class_labels({})
{
}
ObjectDetector::~ObjectDetector()
{
}
void ObjectDetector::handle_bgr_output(cv::optional<cv::Mat> &out_bgr, cv::Mat &last_bgr, const std::vector<cv::Rect> &last_boxes,
const std::vector<int> &last_labels, const std::vector<float> &last_confidences)
{
// BGR output: visualize and optionally display
if (!out_bgr.has_value())
{
return;
}
last_bgr = *out_bgr;
cv::Mat original_bgr;
last_bgr.copyTo(original_bgr);
rtsp::update_data_raw(last_bgr);
preview(last_bgr, last_boxes, last_labels, last_confidences);
if (this->status_msg.empty())
{
rtsp::update_data_result(last_bgr);
}
else
{
cv::Mat bgr_with_status;
last_bgr.copyTo(bgr_with_status);
util::put_text(bgr_with_status, this->status_msg);
rtsp::update_data_result(bgr_with_status);
}
// Maybe save and export the retraining data at this point
this->save_retraining_data(original_bgr, last_confidences);
}
void ObjectDetector::preview(const cv::Mat& rgb, const std::vector<cv::Rect>& boxes, const std::vector<int>& labels, const std::vector<float>& confidences) const
{
for (std::size_t i = 0; i < boxes.size(); i++)
{
// color of a label
int index = labels[i] % label::colors().size();
cv::rectangle(rgb, boxes[i], label::colors().at(index), 2);
cv::putText(rgb,
util::get_label(labels[i], this->class_labels) + ": " + util::to_string_with_precision(confidences[i], 2),
boxes[i].tl() + cv::Point(3, 20),
cv::FONT_HERSHEY_SIMPLEX,
0.7,
cv::Scalar(label::colors().at(index)),
2);
}
}
void ObjectDetector::handle_inference_output(const cv::optional<cv::Mat> &out_bgr, const cv::optional<int64_t> &out_nn_ts, const cv::optional<int64_t> &out_nn_seqno,
const cv::optional<std::vector<cv::Rect>> &out_boxes, const cv::optional<std::vector<int>> &out_labels,
const cv::optional<std::vector<float>> &out_confidences, const cv::optional<cv::Size> &out_size, std::vector<cv::Rect> &last_boxes, std::vector<int> &last_labels,
std::vector<float> &last_confidences)
{
if (!out_nn_ts.has_value())
{
return;
}
// The below objects are on the same desynchronized path
// and are coming together
CV_Assert(out_nn_ts.has_value());
CV_Assert(out_nn_seqno.has_value());
CV_Assert(out_boxes.has_value());
CV_Assert(out_labels.has_value());
CV_Assert(out_confidences.has_value());
CV_Assert(out_size.has_value());
// Compose a message for each item we detected
// Each object adheres to the following schema
//
// {
// "bbox": list of the form [float, float, float, float]. This is an object's bounding box (x0, y0, x1, y1),
// "label": string. Class label of the detected object,
// "confidence": float. Confidence of the network,
// "timestamp": int. Timestamp for this detection.
// }
std::vector<std::string> messages;
for (std::size_t i = 0; i < out_labels->size(); i++)
{
// Bounding box is in (x, y, w, h), normalized coordinates.
cv::Rect rect = out_boxes.value()[i];
// Convert to (x, y, w, h) absolute pixel coordinates.
cv::Rect2f rect_abs(static_cast<float>(rect.x) / out_size->width, static_cast<float>(rect.y) / out_size->height, static_cast<float>(rect.width) / out_size->width, static_cast<float>(rect.height) / out_size->height);
// Convert bounding box to string of form (x0, y0, x1, y1) coordinates.
std::stringstream bboxstr;
auto x0 = rect_abs.x;
auto y0 = rect_abs.y;
auto x1 = rect_abs.x + rect_abs.width;
auto y1 = rect_abs.y + rect_abs.height;
bboxstr << std::fixed << std::setprecision(3) << "\"bbox\": [" << x0 << ", " << y0 << ", " << x1 << ", " << y1 << "]";
// Get the label
auto label = util::get_label(out_labels.value()[i], this->class_labels);
auto confidence = std::to_string(out_confidences.value()[i]);
auto timestamp = std::to_string(*out_nn_ts);
std::string str = std::string("{");
str.append(bboxstr.str()).append(",")
.append("\"label\": \"").append(label).append("\", ")
.append("\"confidence\": \"").append(confidence).append("\", ")
.append("\"timestamp\": \"").append(timestamp).append("\"")
.append("}");
messages.push_back(str);
}
// Compose a single string out of all the detection messages
std::string str = std::string("[");
for (size_t i = 0; i < messages.size(); i++)
{
if (i > 0)
{
str.append(", ");
}
str.append(messages[i]);
}
str.append("]");
this->log_inference("nn: seqno=" + std::to_string(*out_nn_seqno) + ", ts=" + std::to_string(*out_nn_ts) + ", " + str);
// Send out the detection message to anyone who's listening (this will add curly braces around the inference message)
iot::msgs::send_message(iot::msgs::MsgChannel::NEURAL_NETWORK, str);
// Update our cache of items now that we have new ones
last_boxes = std::move(*out_boxes);
last_labels = std::move(*out_labels);
last_confidences = std::move(*out_confidences);
}
bool ObjectDetector::pull_data(cv::GStreamingCompiled &pipeline)
{
cv::optional<cv::Mat> out_bgr;
cv::optional<std::vector<uint8_t>> out_h264;
cv::optional<int64_t> out_h264_seqno;
cv::optional<int64_t> out_h264_ts;
cv::optional<cv::Mat> out_nn;
cv::optional<int64_t> out_nn_ts;
cv::optional<int64_t> out_nn_seqno;
cv::optional<std::vector<cv::Rect>> out_boxes;
cv::optional<std::vector<int>> out_labels;
cv::optional<std::vector<float>> out_confidences;
cv::optional<cv::Size> out_size;
std::vector<cv::Rect> last_boxes;
std::vector<int> last_labels;
std::vector<float> last_confidences;
cv::Mat last_bgr;
std::ofstream ofs;
if (!this->videofile.empty())
{
ofs.open(this->videofile, std::ofstream::out | std::ofstream::binary | std::ofstream::trunc);
}
// Pull the data from the pipeline while it is running
while (pipeline.pull(cv::gout(out_h264, out_h264_seqno, out_h264_ts, out_bgr, out_nn_seqno, out_nn_ts, out_boxes, out_labels, out_confidences, out_size)))
{
this->handle_h264_output(out_h264, out_h264_ts, out_h264_seqno, ofs);
this->handle_inference_output(out_bgr, out_nn_ts, out_nn_seqno, out_boxes, out_labels, out_confidences, out_size, last_boxes, last_labels, last_confidences);
this->handle_bgr_output(out_bgr, last_bgr, last_boxes, last_labels, last_confidences);
if (this->restarting)
{
// We've been interrupted
this->cleanup(pipeline, last_bgr);
return false;
}
}
// Ran out of frames
return true;
}
} // namespace model
| 36.756881 | 223 | 0.631349 | RuinedStar |
01ec24b338070ce553200393ad77e442335dbd6b | 6,283 | cpp | C++ | tests/rayleightiming.cpp | maexlich/opencurrent | a51c5a8105563d2f7e260ee7debf79bda2c2dcf0 | [
"Apache-2.0"
] | 4 | 2016-11-16T15:29:31.000Z | 2018-03-27T03:29:14.000Z | tests/rayleightiming.cpp | laosunhust/FluidSolver | d0c7fa235853863efdf44b742c70cf6673c8cf9e | [
"Apache-2.0"
] | 1 | 2020-01-26T12:29:00.000Z | 2020-01-26T13:56:20.000Z | tests/rayleightiming.cpp | laosunhust/FluidSolver | d0c7fa235853863efdf44b742c70cf6673c8cf9e | [
"Apache-2.0"
] | 1 | 2018-02-14T16:13:13.000Z | 2018-02-14T16:13:13.000Z | /*
* Copyright 2008-2009 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cmath>
#include "tests/testframework.h"
#include "ocuequation/eqn_incompressns3d.h"
#include "ocustorage/grid3d.h"
#include "ocuutil/imagefile.h"
#include "ocuutil/color.h"
#include "ocuutil/timing_pool.h"
using namespace ocu;
DECLARE_UNITTEST_DOUBLE_BEGIN(RayleighTimingTest);
double rand_val(double min_val, double max_val) {
return min_val + 2 * max_val * ((double)rand())/RAND_MAX;
}
void write_slice(const char *filename, const Grid3DDevice<double> &grid)
{
Grid3DHost<double> h_grid;
h_grid.init_congruent(grid);
h_grid.copy_all_data(grid);
int nx = grid.nx();
int ny = grid.ny();
int nz = grid.nz();
ImageFile img;
img.allocate(nx, ny);
for (int i=0; i < nx; i++)
for (int j=0; j < ny; j++) {
double temperature = h_grid.at(i,j,nz/2);
if (temperature < -2) temperature = -2;
if (temperature > 2) temperature = 2;
//float3 color = make_float3(temperature, temperature, temperature);
float3 color = hsv_to_rgb(make_float3((temperature)*360, 1, 1));
//float3 color = pseudo_temperature((temperature+1)*.5);
img.set_rgb(i,j,(unsigned char)(255*color.x),(unsigned char)(255*color.y),(unsigned char)(255*color.z));
}
img.write_ppm(filename);
}
void init_params(Eqn_IncompressibleNS3DParamsD ¶ms, int res, double Ra, double Pr) {
int nx = res;
int ny = res/2;
int nz = res;
double domain_x = 2.0;
double domain_y = 1.0;
double domain_z = 2.0;
double hx = domain_x/nx;
double hy = domain_y/ny;
double hz = domain_z/nz;
params.init_grids(nx, ny, nz, false);
params.hx = hx;
params.hy = hy;
params.hz = hz;
params.max_divergence = 1e-6;
// if everything is set to one, Ra = deltaT
params.viscosity = Pr;
params.thermal_diffusion = 1;
params.gravity = -1;
params.bouyancy = Ra * Pr;
params.vertical_direction = DIR_YPOS;
params.advection_scheme = IT_SECOND_ORDER_CENTERED;
params.time_step = TS_ADAMS_BASHFORD2;
params.cfl_factor = .7;
BoundaryCondition dirichelet;
dirichelet.type = BC_DIRICHELET;
BoundaryCondition closed;
closed.aux_value = 1; // no slip on bottom & top
closed.type = BC_FORCED_INFLOW_VARIABLE_SLIP; // closed & no slip on all sides
BoundaryCondition periodic;
periodic.type = BC_PERIODIC;
params.flow_bc = BoundaryConditionSet(periodic);
params.temp_bc = BoundaryConditionSet(periodic);
params.flow_bc.ypos = closed;
params.flow_bc.yneg = closed;
params.temp_bc.ypos = dirichelet;
params.temp_bc.yneg = dirichelet;
params.temp_bc.yneg.value = 1;
int i,j,k;
for (int i=0; i < nx; i++) {
for (int j=0; j < ny; j++) {
for (int k=0; k < nz; k++) {
double y = 1 - (((j+.5) * hy) / domain_y);
params.init_temp.at(i,j,k) = y + rand_val(-1e-2, 1e-2);
params.init_u.at(i,j,k) = rand_val(-1e-2, 1e-2);
params.init_v.at(i,j,k) = rand_val(-1e-2, 1e-2);
params.init_w.at(i,j,k) = rand_val(-1e-2, 1e-2);
}
}
}
}
void run_resolution(int res, double dt, double t1, double Ra, double Pr, bool do_diagnostic=true) {
Eqn_IncompressibleNS3DParamsD params;
Eqn_IncompressibleNS3DD eqn;
init_params(params, res, Ra, Pr);
UNITTEST_ASSERT_TRUE(eqn.set_parameters(params));
int next_frame = 1;
CPUTimer clock;
CPUTimer step_clock;
int step_count;
int start_count=0;
start_count = eqn.num_steps;
clock.start();
global_timer_clear_all();
step_count = eqn.num_steps;
step_clock.start();
set_forge_ahead(true);
for (double t = 0; t <= t1; t += dt) {
UNITTEST_ASSERT_TRUE(eqn.advance_one_step(dt));
if (do_diagnostic) {
double max_u, max_v, max_w;
eqn.get_u().reduce_maxabs(max_u);
eqn.get_v().reduce_maxabs(max_v);
eqn.get_w().reduce_maxabs(max_w); // not used in any calculations, but useful for troubleshooting
printf("> Max u = %.12f, Max v = %.12f, Max w = %.12f\n", max_u, max_v, max_w);
fflush(stdout);
if (t > next_frame * t1/100) {
char buff[1024];
sprintf(buff, "output.%04d.ppm", next_frame);
printf("%s\n", buff);
write_slice(buff, eqn.get_temperature());
next_frame++;
}
}
else {
if (t > next_frame * t1/100) {
step_clock.stop();
printf("ms/step = %f\n", step_clock.elapsed_ms() / (eqn.num_steps - step_count));
char buff[1024];
sprintf(buff, "output.%04d.ppm", next_frame);
global_counter_print();
global_counter_clear_all();
printf("%s\n", buff);
write_slice(buff, eqn.get_temperature());
next_frame++;
step_count = eqn.num_steps;
step_clock.start();
}
printf("%.4f%% done\r", t/t1 * 100);
}
}
clock.stop();
printf("Elapsed sec: %.8f\n", clock.elapsed_sec());
printf("ms/step = %f\n", clock.elapsed_ms() / (eqn.num_steps - start_count));
printf("\n............ DONE ...............\n\n");
}
void run() {
// run_resolution(256, 1.25e-6, .01, 1e7, 0.71, false);
// run_resolution(128, 2 * 1.25e-6, .01, 1e7, 0.71, false);
// run_resolution(64, 4 * 1.25e-6, .01, 1e7, 0.71, false);
// run_resolution(384, 7.5e-7, .01, 1e7, 0.71, false);
// run_resolution(256, 1.25e-6/4, .001, 1e8, 0.71, false);
run_resolution(384, 7.5e-7/2, .005, 1e8, 0.71, false);
//run_resolution(24, 7.5e-7/2, .005, 1e8, 0.71, false);
global_timer_print();
global_counter_print();
}
DECLARE_UNITTEST_DOUBLE_END(RayleighTimingTest);
| 29.087963 | 111 | 0.627885 | maexlich |
01f5c8d74eeabedd1e6a54408569cd7c1c5607b2 | 1,648 | cpp | C++ | TorentMakerConsoleApplication/Window/SimpleDxWindow.cpp | sssr33/TorrentMaker | 75dc4b7b45c3c277342470f705e4a35264f942f7 | [
"MIT"
] | null | null | null | TorentMakerConsoleApplication/Window/SimpleDxWindow.cpp | sssr33/TorrentMaker | 75dc4b7b45c3c277342470f705e4a35264f942f7 | [
"MIT"
] | null | null | null | TorentMakerConsoleApplication/Window/SimpleDxWindow.cpp | sssr33/TorrentMaker | 75dc4b7b45c3c277342470f705e4a35264f942f7 | [
"MIT"
] | null | null | null | #include "SimpleDxWindow.h"
//SimpleDxWindow::RenderScope::RenderScope(SimpleDxWindow *window, RenderTargetState<1> &&state)
// : window(window), state(std::move(state)) {
//}
//
//SimpleDxWindow::RenderScope::RenderScope(RenderScope &&other)
// : window(std::move(other.window)), state(std::move(other.state))
//{
// other.window = nullptr;
//}
//
//SimpleDxWindow::RenderScope::~RenderScope() {
// if (this->window) {
// this->window->Present();
// }
//}
//
//SimpleDxWindow::RenderScope &SimpleDxWindow::RenderScope::operator=(RenderScope &&other) {
// if (this != &other) {
// this->window = std::move(other.window);
// this->state = std::move(other.state);
//
// other.window = nullptr;
// }
//
// return *this;
//}
//
//
//
//
//SimpleDxWindow::SimpleDxWindow(DxDevice &dxDev)
// : DxWindow(dxDev)
//{
// //this->Show();
//}
//
//SimpleDxWindow::~SimpleDxWindow() {
//}
//
//void SimpleDxWindow::SetOnSizeChanged(std::function<void(const DirectX::XMUINT2 &newSize)> v) {
// this->onSizeChanged = v;
//
// if (this->onSizeChanged) {
// // call event handler to update dependent resources thus making it valid.
// this->onSizeChanged(this->GetOutputSize());
// }
//}
//
//SimpleDxWindow::RenderScope SimpleDxWindow::Begin(ID3D11DeviceContext *d3dCtx, const float color[4]) {
// this->ProcessMessages();
// this->Clear(d3dCtx, DirectX::Colors::CornflowerBlue);
// auto state = this->SetToContext(d3dCtx);
//
// return SimpleDxWindow::RenderScope(this, std::move(state));
//}
//
//void SimpleDxWindow::CreateSizeDependentResources(const DirectX::XMUINT2 &newSize) {
// if (this->onSizeChanged) {
// this->onSizeChanged(newSize);
// }
//} | 26.15873 | 104 | 0.675364 | sssr33 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.