hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
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
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
536f3880b91e5bbffba0069225e1094037533f00
169,421
cxx
C++
inetcore/mshtml/src/site/text/rclclptr.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/mshtml/src/site/text/rclclptr.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/mshtml/src/site/text/rclclptr.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------ // // Class: CRecalcLinePtr implementation // // Synopsis: Special line pointer. Encapsulate the use of a temporary // line array when building lines. This pointer automatically // switches between the main and the temporary new line array // depending on the line index. // //------------------------------------------------------------------------- #include "headers.hxx" #pragma MARK_DATA(__FILE__) #pragma MARK_CODE(__FILE__) #pragma MARK_CONST(__FILE__) #ifndef X__DISP_H_ #define X__DISP_H_ #include "_disp.h" #endif #ifndef X_LSM_HXX_ #define X_LSM_HXX_ #include "lsm.hxx" #endif #ifndef X_TREEPOS_HXX_ #define X_TREEPOS_HXX_ #include "treepos.hxx" #endif #ifndef X_TASKMAN_HXX_ #define X_TASKMAN_HXX_ #include "taskman.hxx" #endif #ifndef X_MARQUEE_HXX_ #define X_MARQUEE_HXX_ #include "marquee.hxx" #endif #ifndef X_RCLCLPTR_HXX_ #define X_RCLCLPTR_HXX_ #include "rclclptr.hxx" #endif MtDefine(CRecalcLinePtr, Layout, "CRecalcLinePtr") MtDefine(CRecalcLinePtr_aryLeftAlignedImgs_pv, CRecalcLinePtr, "CRecalcLinePtr::_aryLeftAlignedImgs::_pv") MtDefine(CRecalcLinePtr_aryRightAlignedImgs_pv, CRecalcLinePtr, "CRecalcLinePtr::_arRightAlignedImgs::_pv") #pragma warning(disable:4706) /* assignment within conditional expression */ //+------------------------------------------------------------------------ // // Member: CRecalcLinePtr::CRecalcLinePtr // // Synopsis: constructor, initializes (caches) margins for the current // display // //------------------------------------------------------------------------- CRecalcLinePtr::CRecalcLinePtr(CDisplay *pdp, CCalcInfo *pci) : _aryLeftAlignedImgs(Mt(CRecalcLinePtr_aryLeftAlignedImgs_pv)), _aryRightAlignedImgs(Mt(CRecalcLinePtr_aryRightAlignedImgs_pv)) { CFlowLayout * pFlowLayout = pdp->GetFlowLayout(); CElement * pElementFL = pFlowLayout->ElementContent(); long lPadding[SIDE_MAX]; WHEN_DBG( _cAll = -1; ) _pdp = pdp; _pci = pci; _iPF = -1; _fInnerPF = FALSE; _xLeft = _xRight = _yBordTop = _xBordLeft = _xBordRight = _yBordBottom = 0; _xPadLeft = _yPadTop = _xPadRight = _yPadBottom = 0; // I am not zeroing out the following because it is not necessary. We zero it out // everytime we call CalcBeforeSpace // _yBordLeftPerLine = _xBordRightPerLine = _xPadLeftPerLine = _xPadRightPerLine = 0; ResetPosAndNegSpace(); _cLeftAlignedLayouts = _cRightAlignedLayouts = 0; _fIsEditable = pFlowLayout->IsEditable(); if ( pElementFL->Tag() == ETAG_MARQUEE && !_fIsEditable && !pElementFL->IsPrintMedia()) { _xMarqueeWidth = DYNCAST(CMarquee, pElementFL)->_lXMargin; } else { _xMarqueeWidth = 0; } _pdp->GetPadding(pci, lPadding, pci->_smMode == SIZEMODE_MMWIDTH); _xLayoutLeftIndent = lPadding[SIDE_LEFT]; _xLayoutRightIndent = lPadding[SIDE_RIGHT]; _fNoMarginAtBottom = FALSE; _ptpStartForListItem = NULL; _fMoveBulletToNextLine = FALSE; } //+------------------------------------------------------------------------ // // Member: CRecalcLinePtr::Init // // Synopsis: Initialize the old and new line array and reset the // RecalcLineptr. // //------------------------------------------------------------------------- void CRecalcLinePtr::Init(CLineArray * prgliOld, int iNewFirst, CLineArray * prgliNew) { _prgliOld = prgliOld; _prgliNew = prgliNew; _xMaxRightAlign = 0; Reset(iNewFirst); } //+------------------------------------------------------------------------ // // Member: CRecalcLinePtr::Reset // // Synopsis: Resets the RecalcLinePtr to use the given offset. Look // for all references to line >= iNewFirst to be looked up in the // new line array else in the old line array. // //------------------------------------------------------------------------- void CRecalcLinePtr::Reset(int iNewFirst) { _iNewFirst = iNewFirst; _iLine = 0; _iNewPast = _prgliNew ? _iNewFirst + _prgliNew->Count() : 0; _cAll = _prgliNew ? _iNewPast : _prgliOld->Count(); Assert(_iNewPast <= _cAll); } //+------------------------------------------------------------------------ // // Member: CRecalcLinePtr::operator // // Synopsis: returns the line from the old or the new line array based // on _iNewFirst. // //------------------------------------------------------------------------- CLineCore * CRecalcLinePtr::operator [] (int iLine) { Assert(iLine < _cAll); if (iLine >= _iNewFirst && iLine < _iNewPast) { return _prgliNew->Elem(iLine - _iNewFirst); } else { return _prgliOld->Elem(iLine); } } //+------------------------------------------------------------------------ // // Member: CRecalcLinePtr::AddLine // // Synopsis: Add's a new line at the end of the new line array. // //------------------------------------------------------------------------- CLineCore * CRecalcLinePtr::AddLine() { CLineCore * pLine = _prgliNew ? _prgliNew->Add(1, NULL): _prgliOld->Add(1, NULL); if(pLine) { Reset(_iNewFirst); // Update _cAll, _iNewPast, etc. to reflect // the correct state after adding line pLine->_iLOI = -1; // to prevent this index to have value 0 (valid cache index) } return pLine; } //+------------------------------------------------------------------------ // // Member: CRecalcLinePtr::InsertLine // // Synopsis: Inserts a line to the old or new line array before the given // line. // //------------------------------------------------------------------------- CLineCore * CRecalcLinePtr::InsertLine(int iLine) { CLineCore * pLine = _prgliNew ? _prgliNew->Insert(iLine - _iNewFirst, 1): _prgliOld->Insert(iLine, 1); if(pLine) { Reset(_iNewFirst); // Update _cAll, _iNewPast, etc. to reflect // the correct state after the newly inserted line pLine->_iLOI = -1; // to prevent this index to have value 0 (valid cache index) } return pLine; } //+------------------------------------------------------------------------ // // Member: CRecalcLinePtr::First // // Synopsis: Sets the iLine to be the current line and returns it // // Returns: returns iLine'th line if there is one. // //------------------------------------------------------------------------- CLineCore * CRecalcLinePtr::First(int iLine) { _iLine = iLine; if (_iLine < _cAll) return (*this)[_iLine]; else return NULL; } //+------------------------------------------------------------------------ // // Member: CRecalcLinePtr::Next // // Synopsis: Moves the current line to the next line, if there is one // // Returns: returns the next line if there is one. // //------------------------------------------------------------------------- CLineCore * CRecalcLinePtr::Next() { if (_iLine + 1 < _cAll) return (*this)[++_iLine]; else return NULL; } //+------------------------------------------------------------------------ // // Member: CRecalcLinePtr::Prev // // Synopsis: Moves the current line to the previous line, if there is one // // Returns: returns the previous line if there is one. // //------------------------------------------------------------------------- CLineCore * CRecalcLinePtr::Prev() { if (_iLine > 0) return (*this)[--_iLine]; else return NULL; } //+---------------------------------------------------------------------------- // // Member: CRecalcLinePtr::InitPrevAfter () // // Synopsis: Initializes the after spacing of the previous line's paragraph // //----------------------------------------------------------------------------- void CRecalcLinePtr::InitPrevAfter(BOOL *pfLastWasBreak, CLinePtr& rpOld) { int oldLine; *pfLastWasBreak = FALSE; // Now initialize the linebreak stuff. oldLine = rpOld; if (rpOld.PrevLine(TRUE, FALSE)) { // If we encounter a break in the previous line, then we // need to remember that for the accumulation to work. if (rpOld->_fHasBreak) { *pfLastWasBreak = TRUE; } } rpOld = oldLine; } //+------------------------------------------------------------------------ // // Member: ApplyLineIndents // // Synopsis: Apply left and right indents for the current line. // //------------------------------------------------------------------------- void CRecalcLinePtr::ApplyLineIndents( CTreeNode * pNode, CLineFull * pLineMeasured, UINT uiFlags, BOOL fPseudoElementEnabled) { LONG xLeft; // Use logical units LONG xRight; // Use logical units long iPF; const CParaFormat * pPF; CFlowLayout * pFlowLayout = _pdp->GetFlowLayout(); CElement * pElementFL = pFlowLayout->ElementContent(); BOOL fInner = SameScope(pNode, pElementFL); if(!pNode) return; pPF = pNode->GetParaFormat(); iPF = pNode->GetParaFormatIndex(LC_TO_FC(_pci->GetLayoutContext())); BOOL fRTLLine = pPF->HasRTL(TRUE); if ( _iPF != iPF || _fInnerPF != fInner || fPseudoElementEnabled ) { if (!fPseudoElementEnabled) { _iPF = iPF; _fInnerPF = fInner; } LONG xParentWidth = _pci->_sizeParent.cx; if ( pPF->_cuvLeftIndentPercent.GetUnitValue() || pPF->_cuvRightIndentPercent.GetUnitValue() ) { // // (olego, IEv60 31646) CSS1 Strict Mode specific. In this mode _pci->_sizeParent.cx // contains the width of pFlowLayout's parent (in compat mode it is overwritten in // CFlowLayout::CalcTextSize), but pFlowLayout->_sizeProposed is what is expected here. // Since xParentWidth is used only when indent is a percent value, and to minimize // perf impact this code is placed under the if statement, instead of xParentWidth's // initialization. // if ( pElementFL->HasMarkupPtr() && pElementFL->GetMarkupPtr()->IsStrictCSS1Document() ) { xParentWidth = pFlowLayout->_sizeProposed.cx; } xParentWidth = pNode->GetParentWidth(_pci, xParentWidth); } _xLeft = pPF->GetLeftIndent(_pci, fInner, xParentWidth); _xRight = pPF->GetRightIndent(_pci, fInner, xParentWidth); if (_xLeft < 0 || _xRight < 0) _pdp->_fHasNegBlockMargins = TRUE; // If we have horizontal indents in percentages, flag the display // so it can do a full recalc pass when necessary (e.g. parent width changes) // Also see CalcBeforeSpace() where we do this for horizontal padding. if ( (pPF->_cuvLeftIndentPercent.IsNull() ? FALSE : pPF->_cuvLeftIndentPercent.GetUnitValue() ) || (pPF->_cuvRightIndentPercent.IsNull() ? FALSE : pPF->_cuvRightIndentPercent.GetUnitValue() ) ) { _pdp->_fContainsHorzPercentAttr = TRUE; } } xLeft = _xLeft; xRight = _xRight; // (changes in the next section should be reflected in AlignObjects() too) // Adjust xLeft to account for marquees, padding and borders. xLeft += _xMarqueeWidth + _xLayoutLeftIndent; xRight += _xMarqueeWidth + _xLayoutRightIndent; xLeft += _xPadLeft + _xBordLeft; xRight += _xPadRight + _xBordRight; if(!fRTLLine) xLeft += _xLeadAdjust; else xRight += _xLeadAdjust; // xLeft is now the sum of indents, border, padding. CSS requires that when // possible, this indent is shared with the space occupied by floated/ALIGN'ed // elements (our code calls that space "margin"). Thus we want to apply a +ve // xLeft only when it's greater than the margin, and the amount applied excludes // what's occupied by the margin already. (We never want to apply a -ve xLeft) // Same reasoning applies to xRight. // Note that xLeft/xRight has NOT accumulated CSS text-indent values yet; // this is because we _don't_ want that value to be shared the way the above // values have been shared. We'll factor in text-indent after this. if (_marginInfo._xLeftMargin) pLineMeasured->_xLeft = max( 0L, xLeft - _marginInfo._xLeftMargin ); else pLineMeasured->_xLeft = xLeft; if (_marginInfo._xRightMargin) pLineMeasured->_xRight = max( 0L, xRight - _marginInfo._xRightMargin ); else pLineMeasured->_xRight = xRight; // text indent is inherited, so if the formatting node correspond's to a layout, // indent the line only if the layout is not a block element. For layout element's // the have blockness, text inherited and first line of paragraph's inside are // indented. if ( uiFlags & MEASURE_FIRSTINPARA && ( pNode->Element() == pElementFL || !pNode->ShouldHaveLayout(LC_TO_FC(_pci->GetLayoutContext())) || !pNode->Element()->IsBlockElement(LC_TO_FC(_pci->GetLayoutContext()))) ) { if(!fRTLLine) pLineMeasured->_xLeft += pPF->GetTextIndent(_pci); else pLineMeasured->_xRight += pPF->GetTextIndent(_pci); } } //+------------------------------------------------------------------------ // // Member: CalcInterParaSpace // // Synopsis: Calculate space before the current line. // // Arguments: [pMe] -- // [iLineFirst] -- line to start calculating from // [yHeight] -- y coordinate of the top of line // // //------------------------------------------------------------------------- CTreeNode * CRecalcLinePtr::CalcInterParaSpace(CLSMeasurer * pMe, LONG iPrevLine, UINT *puiFlags) { LONG iLine; CLineCore *pPrevLine = NULL; CTreeNode *pNodeFormatting; BOOL fFirstLineInLayout = *puiFlags & MEASURE_FIRSTLINE ? TRUE : FALSE; INSYNC(pMe); // Get the previous line that's on a different physical line // and is not a frame line. Note that the initial value of // iPrevLine IS the line before the one we're about to measure. for (iLine = iPrevLine; iLine >= 0; --iLine) { pPrevLine = (*this)[iLine]; if (pPrevLine->_fForceNewLine && pPrevLine->_cch > 0) break; } //pMe->MeasureSetPF(pPF); //pMe->_pLS->_fInnerPFFirst = SameScope(pMe->CurrBranch(), _pdp->GetFlowLayoutElement()); pNodeFormatting = CalcParagraphSpacing(pMe, fFirstLineInLayout); // If a line consists of only a BR character and a block tag, // fold the previous line height into the before space, too. if (pPrevLine && pPrevLine->_fEatMargin) { // // NOTE(SujalP): When we are eating margin we have to be careful to // take into account both +ve and -ve values for both LineHeight // yBS. The easiest way to envision this is to think both of them // as margins which need to be merged -- which is similar to the // case where we are computing before and after space. Hence the // code here is similar to the code one would seen in CalcBeforeSpace // where we set up up _yPosSpace and _yNegSpace. // // If you have the urge to change this code please make sure you // do not change the behaviour of 38561 and 61132. // LONG yPosSpace; LONG yNegSpace; LONG yBeforeSpace = pMe->_li._yBeforeSpace; yPosSpace = max(0L, pPrevLine->_yHeight); yPosSpace = max(yPosSpace, yBeforeSpace); yNegSpace = min(0L, pPrevLine->_yHeight); yNegSpace = min(yNegSpace, yBeforeSpace); pMe->_li._yBeforeSpace = (yPosSpace + yNegSpace) - pPrevLine->_yHeight; } // // Support for WORD-WRAP attribute // // word wrap should not affect minwidth mode if (pNodeFormatting) { pMe->SetBreakLongLines(pNodeFormatting, puiFlags); } if (pMe->_li._fFirstInPara) { *puiFlags |= MEASURE_FIRSTINPARA; CTreeNode *pNode = pNodeFormatting; if(!pNode) return NULL; if (pNode->GetParaFormat(LC_TO_FC(_pci->GetLayoutContext()))->_fHasPseudoElement) { const CFancyFormat *pFF; pNode = _pdp->GetMarkup()->SearchBranchForBlockElement(pNode, pMe->_pFlowLayout); Assert(pMe->_pFlowLayout->IsElementBlockInContext(pNode->Element())); pFF = pNode->GetFancyFormat(LC_TO_FC(_pci->GetLayoutContext())); BOOL fHasFirstLine = pFF->_fHasFirstLine; BOOL fHasFirstLetter = pFF->_fHasFirstLetter; if ( fHasFirstLetter && pNode->ShouldHaveLayout() && !SameScope(pNode, pMe->_pFlowLayout->ElementOwner()) ) { fHasFirstLetter = FALSE; } if (fHasFirstLine || fHasFirstLetter) { BOOL fFirstLetterFound = FALSE; pMe->_cpStopFirstLetter = fHasFirstLetter ? pMe->GetCpOfLastLetter(pNode) : -1; if (pMe->_cpStopFirstLetter < pMe->GetCp()) { fHasFirstLetter = FALSE; pMe->_cpStopFirstLetter = -1; } if (fHasFirstLine) { LONG cchFirstLetter = 0; if (iPrevLine >= 0) { CLineCore *pPrevLine = (*this)[iPrevLine]; CLineOtherInfo *ploi = pPrevLine ? pPrevLine->oi() : NULL; if ( ploi && ploi->_fHasFirstLine && ploi->_fHasFirstLetter && pPrevLine->IsFrame() && !pPrevLine->_fFrameBeforeText && SameScope(ploi->_pNodeForFirstLetter, pNode) ) { cchFirstLetter = ploi->_cchFirstLetter; } } // If this block element (ElemA) begins _BEFORE_ this line, it means // that we have a nested block element (ElemB) inside ElemA and // hence this line is not really the first line in ElemA. // Note: the pMe->_li._cch stores the count of the prechars -- it has // yet to be transferred over to _cchPreChars, which unfortunately // happens after this function. if (pNode->Element()->GetFirstCp() + cchFirstLetter >= (pMe->GetCp() - pMe->_li._cch)) { pMe->_li._fHasFirstLine = TRUE; pMe->PseudoLineEnable(pNode); } } if (fHasFirstLetter) { // Walk back over here to pay attention to the "float" line // which contains the first letter. If you find it, then do // no turn on this bit, else do so. iLine = iPrevLine; while (iLine >= 0) { pPrevLine = (*this)[iLine]; if (pPrevLine->_fForceNewLine && !pPrevLine->IsClear()) break; if ( pPrevLine->IsFrame() && pPrevLine->oi()->_fHasFloatedFL && SameScope(pPrevLine->oi()->_pNodeForFirstLetter, pNode) ) { fFirstLetterFound = TRUE; break; } iLine--; } if ( !fFirstLetterFound && pMe->_cpStopFirstLetter >= 0 ) { pMe->PseudoLetterEnable(pNode); Assert(pMe->_fPseudoLetterEnabled); pMe->_li._fHasFirstLetter = TRUE; } } if ( pMe->_li._fHasFirstLine || pMe->_li._fHasFirstLetter ) { pFF = pNode->GetFancyFormat(LC_TO_FC(_pci->GetLayoutContext())); // If we did not get the clear attribute from the pseudo element // then there is no point in clearing here since it would already // have been cleared. // If we have found the first letter, it means that clearing has // already happened. We do not want to clear the aligned line for // the first letter, now do we? if ( pFF->_fClearFromPseudo && !fFirstLetterFound ) { _marginInfo._fClearLeft |= pFF->_fClearLeft; _marginInfo._fClearRight |= pFF->_fClearRight; } if (fFirstLetterFound) { _marginInfo._fClearLeft = FALSE; _marginInfo._fClearRight = FALSE; } } } } } INSYNC(pMe); return pNodeFormatting; } /* * CRecalcLinePtr::NetscapeBottomMargin(pMe, pDI) * * This function is called for the last line in the display. * It exists because Netscape displays by streaming tags and it * increases the height of a table cell when an end tag passes * by without determining if there is any more text. This makes * it impossible to have a bunch of cells with headers in them * where the cells are tight around the text, but c'est la vie. * * We store the extra space in an intermediary and then add it * into the bottom margin later. * */ LONG CRecalcLinePtr::NetscapeBottomMargin(CLSMeasurer * pMe) { if ( _fNoMarginAtBottom || _pdp->GetFlowLayout()->ElementContent()->Tag() == ETAG_BODY ) { ResetPosAndNegSpace(); _fNoMarginAtBottom = FALSE; } // For empty paragraphs at the end of a layout, we create a dummy line // so we can just use the before space of that dummy line. If there is // no dummy line, then we need to use the after space of the previous // line. return pMe->_li._fDummyLine ? pMe->_li._yBeforeSpace : _lTopPadding + _lNegSpaceNoP + _lPosSpaceNoP; } //+------------------------------------------------------------------------ // // Member: RecalcMargins // // Synopsis: Calculate new margins for the current line. // // Arguments: [iLineStart] -- new lines start at // [iLineFirst] -- line to start calculating from // [yHeight] -- y coordinate of the top of line // [yBeforeSpace] -- before space of the current line // //------------------------------------------------------------------------- void CRecalcLinePtr::RecalcMargins( int iLineStart, int iLineFirst, LONG yHeight, LONG yBeforeSpace) { LONG y; CLineCore * pLine; int iAt; CFlowLayout * pFlowLayout = _pdp->GetFlowLayout(); LONG xWidth = pFlowLayout->GetMaxLineWidth(); // Initialize margins to defaults. _marginInfo.Init(); _fMarginFromStyle = FALSE; // Update the state of the line array. Reset(iLineStart); // go back to find the first line which is clear (i.e., a line // with default margins) y = yHeight; iAt = -1; First(iLineFirst); for (pLine = Prev(); pLine; pLine = Prev()) { if (pLine->IsFrame()) { // Cache the line which is aligned iAt = At(); } else { if (pLine->HasMargins(pLine->oi())) { // current line has margins if(pLine->_fForceNewLine) y -= pLine->_yHeight; } else break; } } // iAt now holds the last aligned frame line we saw while walking back, // and pLine is either NULL or points to the first clear line (i.e., // no margins were specified). The Rclclptr state (_iLine) also indexes // that clear line. // y is the y coordinate of first clear line. // if there were no frames there is nothing to do... if (iAt == -1) return; // There are aligned sites, so calculate margins. int iLeftAlignedImages = 0; int iRightAlignedImages = 0; CAlignedLine * pALine; CLineCore * pLineLeftTop = NULL; CLineCore * pLineRightTop = NULL; // stacks to keep track of the number of left & right aligned sites // adding margins to the current line. _aryLeftAlignedImgs.SetSize(0); _aryRightAlignedImgs.SetSize(0); // have to adjust the height of the aligned frames. // iAt is the last frame line we saw, so start there and // walk forward until we get to iLineFirst. // _yBottomLeftMargin and _yBottomRightMargin are the max y values // for which the current left/right margin values are valid; i.e., // once y increases past _yBottomLeftMargin, there's a new left margin // that must be used. for (pLine = First(iAt); pLine && At() <= iLineFirst; pLine = Next()) { // update y to skip by if(At() == iLineFirst) y += yBeforeSpace; else { // Include the text or center aligned height if (pLine->_fForceNewLine) { y += pLine->_yHeight; } } // If there are any left aligned images while(iLeftAlignedImages) { // check to see if we passed the left aligned image, if so pop it of the // stack and set its height pALine = & _aryLeftAlignedImgs [ iLeftAlignedImages - 1 ]; if(y >= pALine->_pLine->_yHeight + pALine->_yLine) { _aryLeftAlignedImgs.Delete( -- iLeftAlignedImages ); } else break; } // If there are any right aligned images while(iRightAlignedImages) { pALine = & _aryRightAlignedImgs [ iRightAlignedImages - 1 ]; // check to see if we passed the right aligned image, if so pop it of the // stack and set its height if(y >= pALine->_pLine->_yHeight + pALine->_yLine) { _aryRightAlignedImgs.Delete( -- iRightAlignedImages ); } else break; } if (pLine->IsFrame() && At() != iLineFirst) { HRESULT hr = S_OK; const CFancyFormat * pFF = pLine->AO_GetFancyFormat(NULL); CAlignedLine al; al._pLine = pLine; al._yLine = y; // If the current line is left aligned push it on to the left aligned images // stack and adjust the _yBottomLeftMargin. if (pLine->IsLeftAligned()) { // // If the current aligned element needs to clear left, insert // the current aligned layout below all other left aligned // layout's since it is the last element that establishes // the margin. // if ((pFF && pFF->_fClearLeft) || (pLine->oi()->_fHasFloatedFL && pLine->_fClearBefore)) { hr = _aryLeftAlignedImgs.InsertIndirect(0, &al); if (hr) return; } else { CAlignedLine * pAlignedLine; hr = _aryLeftAlignedImgs.AppendIndirect(NULL, &pAlignedLine); if (hr) return; *pAlignedLine = al; } iLeftAlignedImages++; if (y + pLine->_yHeight > _marginInfo._yBottomLeftMargin) { _marginInfo._yBottomLeftMargin = y + pLine->_yHeight; } } // If the current line is right aligned push it on to the right aligned images // stack and adjust the _yBottomRightMargin. else if (pLine->IsRightAligned()) { // // If the current aligned element needs to clear right, insert // the current aligned layout below all other right aligned // layout's since it is the last element that establishes // the margin. // if (pFF && pFF->_fClearRight) { hr = _aryRightAlignedImgs.InsertIndirect(0, &al); if (hr) return; } else { CAlignedLine * pAlignedLine; hr = _aryRightAlignedImgs.AppendIndirect(NULL, &pAlignedLine); if (hr) return; *pAlignedLine = al; } iRightAlignedImages++; if (y + pLine->_yHeight > _marginInfo._yBottomRightMargin) { _marginInfo._yBottomRightMargin = y + pLine->_yHeight; } } } } // Only use remaining floated objects. _fMarginFromStyle = FALSE; // If we have any left aligned sites left on the stack, calculate the // left margin. if(iLeftAlignedImages) { CLineOtherInfo *pLineLeftTopOI; const CFancyFormat *pFF; // get the topmost left aligned line and compute the current lines // left margin pALine = & _aryLeftAlignedImgs [ iLeftAlignedImages - 1 ]; pLineLeftTop = pALine->_pLine; pLineLeftTopOI = pLineLeftTop->oi(); if(!_pdp->IsRTLDisplay()) _marginInfo._xLeftMargin = pLineLeftTopOI->_xLeftMargin + pLineLeftTop->_xLineWidth; else { _marginInfo._xLeftMargin = max(0L, xWidth - pLineLeftTopOI->_xRightMargin); // TODO RTL 112514: this is probably bogus. how to get here? Assert(_marginInfo._xLeftMargin == pLineLeftTopOI->_xLeftMargin + pLineLeftTop->_xLineWidth || !IsTagEnabled(tagDebugRTL)); } _marginInfo._yLeftMargin = pLineLeftTop->_yHeight + pALine->_yLine; // Note if a "frame" margin may be needed _marginInfo._fAddLeftFrameMargin = pLineLeftTop->_fAddsFrameMargin; // Note whether margin space is due to CSS float (as opposed to ALIGN attr). // We need to know this because if it's CSS float, we autoclear after the line. pFF = pLineLeftTop->AO_GetFancyFormat(pLineLeftTopOI); _fMarginFromStyle |= pFF && pFF->_fCtrlAlignFromCSS; } else { // no left aligned sites for the current line, so set the margins to // defaults. _marginInfo._yBottomLeftMargin = MINLONG; _marginInfo._yLeftMargin = MAXLONG; _marginInfo._xLeftMargin = 0; } // If we have any right aligned sites left on the stack, calculate the // right margin. if(iRightAlignedImages) { CLineOtherInfo *pLineRightTopOI; const CFancyFormat *pFF; // get the topmost right aligned line and compute the current lines // right margin pALine = & _aryRightAlignedImgs [ iRightAlignedImages - 1 ]; pLineRightTop = pALine->_pLine; pLineRightTopOI = pLineRightTop->oi(); if(!_pdp->IsRTLDisplay()) _marginInfo._xRightMargin = max(0L, xWidth - pLineRightTopOI->_xLeftMargin); else { _marginInfo._xRightMargin = pLineRightTopOI->_xRightMargin + pLineRightTop->_xLineWidth; // TODO RTL 112514: this is probably bogus. how to get here? Assert(_marginInfo._xRightMargin == max(0L, xWidth - pLineRightTopOI->_xLeftMargin) || !IsTagEnabled(tagDebugRTL)); } _marginInfo._yRightMargin = pLineRightTop->_yHeight + pALine->_yLine; // Note if a "frame" margin may be needed _marginInfo._fAddRightFrameMargin = pLineRightTop->_fAddsFrameMargin; // Note whether margin space is due to CSS float (as opposed to ALIGN attr). // We need to know this because if it's CSS float, we autoclear after the line. pFF = pLineRightTop->AO_GetFancyFormat(pLineRightTopOI); _fMarginFromStyle |= pFF && pFF->_fCtrlAlignFromCSS; } else { // no right aligned sites for the current line, so set the margins to // defaults. _marginInfo._yBottomRightMargin = MINLONG; _marginInfo._yRightMargin = MAXLONG; _marginInfo._xRightMargin = 0; } } //+------------------------------------------------------------------------ // // Member: AlignObjects // // Synopsis: Process all aligned objects on a line and create new // "frame" lines for them. // // Arguments: [pMe] -- measurer used to recalc lines // [uiFlags] -- flags // [iLineStart] -- new lines start at // [iLineFirst] -- line to start calculating from // [pyHeight] -- y coordinate of the top of line // //------------------------------------------------------------------------- int CRecalcLinePtr::AlignObjects( CLSMeasurer *pme, CLineFull *pLineMeasured, LONG cch, BOOL fMeasuringSitesAtBOL, BOOL fBreakAtWord, BOOL fMinMaxPass, int iLineStart, int iLineFirst, LONG *pyHeight, int xWidthMax, LONG *pyAlignDescent, LONG *pxMaxLineWidth) { CFlowLayout * pFlowLayout = _pdp->GetFlowLayout(); CLayout * pLayout; LONG xWidth = pFlowLayout->GetMaxLineWidth(); htmlControlAlign atSite; CLineCore * pLine; CLineCore * pLineNew; CLineFull lifNew; LONG yHeight; LONG yHeightCurLine = 0; int xMin = 0; int iClearLines=0; CTreePos *ptp; CTreeNode *pNodeLayout; LONG cchInTreePos; CLayoutContext *pLayoutContext = _pci->GetLayoutContext(); BOOL fViewChain = (pLayoutContext && pLayoutContext->ViewChain()); CFlowLayoutBreak *pEndingBreak = NULL; if (fViewChain) { // // Retrieve ending layout break to provide access to Site Tasks queue. // CLayoutBreak *pLayoutBreak; pLayoutContext->GetEndingLayoutBreak(_pdp->GetFlowLayoutElement(), &pLayoutBreak); if (pLayoutBreak) { pEndingBreak = DYNCAST(CFlowLayoutBreak, pLayoutBreak); } } Reset(iLineStart); pLine = (*this)[iLineFirst]; // Make sure the current line has aligned sites Assert(pLine->_fHasAligned); yHeight = *pyHeight; // If we are measuring sites at the beginning of the line, // measurer is positioned at the current site. So we dont // need to back up the measurer. Also, margins the current // line apply to the line being inserted before the current // line. if(!fMeasuringSitesAtBOL) { // fliForceNewLine is set for lines that have text in them. Assert (pLine->_fForceNewLine); // adjust the height and recalc the margins for the aligned // lines being inserted after the current line yHeightCurLine = pLine->_yHeight; yHeight += yHeightCurLine; if (fViewChain) { // Adjust Y consumed if this is not BOL _pci->_yConsumed += yHeightCurLine; } iLineFirst++; if (!IsValidMargins(yHeight)) { RecalcMargins(iLineStart, iLineFirst, yHeight, 0); } } ptp = pme->GetPtp(); pNodeLayout = ptp->GetBranch(); if (ptp->IsText()) cchInTreePos = ptp->Cch() - (pme->GetCp() - ptp->GetCp()); else cchInTreePos = ptp->GetCch(); while (cch > 0) { if (ptp->IsBeginElementScope()) { pNodeLayout = ptp->Branch(); if (pNodeLayout->ShouldHaveLayout()) { const CCharFormat * pCF = pNodeLayout->GetCharFormat( LC_TO_FC(_pci->GetLayoutContext()) ); const CParaFormat * pPF = pNodeLayout->GetParaFormat( LC_TO_FC(_pci->GetLayoutContext()) ); const CFancyFormat * pFF = pNodeLayout->GetFancyFormat( LC_TO_FC(_pci->GetLayoutContext()) ); BOOL fClearLeft = pFF->_fClearLeft; BOOL fClearRight = pFF->_fClearRight; CElement * pElementLayout = pNodeLayout->Element(); cchInTreePos = pme->GetNestedElementCch(pElementLayout, &ptp); atSite = pNodeLayout->GetSiteAlign( LC_TO_FC(_pci->GetLayoutContext()) ); if ( !pCF->IsDisplayNone() && pFF->_fAlignedLayout) { LONG xWidthSite, yHeightSite, yBottomMarginSite; pLayout = pNodeLayout->GetUpdatedLayout( _pci->GetLayoutContext() ); // measuring sites at the Beginning of the line, // insert the aligned line before the current line lifNew.Init(); if(fMeasuringSitesAtBOL) { pLineNew = InsertLine(iLineFirst); if (!pLineNew) goto Cleanup; lifNew._fFrameBeforeText = TRUE; lifNew._yBeforeSpace = pLineMeasured->_yBeforeSpace; } else { // insert the aligned line after the current line pLineNew = AddLine(); if (!pLineNew) goto Cleanup; lifNew._fHasEOP = (*this)[iLineFirst - 1]->_fHasEOP; } // Update the line width and new margins caused by the aligned line for(;;) { int yConsumedSafe = 0; BOOL fLayoutOverflowSafe = FALSE; if (fViewChain) { // save consumed space yConsumedSafe = _pci->_yConsumed; // save overflow flag fLayoutOverflowSafe = _pci->_fLayoutOverflow; // make adjustments to Y consumed if the align object has clear attribute(s) if(atSite == htmlAlignLeft) { if ( fClearLeft && _marginInfo._xLeftMargin && lifNew._yBeforeSpace < _marginInfo._yBottomLeftMargin - yHeight) { _pci->_yConsumed += (_marginInfo._yBottomLeftMargin - yHeight); } } else if(atSite == htmlAlignRight) { if ( fClearRight && _marginInfo._xRightMargin && lifNew._yBeforeSpace < _marginInfo._yBottomRightMargin - yHeight) { _pci->_yConsumed += (_marginInfo._yBottomRightMargin - yHeight); } } } // Measure the site pme->GetSiteWidth(pNodeLayout, pLayout, _pci, fBreakAtWord, max(0l, xWidthMax - _xLayoutLeftIndent - _xLayoutRightIndent), &xWidthSite, &yHeightSite, &xMin, &yBottomMarginSite); if (fViewChain) { // if align object didn't fit to space provided... if (pEndingBreak) { // we want to remember element's tree node into Site Tasks queue. // (if element knows how to break) if (_pci->_fLayoutOverflow) { CFlowLayoutBreak::CArySiteTask *pArySiteTask; pArySiteTask = pEndingBreak->GetSiteTasks(); Assert(pArySiteTask); if (pArySiteTask) { CFlowLayoutBreak::CSiteTask *pSiteTask; pSiteTask = pArySiteTask->Append(); pSiteTask->_pTreeNode = pNodeLayout; if (atSite == htmlAlignLeft) { pSiteTask->_xMargin = fClearLeft ? 0 : _marginInfo._xLeftMargin; } else if (atSite == htmlAlignRight) { pSiteTask->_xMargin = fClearRight ? 0 : _marginInfo._xRightMargin; } else { pSiteTask->_xMargin = 0; } } } // (bug #111362) yHeightSite must be adjusted to available height // to avoid unnecessary deletion of lines during CDisplay::UndoMeasure. // It's also safe since it doesn't affect any properties of the // aligned object. if ((_pci->_cyAvail - _pci->_yConsumed) < yHeightSite) { yHeightSite = _pci->_cyAvail - _pci->_yConsumed; } } // restore saved values _pci->_yConsumed = yConsumedSafe; // aligned objects should not affect pagination of the main flow _pci->_fLayoutOverflow = fLayoutOverflowSafe; } // // if clear is set on the layout, we don need to auto clear. // if (fClearLeft || fClearRight) break; // If we've overflowed, and the current margin allows for auto // clearing, we have to introduce a clear line. if (_fMarginFromStyle && _marginInfo._xLeftMargin + _marginInfo._xRightMargin > 0 && xWidthSite > xWidthMax) { int iliClear; _marginInfo._fAutoClear = TRUE; // Find the index of the clear line that is being added. if(fMeasuringSitesAtBOL) { iliClear = iLineFirst + iClearLines; } else { iliClear = Count() - 1; } // --------------------------------------------------------- // // BEGIN HACK! HACK! HACK! HACK! // // ClearObjects will look at the line array to make some // of its decisions. It will also *reuse* the line in line // array -- but will assume that it has no line other info // associated with it. Hence, we just transfer the lifNew // over to the core line and do not bother with the other // info part of lifNew since (a)ClearObjects would have to // release it -- since it is reusing pliNew and (b)ClearObjects // does not require to look at the other info of pliNew. Assert(lifNew._iLOI < 0); *pLineNew = lifNew; // // END HACK! HACK! HACK! HACK! // // --------------------------------------------------------- // add a clear line ClearObjects(&lifNew, iLineStart, iliClear, &yHeight); iClearLines++; // // Clear line takes any beforespace, so clear the // beforespace for the current line // pme->_li._yBeforeSpace = 0; ResetPosAndNegSpace(); // insert the new line for the alined element after the // clear line. lifNew.Init(); if(fMeasuringSitesAtBOL) { pLineNew = InsertLine(iLineFirst + iClearLines); if (!pLineNew) goto Cleanup; lifNew._fFrameBeforeText = TRUE; } else { pLineNew = AddLine(); if (!pLineNew) goto Cleanup; lifNew._fFrameBeforeText = FALSE; } RecalcMargins(iLineStart, fMeasuringSitesAtBOL ? iLineFirst + iClearLines : Count() - 1, yHeight, 0); xWidthMax = GetAvailableWidth(); } // We fit just fine, but keep track of total available width. else { xWidthMax -= xWidthSite; break; } } // end of for loop // Start out assuming that there are no style floated objects. _fMarginFromStyle = FALSE; // Note if the site adds "frame" margin space // (e.g., tables do, images do not) lifNew._fAddsFrameMargin = !(pNodeLayout->Element()->Tag() == ETAG_IMG); // Top Margin is included in the line height for aligned lines, // at the top of the document. Before paragraph spacing is // also included in the line height. long xLeftMargin, yTopMargin, xRightMargin; // get the site's margins pLayout->GetMarginInfo(_pci, &xLeftMargin, &yTopMargin, &xRightMargin, NULL); // note: RTL display (but not RTL line) needs different calculations, because when // an RTL object doesn't fit in dislpay width, it needs to shift to the left. // Also, aligned RTL objects affect min/max calculations in combination with // right margin (instead of left). // Therefore, calculations are done from the right margin long xPos; if (!_pdp->IsRTLDisplay()) xPos = xLeftMargin; else xPos = xRightMargin; // Set proposed relative to the line pLayout->SetXProposed(xPos); pLayout->SetYProposed(yTopMargin + (fMeasuringSitesAtBOL ? (_yPadTop + _yBordTop) : 0)); if (pCF->HasCharGrid(FALSE)) { long xGridWidthSite = pme->_pLS->GetClosestGridMultiple(pme->_pLS->GetCharGridSize(), xWidthSite); pLayout->SetXProposed(xPos + ((xGridWidthSite - xWidthSite)/2)); xWidthSite = xGridWidthSite; } if (pCF->HasLineGrid(FALSE)) { long yGridHeightSite = pme->_pLS->GetClosestGridMultiple(pme->_pLS->GetLineGridSize(), yHeightSite); pLayout->SetYProposed(yTopMargin + ((yGridHeightSite - yHeightSite)/2)); yHeightSite = yGridHeightSite; } // _cch, _xOverhang and _xLeft are initialized to zero Assert(lifNew._cch == 0 && lifNew._xLineOverhang == 0 && lifNew._xLeft == 0 && lifNew._xRight == 0); // for the current line measure the left and the right indent { long xParentWidth = _pci->_sizeParent.cx; if ( pPF->_cuvLeftIndentPercent.GetUnitValue() || pPF->_cuvRightIndentPercent.GetUnitValue() ) { xParentWidth = pNodeLayout->GetParentWidth(_pci, xParentWidth); } long xLeftIndent = pPF->GetLeftIndent(_pci, FALSE, xParentWidth); long xRightIndent = pPF->GetRightIndent(_pci, FALSE, xParentWidth); if (pCF->_fHasBgColor || pCF->_fHasBgImage) { lifNew._fHasBackground = TRUE; } // (changes to the next block should be reflected in // ApplyLineIndents() too) if(atSite == htmlAlignLeft) { _marginInfo._fAddLeftFrameMargin = lifNew._fAddsFrameMargin; xLeftIndent += _xMarqueeWidth + _xLayoutLeftIndent; xLeftIndent += _xPadLeft + _xBordLeft; // xLeftIndent is now the sum of indents. CSS requires that when possible, this // indent is shared with the space occupied by floated/ALIGN'ed elements // (our code calls that space "margin"). Thus we want to apply a +ve xLeftIndent // only when it's greater than the margin, and the amount applied excludes // what's occupied by the margin already. (We never want to apply a -ve xLeftIndent) if (!fClearLeft) lifNew._xLeft = max( 0L, xLeftIndent - _marginInfo._xLeftMargin ); else lifNew._xLeft = xLeftIndent; // If the current layout has clear left, then we need to adjust its // before space so we're beneath all other left-aligned layouts. // For the current layout to be clear left, its yBeforeSpace + yHeight must // equal or exceed the current yBottomLeftMargin. if ( fClearLeft && _marginInfo._xLeftMargin && lifNew._yBeforeSpace < _marginInfo._yBottomLeftMargin - yHeight) { lifNew._yBeforeSpace = _marginInfo._yBottomLeftMargin - yHeight; } } else if(atSite == htmlAlignRight) { _marginInfo._fAddRightFrameMargin = lifNew._fAddsFrameMargin; xRightIndent += _xMarqueeWidth + _xLayoutRightIndent; xRightIndent += _xPadRight + _xBordRight; // xRightIndent is now the sum of indents. CSS requires that when possible, this // indent is shared with the space occupied by floated/ALIGN'ed elements // (our code calls that space "margin"). Thus we want to apply a +ve xRightIndent // only when it's greater than the margin, and the amount applied excludes // what's occupied by the margin already. (We never want to apply a -ve xRightIndent) if (!fClearRight) lifNew._xRight = max( 0L, xRightIndent - _marginInfo._xRightMargin ); else lifNew._xRight = xRightIndent; LONG xLeft = xLeftIndent + _xMarqueeWidth + _xLayoutLeftIndent + _xPadLeft + _xBordLeft; if (!fClearLeft) xLeft = max(0L, xLeft - _marginInfo._xLeftMargin); xMin += xLeft + lifNew._xRight; // If it's right aligned, remember the widest one in max mode. _xMaxRightAlign = max(_xMaxRightAlign, long(xMin)); // If the current layout has clear right, then we need to adjust its // before space so we're beneath all other right-aligned layouts. // For the current layout to be clear right, its yBeforeSpace + yHeight must // equal or exceed the current yBottomRightMargin. if ( fClearRight && _marginInfo._xRightMargin && lifNew._yBeforeSpace < _marginInfo._yBottomRightMargin - yHeight) { lifNew._yBeforeSpace = _marginInfo._yBottomRightMargin - yHeight; } } } // RTL line needs the adjustment at the right if(!pme->_li.IsRTLLine()) lifNew._xLeft += _xLeadAdjust; else lifNew._xRight += _xLeadAdjust; lifNew._xWidth = xWidthSite; lifNew._xLineWidth = lifNew._xWidth; if (fMeasuringSitesAtBOL) lifNew._yExtent = _yPadTop + _yBordTop; lifNew._yExtent += yHeightSite; lifNew._yHeight = lifNew._yExtent + lifNew._yBeforeSpace; lifNew._pNodeForLayout = pNodeLayout; _fMarginFromStyle = pFF->_fCtrlAlignFromCSS; // Update the left and right margins if (atSite == htmlAlignLeft) { lifNew.SetLeftAligned(); _cLeftAlignedLayouts++; lifNew._xLineWidth += lifNew._xLeft; // note: for LTR display, right-aligned objects affect min/max calculations. // for RTL it is vice versa if (!_pdp->IsRTLDisplay()) { lifNew._xLeftMargin = fClearLeft ? 0 : _marginInfo._xLeftMargin; } else { if (fClearLeft) { lifNew._xLeftMargin = 0; } if (fMinMaxPass) { lifNew._xRightMargin = _marginInfo._xRightMargin; } else { lifNew._xRightMargin = max(_marginInfo._xRightMargin, xWidth + 2 * _xMarqueeWidth - (fClearLeft ? 0 : _marginInfo._xLeftMargin) - lifNew._xLineWidth); lifNew._xRightMargin = max(_xLayoutRightIndent, lifNew._xRightMargin); } } // // if the current layout has clear then it may not // establish the margin, because it needs to clear // any left aligned layouts if any, in which case // the left margin remains the same. // if (!fClearLeft || _marginInfo._xLeftMargin == 0 ) { _marginInfo._xLeftMargin += lifNew._xLineWidth; _marginInfo._yLeftMargin = yHeight + lifNew._yHeight; } // // Update max y of all the left margin's // if (yHeight + lifNew._yHeight > _marginInfo._yBottomLeftMargin) { _marginInfo._yBottomLeftMargin = yHeight + lifNew._yHeight; if (yHeight + lifNew._yHeight > *pyAlignDescent) { *pyAlignDescent = yHeight + lifNew._yHeight - yBottomMarginSite; } } } else { lifNew.SetRightAligned(); _cRightAlignedLayouts++; lifNew._xLineWidth += lifNew._xRight; if (!_pdp->IsRTLDisplay()) { if (fMinMaxPass) { lifNew._xLeftMargin = _marginInfo._xLeftMargin; } else { lifNew._xLeftMargin = max(_marginInfo._xLeftMargin, xWidth + 2 * _xMarqueeWidth - (fClearRight ? 0 : _marginInfo._xRightMargin) - lifNew._xLineWidth); lifNew._xLeftMargin = max(_xLayoutLeftIndent, lifNew._xLeftMargin); } } else { lifNew._xRightMargin = fClearRight ? 0 : _marginInfo._xRightMargin; } // // if the current layout has clear then it may not // establish the margin, because it needs to clear // any left aligned layouts if any, in which case // the left margin remains the same. // if (!fClearRight || _marginInfo._xRightMargin == 0) { _marginInfo._xRightMargin += lifNew._xLineWidth; _marginInfo._yRightMargin = yHeight + lifNew._yHeight; } // // Update max y of all the right margin's // if (yHeight + lifNew._yHeight > _marginInfo._yBottomRightMargin) { _marginInfo._yBottomRightMargin = yHeight + lifNew._yHeight; if (yHeight + lifNew._yHeight > *pyAlignDescent) { *pyAlignDescent = yHeight + lifNew._yHeight; } } } if (pxMaxLineWidth) { if(!_pdp->IsRTLDisplay()) { *pxMaxLineWidth = max(*pxMaxLineWidth, lifNew._xLeftMargin + lifNew._xLineWidth); } else { *pxMaxLineWidth = max(*pxMaxLineWidth, lifNew._xRightMargin + lifNew._xLineWidth); } } if (_pci->IsNaturalMode()) { const CFancyFormat * pFF = pNodeLayout->GetFancyFormat(); Assert(pFF->_bPositionType != stylePositionabsolute); long dx; if (!_pdp->IsRTLDisplay()) dx = lifNew._xLeftMargin + lifNew._xLeft; else { dx = - lifNew._xRightMargin - lifNew._xRight; } long xPos; // Aligned elements have their CSS margin stored in _ptProposed of // their layout. In the static case above, AddLayoutDispNode() // accounts for it. This is where we account for it in the // relative case. (Bug #65664) if(!_pdp->IsRTLDisplay()) xPos = dx + pLayout->GetXProposed(); else { // we need to set the top left corner. AssertSz(!IsTagEnabled(tagDebugRTL), "AlignObjects case 65664"); // TODO RTL 112514 CSize size; pLayout->GetApparentSize(&size); xPos = dx + _pdp->GetViewWidth() - pLayout->GetXProposed() - size.cx; } if (pFF->_bPositionType != stylePositionrelative) { pme->_pDispNodePrev = _pdp->AddLayoutDispNode( _pci, pNodeLayout, xPos, yHeight + lifNew.GetYTop() + pLayout->GetYProposed(), pme->_pDispNodePrev ); } else { CPoint ptAuto(xPos, yHeight + lifNew._yBeforeSpace + pLayout->GetYProposed()); pNodeLayout->Element()->ZChangeElement(0, &ptAuto, _pci->GetLayoutContext()); } } // save back into the line array here pLineNew->AssignLine(lifNew); // If we are measuring sites at the Beginning of the line. We are // interested only in the current site. if(fMeasuringSitesAtBOL) { break; } } } } cch -= cchInTreePos; ptp = ptp->NextTreePos(); Assert(ptp); cchInTreePos = ptp->GetCch(); } Cleanup: // Height of the current text line that contains the embedding characters for // the aligned sites is added at the end of CRecalcLinePtr::MeasureLine. // Here we are taking care of only the clear lines here. *pyHeight = yHeight - yHeightCurLine; if (fViewChain) { // restore Y consumed _pci->_yConsumed -= yHeightCurLine; } return iClearLines; } //+-------------------------------------------------------------------------- // // Member: ClearObjects // // Synopsis: Insert new line for clearing objects at the left/right margin // // Arguments: [pLineMeasured] -- Current line measured. // [iLineStart] -- new lines start at // [iLineFirst] -- line to start calculating from // [pyHeight] -- y coordinate of the top of line // // //--------------------------------------------------------------------------- BOOL CRecalcLinePtr::ClearObjects( CLineFull *pLineMeasured, int iLineStart, int & iLineFirst, LONG *pyHeight) { CLineCore * pLine; LONG yAt; CLineCore * pLineNew; Reset(iLineStart); pLine = (*this)[iLineFirst]; Assert(_marginInfo._fClearLeft || _marginInfo._fClearRight || _marginInfo._fAutoClear); // Find the height to clear yAt = *pyHeight; if (_marginInfo._fClearLeft && yAt < _marginInfo._yBottomLeftMargin) { yAt = _marginInfo._yBottomLeftMargin; } if (_marginInfo._fClearRight && yAt < _marginInfo._yBottomRightMargin) { yAt = _marginInfo._yBottomRightMargin; } if (_marginInfo._fAutoClear) { yAt = max(yAt, min(_marginInfo._yRightMargin, _marginInfo._yLeftMargin)); } if(pLine->_cch > 0 && yAt <= (*pyHeight + pLine->_yHeight)) { // nothing to clear pLine->_fClearBefore = pLine->_fClearAfter = FALSE; } // if the current line has any characters or is an aligned site line, // then add a new line, otherwise, re-use the current line. else if (pLine->_cch || pLine->IsFrame() && !_marginInfo._fAutoClear) { if(yAt > *pyHeight) { BOOL fIsFrame = pLine->IsFrame(); pLineNew = AddLine(); pLine = (*this)[iLineFirst]; if (pLineNew) { CLineFull lif; CLineOtherInfo *pLineInfo = pLine->oi(); lif.Init(); lif._cch = 0; lif._xLeft = pLineInfo->_xLeft; lif._xRight = pLine->_xRight; lif._xLeftMargin = _marginInfo._xLeftMargin; lif._xRightMargin = _marginInfo._xRightMargin; lif._xLineWidth = max (0L, (_marginInfo._xLeftMargin ? _xMarqueeWidth : 0) + (_marginInfo._xRightMargin ? _xMarqueeWidth : 0) + _pdp->GetFlowLayout()->GetMaxLineWidth() - _marginInfo._xLeftMargin - _marginInfo._xRightMargin); lif._xWidth = 0; // Make the line the right size to clear. if (fIsFrame) lif._yHeight = pLine->_yHeight; else if (pLine->_fForceNewLine) { lif._yHeight = yAt - *pyHeight - pLine->_yHeight; } else { // // if the previous line does not force new line, // then we need to propagate the beforespace. // lif._yBeforeSpace = pLineInfo->_yBeforeSpace; lif._yHeight = yAt - *pyHeight; Assert(lif._yHeight >= lif._yBeforeSpace); } *pyHeight += lif._yHeight; lif._yExtent = lif._yHeight - lif._yBeforeSpace; lif._yDescent = 0; lif._yTxtDescent = 0; lif._fForceNewLine = TRUE; lif._fClearAfter = !pLineMeasured->_fClearBefore; lif._fClearBefore = pLineMeasured->_fClearBefore; lif._xLineOverhang = 0; lif._cchWhite = 0; lif._fHasEOP = pLine->_fHasEOP; if (_pci->GetLayoutContext()) { lif._fClearLeft = _marginInfo._fClearLeft; lif._fClearRight = _marginInfo._fClearRight; lif._fAutoClear = _marginInfo._fAutoClear; } pLine->_fClearBefore = pLine->_fClearAfter = FALSE; pLineNew->AssignLine(lif); } else { Assert(FALSE); return FALSE; } } } // Just replacing the existing empty line. else { CLineFull lif; Assert(pLine->_iLOI < 0); lif.Init(); lif._xWidth = 0; // The clear line needs to have a margin for // recalc margins to work. lif._xLeftMargin = _marginInfo._xLeftMargin; lif._xRightMargin = _marginInfo._xRightMargin; lif._xLineWidth = max (0L, (_marginInfo._xLeftMargin ? _xMarqueeWidth : 0) + (_marginInfo._xRightMargin ? _xMarqueeWidth : 0) + _pdp->GetFlowLayout()->GetMaxLineWidth() - _marginInfo._xLeftMargin - _marginInfo._xRightMargin); lif._xLeft = pLineMeasured->_xLeft; lif._xRight = pLineMeasured->_xRight; lif._yHeight = yAt - *pyHeight; lif._yExtent = lif._yHeight; lif._yDescent = 0; lif._yTxtDescent = 0; lif._xLineOverhang = 0; lif._cchWhite = 0; lif._fHasBulletOrNum = FALSE; lif._fClearAfter = !pLineMeasured->_fClearBefore; lif._fClearBefore = pLineMeasured->_fClearBefore; lif._fForceNewLine = TRUE; if (_pci->GetLayoutContext()) { lif._fClearLeft = _marginInfo._fClearLeft; lif._fClearRight = _marginInfo._fClearRight; lif._fAutoClear = _marginInfo._fAutoClear; } pLine->AssignLine(lif); if (!_marginInfo._fAutoClear) iLineFirst--; // If we are clearing the line, then we will come around again to measure // the line and we will call CalcBeforeSpace all over again which will // add in the padding+border of block elements coming into scope again. // To avoid this, remove the padding+border added in this time. if (pLineMeasured->_fFirstInPara) { _xBordLeft -= _xBordLeftPerLine; _xBordRight -= _xBordRightPerLine; _xPadLeft -= _xPadLeftPerLine; _xPadRight -= _xPadRightPerLine; } } if(pLine->_fForceNewLine) *pyHeight += pLine->_yHeight; // Prepare for the next pass of the measurer. _marginInfo._fClearLeft = FALSE; _marginInfo._fClearRight = FALSE; return TRUE; } //+---------------------------------------------------------------------------- // // Member: CRecalcLinePtr::MeasureLine() // // Synopsis: Measures a new line, creates aligned and clear lines if // current text line has aligned objects or clear flags set on it. // Updates iNewLine to point to the last text line. -1 if there is // no text line before the current line // //----------------------------------------------------------------------------- BOOL CRecalcLinePtr::MeasureLine(CLSMeasurer &me, UINT uiFlags, INT * piLine, LONG * pyHeight, LONG * pyAlignDescent, LONG * pxMinLineWidth, LONG * pxMaxLineWidth ) { LONG cchSkip = 0; LONG xWidth = 0; CLineCore *pliNew; INT iTLine = *piLine - 1; BOOL fAdjustForCompact = FALSE; CFlowLayout *pFlowLayout = _pdp->GetFlowLayout(); BOOL fClearMarginsRequired; CTreeNode *pNodeFormatting; Reset(_iNewFirst); pliNew = (*this)[*piLine]; _xLeadAdjust = 0; _ptpStartForListItem = NULL; me._cchAbsPosdPreChars = 0; me._fRelativePreChars = FALSE; me._fMeasureFromTheStart = FALSE; me._fSeenAbsolute = FALSE; _marginInfo._fClearLeft = _marginInfo._fClearRight = _marginInfo._fAutoClear = FALSE; // If the current line being measure has an offset of 0, It implies // the current line is the top most line. if (*pyHeight == 0 ) uiFlags |= MEASURE_FIRSTLINE; #if DBG==1 // We should never have an index off the end of the line array. if (iTLine >= 0 && (*this)[iTLine] == NULL) { Assert(FALSE); goto err; } #endif // If we are measuring aligned sites at the beginnning of the line, // we have initialized the line once. me.NewLine(uiFlags & MEASURE_FIRSTINPARA); Assert(!me._fPseudoLineEnabled); // Space between paragraphs. pNodeFormatting = CalcInterParaSpace(&me, iTLine, &uiFlags); // // Note: CalcBeforeSpace needs to be call ed before we call RecalcMargins // because before space is used to compute margins. // // If the current line being measured has invalid margins, a line that is // below an aligned line, margins have changed so recalculate margins. if (!IsValidMargins(*pyHeight + max(0l, me._li._yBeforeSpace))) { BOOL fClearLeft = _marginInfo._fClearLeft; BOOL fClearRight = _marginInfo._fClearRight; RecalcMargins(_iNewFirst, *piLine, *pyHeight, me._li._yBeforeSpace); if (_fMarginFromStyle) uiFlags |= MEASURE_AUTOCLEAR; // // Restore the clear flags on _marginInfo, since RecalcMargins init's // the marginInfo. CalcBeforeSpace set's up clear flags on the marginInfo // if any elements comming into scope have clear attribute/style set. // _marginInfo._fClearLeft = fClearLeft; _marginInfo._fClearRight = fClearRight; } if ( _pci->GetLayoutContext() // layout in context && _pci->GetLayoutContext()->ViewChain() // there is a view chain && _pdp->LineCount() == 1) // this is the first line { me._cyTopBordPad = _yBordTop + _yPadTop; me._li._cyTopBordPad = me._cyTopBordPad; // Compute the available width for the current line. // (Do this after determining the margins for the line) xWidth = GetAvailableWidth(); ProcessAlignedSiteTasksAtBOB(&me, &me._li, uiFlags, piLine, pyHeight, &xWidth, pyAlignDescent, pxMaxLineWidth, &fClearMarginsRequired); } // // If we need to clear aligned elements, don't bother measuring text // if (!CheckForClear()) { // Apply the line indents, _xLeft and _xRight ApplyLineIndents(pNodeFormatting, &me._li, uiFlags, me._fPseudoElementEnabled); if( iTLine >= 0 ) { BOOL fInner = FALSE; const CParaFormat* pPF; pPF = me.MeasureGetPF(&fInner); CLineCore *pli = (*this)[iTLine]; // If we have the compact attribute set, see if we can fit the DT and the DD on the // same line. if( pPF->HasCompactDL(fInner) && pli->_fForceNewLine ) { CTreeNode * pNodeCurrBlockElem = pNodeFormatting; if (pNodeCurrBlockElem->Element()->IsTagAndBlock(ETAG_DD)) { CLineFull lif = *pli; CTreePos * ptp; CTreePos * ptpFirst; CTreeNode * pNodePrevBlockElem; // // Find the DT which should have appeared before the DD // // Get the max we will travel backwards in search of the DT pFlowLayout->GetContentTreeExtent(&ptpFirst, NULL); pNodePrevBlockElem = NULL; ptp = me.GetPtp(); for(;;) { ptp = ptp->PreviousTreePos(); Assert(ptp); if ( (ptp == ptpFirst) || ptp->IsText() ) break; if ( ptp->IsEndElementScope() && ptp->Branch()->Element()->IsTagAndBlock(ETAG_DT) ) { pNodePrevBlockElem = ptp->Branch(); break; } } #if DBG==1 if (pNodePrevBlockElem) { Assert(pNodePrevBlockElem->Element()->IsTagAndBlock(ETAG_DT)); Assert((pFlowLayout->GetContentMarkup()->FindMyListContainer(pNodeCurrBlockElem) == pFlowLayout->GetContentMarkup()->FindMyListContainer(pNodePrevBlockElem))); } #endif // Make sure that the DT is thin enough to fit the DD on the same line. // TODO RTL 112514: avoid obscure formulas in offset calculations if ( pNodePrevBlockElem && (!pPF->_fRTL ? me._li._xLeft > lif._xWidth + lif._xLeft + lif._xLineOverhang : me._li._xRight > lif._xWidth + lif._xRight + lif._xLineOverhang ) ) { fAdjustForCompact = TRUE; lif._fForceNewLine = FALSE; if(!pPF->_fRTL) { lif._xRight = 0; lif._xLineWidth = me._li._xLeft; } else { lif._xLeft = 0; lif._xLineWidth = me._li._xRight; } *pyHeight -= lif._yHeight; if (me._li._yBeforeSpace < lif._yBeforeSpace) me._li._yBeforeSpace = lif._yBeforeSpace; if (lif._yBeforeSpace < me._li._yBeforeSpace) lif._yBeforeSpace = me._li._yBeforeSpace; // If the current line being measured has an offset of 0, It implies // the current line is the top most line. if (*pyHeight == 0 ) uiFlags |= MEASURE_FIRSTLINE; lif.ReleaseOtherInfo(); pli->AssignLine(lif); // Adjust the margins RecalcMargins(_iNewFirst, *piLine, *pyHeight, me._li._yBeforeSpace); if (_fMarginFromStyle) uiFlags |= MEASURE_AUTOCLEAR; } } } } me._cyTopBordPad = _yBordTop + _yPadTop; me._li._cyTopBordPad = me._cyTopBordPad; // Compute the available width for the current line. // (Do this after determining the margins for the line) xWidth = GetAvailableWidth(); cchSkip = CalcAlignedSitesAtBOL(&me, &me._li, uiFlags, piLine, pyHeight, &xWidth, pyAlignDescent, pxMaxLineWidth, &fClearMarginsRequired); pliNew = (*this)[*piLine]; if (!fClearMarginsRequired) { me._cchPreChars = me._li._cch; me._li._cch = 0; if (me._fMeasureFromTheStart) me.SetCp(me.GetCp() - me._cchPreChars, NULL); if (_fMarginFromStyle) uiFlags |= MEASURE_AUTOCLEAR; me._pLS->_cchSkipAtBOL = cchSkip; me._yli = *pyHeight; if(!me.MeasureLine(xWidth, -1, uiFlags, &_marginInfo, pxMinLineWidth)) { Assert(FALSE); goto err; } Check(cchSkip <= me._li._cch); // if it is in edit mode _fNoContent will be always FALSE // If it has a LI on it then too we will say that the display has contents _pdp->_fNoContent = !_fIsEditable && !!(uiFlags & MEASURE_FIRSTLINE && me._li._cch == 0) && !me._li._fHasBulletOrNum; me.Resync(); if (!me._fMeasureFromTheStart) me._li._cch += me._cchPreChars; if ( me._li._fHasBulletOrNum && (_yBordTop || _yPadTop) && !IsListItem(me.GetPtp()->GetBranch()) && !me._pLS->HasVisualContent() ) { _fMoveBulletToNextLine = TRUE; me._li._fHasBulletOrNum = FALSE; me._li._fHasTransmittedLI = TRUE; me._li._yExtent = me._li._yHeight = me._li._yDescent = me._li._yTxtDescent = 0; _ptpStartForListItem = NULL; } // If we couldn't fit anything on the line, clear an aligned thing and // we'll try again afterwards. if (!_marginInfo._fAutoClear || me._li._cch > 0) { // CalcAfterSpace modifies, _xBordLeft and _xBordRight // to account for block elements going out of scope, // set the flag before they are modified. me._li._fHasParaBorder = (_xBordLeft + _xBordRight) != 0; CalcAfterSpace(&me, me._li._fDummyLine && (uiFlags & MEASURE_FIRSTLINE ? TRUE : FALSE), LONG_MAX); // Monitor progress here Assert(me._li._cch != 0 || _pdp->GetLastCp() == me.GetCp()); me._li._yHeight += _yBordTop + _yBordBottom + _yPadTop + _yPadBottom; me._li._yDescent += _yBordBottom + _yPadBottom; me._li._yHeight += (LONG)me._li._yBeforeSpace; me._li._yExtent += _yBordTop + _yBordBottom + _yPadTop + _yPadBottom; me._li._fHasParaBorder |= (_yBordTop + _yBordBottom) != 0; AssertSz(!IsBadWritePtr(pliNew, sizeof(CLineCore)), "Line Array has been realloc'd and now pliNew is invalid! " "Memory corruption is about to occur!"); // Remember the longest word. if(pxMinLineWidth && _pdp->_xMinWidth >= 0) { _pdp->_xMinWidth = max(_pdp->_xMinWidth, *pxMinLineWidth); } } else { ResetPosAndNegSpace(); } } else { me.Advance(cchSkip); ResetPosAndNegSpace(); me._li._cch += cchSkip; me._li._fHasEmbedOrWbr = TRUE; me._li._fDummyLine = TRUE; me._li._fForceNewLine = FALSE; me._li._fClearAfter = TRUE; } } else { me.Advance(-me._li._cch); me._li._fClearBefore = TRUE; me._li._xWhite = me._li._xWidth = 0; me._li._cch = me._li._cchWhite = 0; me._li._yBeforeSpace = me._li._yBeforeSpace; } if (me._li._fForceNewLine) _yPadTop = _yPadBottom = _yBordTop = _yBordBottom = 0; // If we're autoclearing, we don't need to do anything here. if (!_marginInfo._fAutoClear || me._li._cch > 0) { if( fAdjustForCompact ) { CLineCore *pli = (*this)[iTLine]; // since fAdjustForCompact is set, we know iTLine >= 0 CLineFull lif = *pli; lif.ReleaseOtherInfo(); // The DT and DL have different heights, need to make them each the height of the // greater of the two. LONG iDTHeight = lif._yHeight - lif._yBeforeSpace - lif._yDescent; LONG iDDHeight = me._li._yHeight - me._li._yBeforeSpace - me._li._yDescent; lif._yBeforeSpace += max( 0l, iDDHeight - iDTHeight ); me._li._yBeforeSpace += max( 0l, iDTHeight - iDDHeight ); lif._yDescent += max( 0l, me._li._yDescent - lif._yDescent ); me._li._yDescent += max( 0l, lif._yDescent - me._li._yDescent ); lif._yHeight = me._li._yHeight = lif._yBeforeSpace + iDTHeight + lif._yDescent; pli->AssignLine(lif); } me._li._xLeftMargin = _marginInfo._xLeftMargin; me._li._xRightMargin = _marginInfo._xRightMargin; me._li._xLineWidth = me._li.CalcLineWidth(); if(me._li._fForceNewLine && xWidth > me._li._xLineWidth) me._li._xLineWidth = xWidth; if(me._li._fHidden) { me._li._yExtent = 0; } if(pxMaxLineWidth) { *pxMaxLineWidth = max(*pxMaxLineWidth, (!me._li._fRTLLn ? me._li._xLeftMargin : me._li._xRightMargin) + me._li._xWidth + me._li._xLeft - me._li._xNegativeShiftRTL + me._li._xLineOverhang + me._li._xRight); } if ( me._li._cch || (uiFlags & MEASURE_EMPTYLASTLINE) ) { Assert(pliNew); // This innocent looking line is where we transfer // the calculated values to the permanent line array. pliNew->AssignLine(me._li); } // Align those sites which occur somewhere in the middle or at end of the line // (Those occurring at the start are handled in the above loop) if( me._li._fHasAligned && me._cAlignedSites > me._cAlignedSitesAtBeginningOfLine) { // Position the measurer so that it points to the beginning of the line // excluding all the whitespace characters. LONG cch = pliNew->_cch - me.CchSkipAtBeginningOfLine(); CTreePos *ptpOld = me.GetPtp(); LONG cpOld = me.GetCp(); me.Advance(-cch); AlignObjects(&me, &me._li, cch, FALSE, (uiFlags & MEASURE_BREAKATWORD) ? TRUE : FALSE, pxMinLineWidth ? TRUE : FALSE, _iNewFirst, *piLine, pyHeight, xWidth, pyAlignDescent, pxMaxLineWidth); me.SetPtp(ptpOld, cpOld); Assert(me._li == *(*this)[*piLine]); WHEN_DBG(pliNew = NULL); } if ( me._li._fHasFirstLetter && me._li._fHasFloatedFL ) { AlignFirstLetter(&me, _iNewFirst, *piLine, pyHeight, pyAlignDescent, pNodeFormatting); } // NETSCAPE: Right-aligned sites are not normally counted in the maximum line width. // However, the maximum line width should not be allowed to shrink below // the minimum (which does include all left/right-aligned sites guaranteed // to occur on a single line). if (pxMaxLineWidth && pxMinLineWidth) { *pxMaxLineWidth = max(*pxMaxLineWidth, *pxMinLineWidth); } if(me._pLS->HasChunks()) { FixupChunks(me, piLine); pliNew = (*this)[*piLine]; me._li = *pliNew; } } if (_marginInfo._fClearLeft || _marginInfo._fClearRight || _marginInfo._fAutoClear) { ClearObjects(&me._li, _iNewFirst, *piLine, pyHeight); // The calling function(s) expect to point to the last text line. while(*piLine >= 0) { pliNew = (*this)[*piLine]; if(pliNew->IsTextLine()) break; else (*piLine)--; } me._li = *pliNew; } else if (me._li._fForceNewLine) { *pyHeight += me._li._yHeight; } me.PseudoLineDisable(); me._cchPreChars = 0; me._fMeasureFromTheStart = 0; me._pLS->_cchSkipAtBOL = 0; return TRUE; err: me.PseudoLineDisable(); return FALSE; } //+---------------------------------------------------------------------------- // // Member: CRecalcLinePtr::ProcessAlignedSiteTasksAtBOB() // // NOTE: Print View specific !!! Should be called once for block // (before any line is calculated) // // Synopsis: Process Site Tasks queue by measuring aligned sites. // // Params: see CRecalcLinePtr::CalcAlignedSitesAtBOL params. // // Return: nothing. // //----------------------------------------------------------------------------- void CRecalcLinePtr::ProcessAlignedSiteTasksAtBOB( CLSMeasurer * pme, CLineFull * pLineMeasured, UINT uiFlags, INT * piLine, LONG * pyHeight, LONG * pxWidth, LONG * pyAlignDescent, LONG * pxMaxLineWidth, BOOL * pfClearMarginsRequired) { CLayoutContext *pLayoutContext = _pci->GetLayoutContext(); Assert( pLayoutContext && pLayoutContext->ViewChain() && _pdp->LineCount() == 1); // if this is print view and we are called for the first // line of a block, additional work may be needed CLayoutBreak *pLayoutBreak; pLayoutContext->GetLayoutBreak(_pdp->GetFlowLayoutElement(), &pLayoutBreak); if ( pLayoutBreak && DYNCAST(CFlowLayoutBreak, pLayoutBreak)->HasSiteTasks()) { CFlowLayoutBreak::CArySiteTask *pArySiteTask; CFlowLayoutBreak *pFlowLayoutBreak = DYNCAST(CFlowLayoutBreak, pLayoutBreak); pArySiteTask = pFlowLayoutBreak->GetSiteTasks(); // If there are Site Tasks, go ahead and process them if (pArySiteTask) { int i; int cLimit = pArySiteTask->Size(); long cpSafe = pme->GetCp(); for (i = 0; i < cLimit; ++i) { CFlowLayoutBreak::CSiteTask *pSiteTask; htmlControlAlign atSite; pSiteTask = &((*pArySiteTask)[i]); // Adjust ls measurer pme->SetPtp(pSiteTask->_pTreeNode->GetBeginPos(), -1); Check(pme->GetCp() <= cpSafe); if (pme->GetCp() < cpSafe) // (olego) otherwise this site will be processed during CalcAlignedSitesAtBOL. { // if last time (previous block) the element was placed with offset (margin), // restore it here atSite = pSiteTask->_pTreeNode->GetSiteAlign(LC_TO_FC(_pci->GetLayoutContext())); if (atSite == htmlAlignLeft) { if (_marginInfo._xLeftMargin < pSiteTask->_xMargin) { _marginInfo._xLeftMargin = pSiteTask->_xMargin; } } else if (atSite == htmlAlignRight) { if (_marginInfo._xRightMargin < pSiteTask->_xMargin) { _marginInfo._xRightMargin = pSiteTask->_xMargin; } } // Call CalcAlignedSitesAtBOLCore to process tasks CalcAlignedSitesAtBOLCore(pme, pLineMeasured, uiFlags, piLine, pyHeight, pxWidth, pyAlignDescent, pxMaxLineWidth, pfClearMarginsRequired, TRUE // Here we want only one element to be processed ); } } _marginInfo._fClearLeft = pFlowLayoutBreak->_fClearLeft; _marginInfo._fClearRight = pFlowLayoutBreak->_fClearRight; _marginInfo._fAutoClear = pFlowLayoutBreak->_fAutoClear; pme->SetCp(cpSafe, NULL); } } } //+---------------------------------------------------------------------------- // // Member: CRecalcLinePtr::CalcAlignedSitesAtBOL() // // Synopsis: Measures any aligned sites which are at the BOL. // // Params: // prtp(i,o): The position in the runs for the text // pLineMeasured(i,o): The line being measured // uiFlags(i): The flags controlling the measurer behaviour // piLine(i,o): The line before which all aligned lines are added. // Incremented to reflect addition of lines. // pxWidth(i,o): Contains the available width for the line. Aligned // lines will decrease the available width. // pxMinLineWidth(o): These two are passed directly to AlignObjects. // pxMaxLineWidth(o): // // Return: LONG - the no of character's to skip at the beginning of // the line // //----------------------------------------------------------------------------- LONG CRecalcLinePtr::CalcAlignedSitesAtBOL( CLSMeasurer * pme, CLineFull * pLineMeasured, UINT uiFlags, INT * piLine, LONG * pyHeight, LONG * pxWidth, LONG * pyAlignDescent, LONG * pxMaxLineWidth, BOOL * pfClearMarginsRequired) { CTreePos *ptp; ptp = pme->GetPtp(); if (ptp->IsText() && ptp->Cch()) { TCHAR ch = CTxtPtr(_pdp->GetMarkup(), pme->GetCp()).GetChar(); CTreeNode *pNode = pme->CurrBranch(); // Check to see whether this line begins with whitespace; // if it doesn't, or if it does but we're in a state where whitespace is significant // (e.g. inside a PRE tag), then by definition there are no aligned // sites at BOL (because there's something else there first). // Similar code is in CalcAlignedSitesAtBOLCore() for handling text // between aligned elements. if ( !IsWhite(ch) || pNode->GetParaFormat(LC_TO_FC(_pci->GetLayoutContext()))->HasInclEOLWhite( SameScope(pNode, pme->_pFlowLayout->ElementContent()) ) ) { *pfClearMarginsRequired = FALSE; return 0; } } return CalcAlignedSitesAtBOLCore(pme, pLineMeasured, uiFlags, piLine, pyHeight, pxWidth, pyAlignDescent, pxMaxLineWidth, pfClearMarginsRequired); } LONG CRecalcLinePtr::CalcAlignedSitesAtBOLCore( CLSMeasurer *pme, CLineFull *pLineMeasured, UINT uiFlags, INT *piLine, LONG *pyHeight, LONG *pxWidth, LONG *pyAlignDescent, LONG *pxMaxLineWidth, BOOL *pfClearMarginsRequired, BOOL fProcessOnce) // this parameter is added for print view support. It is TRUE when // the function is called to process Site Tasks for the block. In this // case we want only the first site to be processed. { CFlowLayout *pFlowLayout = _pdp->GetFlowLayout(); CElement *pElementFL = pFlowLayout->ElementContent(); const CCharFormat *pCF; // The char format LONG cpSave = pme->GetCp(); // Saves the cp the measurer is at CTreePos *ptpSave = pme->GetPtp(); BOOL fAnyAlignedSiteMeasured; // Did we measure any aligned site at all? CTreePos *ptpLayoutLast; CTreePos *ptp; LONG cp; CTreeNode *pNode; CElement *pElement; BOOL fInner; AssertSz(!(uiFlags & MEASURE_BREAKWORDS), "Cannot call CalcSitesAtBOL when we are hit testing!"); AssertSz(!fProcessOnce || (_pci->GetLayoutContext() && _pci->GetLayoutContext()->ViewChain()), "Improper usage of CalcAlignedSitesAtBOLCore parameters in non print view mode !!!"); // // By default, do not clear margins // *pfClearMarginsRequired = FALSE; fAnyAlignedSiteMeasured = FALSE; pFlowLayout->GetContentTreeExtent(NULL, &ptpLayoutLast); ptp = ptpSave; cp = cpSave; pNode = ptp->GetBranch(); pElement = pNode->Element(); pCF = pNode->GetCharFormat(LC_TO_FC(_pci->GetLayoutContext())); fInner = SameScope(pNode, pElementFL); for (;;) { pme->SetPtp(ptp, cp); if (ptp == ptpLayoutLast) break; if (ptp->IsPointer()) { ptp = ptp->NextTreePos(); continue; } if (ptp->IsNode()) { pNode = ptp->Branch(); pElement = pNode->Element(); fInner = SameScope(pNode, pElementFL); if (ptp->IsEndNode()) pNode = pNode->Parent(); if(pNode) pCF = pNode->GetCharFormat(LC_TO_FC(_pci->GetLayoutContext())); else break; } // // NOTE(SujalP): // pCF should never be NULL since though it starts out as NULL, it should // be initialized the first time around in the code above. It has happened // in stress once that pCF was NULL. Hence the check for pCF and the assert. // (Bug 18065). // AssertSz(pNode && pElement && pCF, "None of these should be NULL"); if (!(pNode && pElement && pCF)) break; if ( !_fIsEditable && ptp->IsBeginElementScope() && pCF->IsDisplayNone() ) { cp += pme->GetNestedElementCch(pNode->Element(), &ptp); cp -= ptp->GetCch(); } else if ( ptp->IsBeginElementScope() && pNode->ShouldHaveLayout() ) { pme->_fHasNestedLayouts = TRUE; pLineMeasured->_fHasNestedRunOwner |= pNode->Element()->IsRunOwner(); if (!pElement->IsInlinedElement(LC_TO_FC(_pci->GetLayoutContext()))) { // // Absolutely positioned sites are measured separately // inside the measurer. They also count as whitespace and // hence we will continue looking for aligned sites after // them at BOL. // if (!pNode->IsAbsolute(LC_TO_FC(_pci->GetLayoutContext()))) { CLineCore *pLine; // // Mark the line which will contain the WCH_EMBEDDING as having // an aligned site in it. // pLine = (*this)[*piLine]; pLine->_fHasAligned = TRUE; // // Measure the aligned site and create a line for it. // AlignObjects returns the number of clear lines, so we need // to add the number of clear lines + the aligned line that is // inserted to *piLine to make *piLine point to the text line // that contains the embedding characters for the aligned site. // *piLine += AlignObjects(pme, pLineMeasured, 1, TRUE, (uiFlags & MEASURE_BREAKATWORD) ? TRUE : FALSE, (uiFlags & MEASURE_MAXWIDTH) ? TRUE : FALSE, _iNewFirst, *piLine, pyHeight, *pxWidth, pyAlignDescent, pxMaxLineWidth); // // This the now the next available line, because we just inserted // a line for the aligned site. // (*piLine)++; // // Aligned objects change the available width for the line // *pxWidth = GetAvailableWidth(); // // This is ONLY used for DD. Weird, does it need to be that special? // _xLeadAdjust = 0; // // Also update the xLeft and xRight for the next line // to be inserted. // ApplyLineIndents(pNode, pLineMeasured, uiFlags, pme->_fPseudoElementEnabled); // // Remember we measured an aligned site in this pass // fAnyAlignedSiteMeasured = TRUE; } cp += pme->GetNestedElementCch(pElement, &ptp); cp -= ptp->GetCch(); } else { if (CheckForClear(pNode)) { *pfClearMarginsRequired = TRUE; } break; } } else if (ptp->IsText()) { CTxtPtr tp(_pdp->GetMarkup(), cp); // NOTE: Cch() could return 0 here but we should be OK with that. LONG cch = ptp->Cch(); BOOL fNonWhitePresent = FALSE; TCHAR ch; while (cch) { ch = tp.GetChar(); // // These characters need to be treated like whitespace // if (!( ch == _T(' ') || ( InRange(ch, TEXT('\t'), TEXT('\r')) && !pNode->GetParaFormat()->HasInclEOLWhite( SameScope(pNode, pme->_pFlowLayout->ElementContent())) ) ) ) { fNonWhitePresent = TRUE; break; } cch--; tp.AdvanceCp(1); } if (fNonWhitePresent) break; } else if ( ptp->IsEdgeScope() && pElement != pElementFL && ( pFlowLayout->IsElementBlockInContext(pElement) || pElement->Tag() == ETAG_BR ) ) { break; } else if ( ptp->IsBeginElementScope() && CheckForClear(pNode) ) { *pfClearMarginsRequired = TRUE; break; } if (fProcessOnce) break; // // Goto the next tree position // cp += ptp->GetCch(); ptp = ptp->NextTreePos(); } // // Restore the measurer to where it was when we came in // pme->SetPtp(ptpSave, cpSave); return fAnyAlignedSiteMeasured ? cp - cpSave : 0; } //+---------------------------------------------------------------------------- // // Member: CRecalcLinePtr::CheckForClear() // // Synopsis: CalcBeforeSpace set's up _fClearLeft & _fClearRight on the // _marginInfo, if a pNode is passed the use its clear flags, // check if we need to clear based on margins. // // Arguments: pNode - (optional) can be null. // // Returns: A bool indicating if clear is required. // //----------------------------------------------------------------------------- BOOL CRecalcLinePtr::CheckForClear(CTreeNode * pNode) { BOOL fClearLeft; BOOL fClearRight; if (pNode) { const CFancyFormat * pFF = pNode->GetFancyFormat(LC_TO_FC(_pci->GetLayoutContext())); fClearLeft = pFF->_fClearLeft; fClearRight = pFF->_fClearRight; } else { fClearLeft = _marginInfo._fClearLeft; fClearRight = _marginInfo._fClearRight; } _marginInfo._fClearLeft = _marginInfo._xLeftMargin && fClearLeft; _marginInfo._fClearRight = _marginInfo._xRightMargin && fClearRight; return _marginInfo._fClearLeft || _marginInfo._fClearRight; } //+---------------------------------------------------------------------------- // // Member: CRecalcLinePtr::FixupChunks // // Synopsis: If the current line has multiple chunks in the line (caused by // relative chunks), then break the line into multiple lines that // form a single screen line and fix up justification. // // REMINDER: RightToLeft lines measure from the right. Therefore, the // chunks need to be handled accordingly. //----------------------------------------------------------------------------- void CRecalcLinePtr::FixupChunks(CLSMeasurer &me, INT *piLine) { CLSLineChunk * plc = me._pLS->GetFirstChunk(); CLineCore * pliT = (*this)[*piLine]; CLineFull li = *pliT; LONG cchLeft = li._cch; LONG xWidthLeft = li._xWidth; LONG xPos = li._xLeft; // chunk position. note: if any BiDi is involved, // position is always taken from the chunk BOOL fFirstLine = TRUE; LONG iFirstChunk = *piLine; BOOL fBiDiLine = FALSE; // if all we have is one chunk in the line, we dont need to create // additional lines if(plc->_cch >= cchLeft) { li._fRelative = me._pLS->_pElementLastRelative != NULL; li._fPartOfRelChunk = TRUE; _pdp->NoteMost(&li); return; } while(plc || cchLeft) { BOOL fLastLine = !plc || cchLeft <= plc->_cch; CLineFull lifNew; // get x position from plc (if available) if (plc) { if (!plc->_fRTLChunk != !li.IsRTLLine()) fBiDiLine = TRUE; // limit xPos by line width (right-aligned lines may have hanging white space) LONG xPosNew = li._xLeft + min(li._xWidth, plc->_xLeft); #if DBG==1 // Assert that in strictly LTR case, current xPos matches the saved chunk position // TODO RTL 112514: make xPos calculation debug-only (when it works) AssertSz(li.IsRTLLine() || fBiDiLine || xPos == xPosNew || !IsTagEnabled(tagDebugRTL), // TODO RTL 112514: this fires in some LTR cases "chunk position doesn't match accumulated widh"); #endif xPos = xPosNew; } else { AssertSz(xWidthLeft <= 0 || !IsTagEnabled(tagDebugRTL), "no plc for a chunk, and it is not a trailing empty chunk"); } lifNew = li; lifNew._xLeft = xPos; if(!fFirstLine) { pliT = InsertLine(++(*piLine)); if (!pliT) break; // TODO RTL 112514: will bullets work with mixed-flow positioned lines? lifNew._fHasBulletOrNum = FALSE; lifNew._fFirstFragInLine = FALSE; } else { li.ReleaseOtherInfo(); lifNew._iLOI = -1; } lifNew._cch = min(cchLeft, long(plc ? plc->_cch : cchLeft)); lifNew._xWidth = plc ? min(long(plc->_xWidth), xWidthLeft) : xWidthLeft; lifNew._fRelative = plc ? plc->_fRelative : me._pLS->_pElementLastRelative != NULL; lifNew._fSingleSite = plc ? plc->_fSingleSite : me._pLS->_fLastChunkSingleSite; lifNew._fPartOfRelChunk = TRUE; lifNew._fHasEmbedOrWbr = li._fHasEmbedOrWbr; // TODO RTL 112514: First/last chunks must have correct xLeft, xRight, fCleanBefore, etc. // Calculations like CalcRectsOfRangeOnLine depend on that. // It is unlcear to me if this must be true for first/last rather or // leftmost/rightmost. Both seem to be unnecessary complex. Why can't all // chunks have same flags and consistent offsets? The chunks are merely duplicates // of the container line, nothing is important there beyond offset and width. if(fLastLine) { lifNew._cchWhite = min(lifNew._cch, long(li._cchWhite)); lifNew._xWhite = min(lifNew._xWidth, long(li._xWhite)); lifNew._xLineOverhang = li._xLineOverhang; lifNew._fClearBefore = li._fClearBefore; lifNew._fClearAfter = li._fClearAfter; lifNew._fForceNewLine = li._fForceNewLine; lifNew._fHasEOP = li._fHasEOP; lifNew._fHasBreak = li._fHasBreak; // TODO RTL 112514: // I would suppose that _xLineWidth should // always equal to conainer line, but some code // elsewhere only expects that from the last fragment. // If a middle fragment has width that matches container width, // it causes line borders to ignore right margin. lifNew._xLineWidth = li._xLineWidth; // TODO RTL 112514: // pure LTR case benefits from _xRight taken from original line // In other cases, we need to something trickier, and it is not quite working yet if(!li.IsRTLLine() && !fBiDiLine) lifNew._xRight = li._xRight; else { // calculate _xRight to match line width // TODO RTL 112514: // this may not work in tables // (because _xLineWidth is very big during min/max pass) lifNew._xRight = 0; lifNew._xRight = lifNew._xLineWidth - lifNew.CalcLineWidth(); Assert(lifNew._xRight >= 0 || !IsTagEnabled(tagDebugRTL)); } } else { lifNew._cchWhite = 0; lifNew._xWhite = 0; lifNew._xLineOverhang = 0; lifNew._fClearBefore = FALSE; lifNew._fClearAfter = FALSE; lifNew._fForceNewLine = FALSE; lifNew._fHasEOP = FALSE; lifNew._fHasBreak = FALSE; lifNew._xRight = 0; lifNew._xLineWidth = lifNew.CalcLineWidth(); } if ( !fFirstLine && _ptpStartForListItem ) { LONG cpLIStart = _ptpStartForListItem->GetCp(); LONG cpThisLine = me.GetCp() - cchLeft; LONG cchThisLine = lifNew._cch; if ( cpLIStart >= cpThisLine && cpLIStart < cpThisLine + cchThisLine ) { CLineCore * pli0 = (*this)[iFirstChunk]; lifNew._fHasBulletOrNum = pli0->_fHasBulletOrNum; pli0->_fHasBulletOrNum = FALSE; _ptpStartForListItem = NULL; } } fFirstLine = FALSE; plc = plc ? plc->_plcNext : NULL; xPos = lifNew._xLineWidth; // note: unused unless all LTR xWidthLeft -= lifNew._xWidth; cchLeft -= lifNew._cch; _pdp->NoteMost(&lifNew); pliT->AssignLine(lifNew); } } //+---------------------------------------------------------------------------- // // Member: CRecalcLinePtr::CalcParagraphSpacing // // Synopsis: Compute paragraph spacing for the current line // //----------------------------------------------------------------------------- CTreeNode * CRecalcLinePtr::CalcParagraphSpacing( CLSMeasurer *pMe, BOOL fFirstLineInLayout) { CTreePos *ptp = pMe->GetPtp(); CTreeNode *pNode; Assert( !ptp->IsBeginNode() || !_pdp->GetFlowLayout()->IsElementBlockInContext(ptp->Branch()->Element()) || !ptp->Branch()->Element()->IsInlinedElement() || pMe->_li._fFirstInPara || ptp->GetBranch()->Element()->IsOverlapped() ); // no bullet on the line pMe->_li._fHasBulletOrNum = FALSE; if (_fMoveBulletToNextLine) { pMe->_li._fHasBulletOrNum = TRUE; _fMoveBulletToNextLine = FALSE; _ptpStartForListItem = pMe->GetPtp(); } // Reset these flags for every line that we measure. _fNoMarginAtBottom = FALSE; // Only interesting for the first line of a paragraph. if (pMe->_li._fFirstInPara || pMe->_fLastWasBreak) { ptp = CalcBeforeSpace(pMe, fFirstLineInLayout); pMe->_li._yBeforeSpace = _lTopPadding + _lNegSpace + _lPosSpace; if (_pci->_smMode == SIZEMODE_MMWIDTH) { DWORD uTextAlignLast = ptp->GetBranch()->GetParaFormat(LC_TO_FC(_pci->GetLayoutContext()))->_uTextAlignLast; if ( uTextAlignLast != styleTextAlignLastNotSet && uTextAlignLast != styleTextAlignLastAuto ) { _pdp->SetLastLineAligned(); } } // // pre para space adjustment for print preview // { CFlowLayout * pFlowLayout = _pdp->GetFlowLayout(); Assert(pFlowLayout); if (pFlowLayout->ElementCanBeBroken()) { CLayoutContext * pLayoutContext = pFlowLayout->LayoutContext(); if (pLayoutContext && pLayoutContext->ViewChain()) { // adjust the Current y. pMe->_pci->_yConsumed += pMe->_li._yBeforeSpace; } } } } // Not at the beginning of a paragraph, we have no interline spacing. else { pMe->_li._yBeforeSpace = 0; } if(ptp) pNode = ptp->GetBranch(); else return NULL; pMe->MeasureSetPF(pNode->GetParaFormat(LC_TO_FC(_pci->GetLayoutContext())), SameScope(pNode, _pdp->GetFlowLayout()->ElementContent()), TRUE); return pNode; // formatting node } //+---------------------------------------------------------------------------- // // Member: CRecalcLinePtr::SetupMeasurerForBeforeSpace // // Synopsis: Setup the measurer so that it has all the post space info collected // from the previous line. This function is called only ONCE when // per recalclines loop. Subsequenlty we keep then spacing in sync // as we are measuring the lines. // // Returns: Nothing // //----------------------------------------------------------------------------- void CRecalcLinePtr::SetupMeasurerForBeforeSpace(CLSMeasurer *pMe, LONG yHeight) { CFlowLayout *pFlowLayout = _pdp->GetFlowLayout(); CElement *pElementFL = pFlowLayout->ElementContent(); LONG cpSave = pMe->GetCp(); CTreePos *ptp; CTreeNode *pNode; INSYNC(pMe); ResetPosAndNegSpace(); _pdp->EndNodeForLine(pMe->GetCp(), pMe->GetPtp(), _pci, NULL, &ptp, &pMe->_pLS->_pNodeForAfterSpace); if ( ptp != pMe->GetPtp() || pMe->_pLS->_pNodeForAfterSpace ) { pMe->SetPtp(ptp, -1); // // Having gone back to a point where there is some text or a layout(which // effectively means some text) we compute the "after" space. The point // which we go back to is effectively the point at which we would have // stopped measuring the previous line. // CalcAfterSpace(pMe, yHeight == 0, cpSave); } // // Be sure that calc after space gets us at the beginning of the // current line. If it leaves us before the current line then there is a // _VERY_ good chance that we will end up with more characters in the line // array than there are in the backing story. // Assert(pMe->GetCp() == cpSave); // initialize left and right padding & borderspace for parent block elements _xPadLeft = _xPadRight = _xBordLeft = _xBordRight = 0; _yPadTop = _yPadBottom = _yBordTop = _yBordBottom = 0; _xBordLeftPerLine = _xBordRightPerLine = _xPadLeftPerLine = _xPadRightPerLine = 0; pNode = pMe->CurrBranch(); // Measurer can be initialized for any line in the line array, so // compute the border and padding for all the block elements that // are currently in scope. if(DifferentScope(pNode, pElementFL)) { CDoc * pDoc = pFlowLayout->Doc(); CTreeNode * pNodeTemp; CElement * pElement; pNodeTemp = pMe->GetPtp()->IsBeginElementScope() ? pNode->Parent() : pNode; while( pNodeTemp && DifferentScope(pNodeTemp, pElementFL)) { pElement = pNodeTemp->Element(); if( !pNodeTemp->ShouldHaveLayout() && pNodeTemp->GetCharFormat()->HasPadBord(FALSE) && pFlowLayout->IsElementBlockInContext(pElement)) { const CFancyFormat * pFF = pNodeTemp->GetFancyFormat(); const CCharFormat * pCF = pNodeTemp->GetCharFormat(); LONG lFontHeight = pCF->GetHeightInTwips(pDoc); BOOL fNodeVertical = pCF->HasVerticalLayoutFlow(); BOOL fWritingModeUsed = pCF->_fWritingModeUsed; if ( !pElement->_fDefinitelyNoBorders ) { CBorderInfo borderinfo; pElement->_fDefinitelyNoBorders = !GetBorderInfoHelper( pNodeTemp, _pci, &borderinfo, GBIH_NONE ); if ( !pElement->_fDefinitelyNoBorders ) { _xBordLeftPerLine += borderinfo.aiWidths[SIDE_LEFT]; _xBordRightPerLine += borderinfo.aiWidths[SIDE_RIGHT]; } } _xPadLeftPerLine += pFF->GetLogicalPadding(SIDE_LEFT, fNodeVertical, fWritingModeUsed).XGetPixelValue( _pci, _pci->_sizeParent.cx, lFontHeight); _xPadRightPerLine += pFF->GetLogicalPadding(SIDE_RIGHT, fNodeVertical, fWritingModeUsed).XGetPixelValue( _pci, _pci->_sizeParent.cx, lFontHeight); } pNodeTemp = pNodeTemp->Parent(); } _xBordLeft = _xBordLeftPerLine; _xBordRight = _xBordRightPerLine; _xPadLeft = _xPadLeftPerLine; _xPadRight = _xPadRightPerLine; } INSYNC(pMe); return; } //+---------------------------------------------------------------------------- // // Member: CRecalcLinePtr::CalcAfterSpace // // Synopsis: This function computes the after space of the line and adds // on the extra characters at the end of the line. Also positions // the measurer correctly (to the ptp at the ptp belonging to // the first character in the next line). // // Returns: Nothing // //----------------------------------------------------------------------------- void CRecalcLinePtr::CalcAfterSpace(CLSMeasurer *pMe, BOOL fFirstLineInLayout, LONG cpMax) { CFlowLayout *pFlowLayout = _pdp->GetFlowLayout(); CTreeNode *pNode; CElement *pElement; CTreePos *ptpStop; CTreePos *ptp; CUnitValue cuv; LONG cpCurrent; BOOL fConsumedFirstOne = pMe->_fEndSplayNotMeasured; BOOL fContinueLooking = TRUE; BOOL fConsumedBlockElement = FALSE; LONG cchInPtp; INSYNC(pMe); if (pMe->_li._fForceNewLine) { ResetPosAndNegSpace(); } if (pMe->_pLS->_pNodeForAfterSpace) { BOOL fConsumed; CollectSpaceInfoFromEndNode(pMe, pMe->_pLS->_pNodeForAfterSpace, fFirstLineInLayout, FALSE, &fConsumed); } Assert(_yPadBottom == 0); Assert(_yBordBottom == 0); ptpStop = pMe->_pLS->_treeInfo._ptpLayoutLast; #if DBG==1 { CTreePos *ptpStartDbg; CTreePos *ptpStopDbg; pFlowLayout->GetContentTreeExtent(&ptpStartDbg, &ptpStopDbg); Assert(ptpStop == ptpStopDbg); } #endif for (cpCurrent = pMe->GetCp(), ptp = pMe->GetPtp(); ptp && cpCurrent < cpMax && fContinueLooking; ptp = ptp->NextTreePos()) { cchInPtp = ptp->GetCch(); if (cchInPtp == 0) { Assert( ptp->IsPointer() || ptp->IsText() || !ptp->IsEdgeScope() ); continue; } if (ptp == ptpStop) break; Assert(cpCurrent >= ptp->GetCp() && cpCurrent < ptp->GetCp() + ptp->GetCch()); if (ptp->IsNode()) { Assert(ptp->IsEdgeScope()); pNode = ptp->Branch(); pElement = pNode->Element(); const CCharFormat *pCF = pNode->GetCharFormat(LC_TO_FC(_pci->GetLayoutContext())); if (ptp->IsEndNode()) { // // NOTE(SujalP): // If we had stopped because we had a line break then I cannot realistically // consume the end block element on this line. This would break editing when // the user hit shift-enter to put in a BR -- the P tag I was under has to // end in the next line since that is where the user wanted to see the caret. // IE bug 44561 // if (pMe->_fLastWasBreak && _fIsEditable) break; if (pFlowLayout->IsElementBlockInContext(pElement)) { const CFancyFormat * pFF = pNode->GetFancyFormat(); pMe->_li._fHasEOP = TRUE; ENI_RETVAL retVal = CollectSpaceInfoFromEndNode(pMe, pNode, fFirstLineInLayout, FALSE, &fConsumedBlockElement); if (retVal == ENI_CONSUME_TERMINATE) { fContinueLooking = FALSE; } else if (retVal == ENI_TERMINATE) { fContinueLooking = FALSE; break; } _fNoMarginAtBottom = pElement->Tag() == ETAG_P && pElement->_fExplicitEndTag && !pFF->HasExplicitLogicalMargin(SIDE_BOTTOM, pCF->HasVerticalLayoutFlow(), pCF->_fWritingModeUsed); } // Else do nothing, just continue looking ahead // Just verifies that an element is block within itself. Assert(ptp != ptpStop); } else if (ptp->IsBeginNode()) { if (pCF->IsDisplayNone()) { LONG cchHidden = pMe->GetNestedElementCch(pElement, &ptp); // Ptp gets updated inside GetNestedElementCch, so be sure to // update cchInPtp too cchInPtp = ptp->GetCch(); // Since we update the count below for everything, lets dec the // count over here. cchHidden -= cchInPtp; // Add the characters to the line. pMe->_li._cch += cchHidden; // Also add them to the whitespace of the line pMe->_li._cchWhite += (SHORT)cchHidden; // Add to cpCurrent cpCurrent += cchHidden; } // We need to stop when we see a new block element else if (pFlowLayout->IsElementBlockInContext(pElement)) { pMe->_li._fHasEOP = TRUE; break; } // Or a new layout (including aligned ones, since these // will now live on lines of their own. else if (pNode->ShouldHaveLayout(LC_TO_FC(_pci->GetLayoutContext())) || pNode->IsRelative(LC_TO_FC(_pci->GetLayoutContext()))) break; else if (pElement->Tag() == ETAG_BR) break; else if (!pNode->Element()->IsNoScope()) break; } if (_fIsEditable ) { if (fConsumedFirstOne && ptp->ShowTreePos()) break; else fConsumedFirstOne = TRUE; } } else { Assert(ptp->IsText() && ptp->Cch() != 0); break; } Assert(cchInPtp == ptp->GetCch()); // Add the characters to the line. pMe->_li._cch += cchInPtp; // Also add them to the whitespace of the line Assert((LONG)pMe->_li._cchWhite + cchInPtp < SHRT_MAX); pMe->_li._cchWhite += (SHORT)cchInPtp; // Add to cpCurrent cpCurrent += cchInPtp; } pMe->_fEmptyLineForPadBord = !fContinueLooking; // The last paragraph of a layout shouldn't have this flag set if( ptp == ptpStop ) pMe->_li._fHasEOP = FALSE; if (pMe->GetPtp() != ptp) pMe->SetPtp(ptp, cpCurrent); INSYNC(pMe); } //+---------------------------------------------------------------------------- // // Member: CRecalcLinePtr::CalcBeforeSpace // // Synopsis: This function computes the before space of the line and remembers // the characters it has gone past in _li._cch. // // Also computes border and padding (left and right too!) for // elements coming into scope. // // Returns: Nothing // //----------------------------------------------------------------------------- CTreePos * CRecalcLinePtr::CalcBeforeSpace(CLSMeasurer *pMe, BOOL fFirstLineInLayout) { const CFancyFormat * pFF; const CParaFormat * pPF; const CCharFormat * pCF; CFlowLayout *pFlowLayout = _pdp->GetFlowLayout(); CDoc *pDoc = pFlowLayout->Doc(); CTreeNode *pNode = NULL; CElement *pElement; CTreePos *ptpStop; CTreePos *ptp; CTreePos *ptpFormatting = NULL; BOOL fSeenBeginBlockTag = FALSE; BOOL fContinueLooking = TRUE; pMe->_fSeenAbsolute = FALSE; ptpStop = pMe->_pLS->_treeInfo._ptpLayoutLast; #if DBG==1 { CTreePos *ptpStartDbg; CTreePos *ptpStopDbg; pFlowLayout->GetContentTreeExtent(&ptpStartDbg, &ptpStopDbg); Assert(ptpStop == ptpStopDbg); } #endif _xBordLeftPerLine = _xBordRightPerLine = _xPadLeftPerLine = _xPadRightPerLine = 0; pMe->_fEmptyLineForPadBord = FALSE; if (fFirstLineInLayout) { LONG lPadding[SIDE_MAX]; _pdp->GetPadding(_pci, lPadding, _pci->_smMode == SIZEMODE_MMWIDTH); if (pFlowLayout->ElementContent()->TestClassFlag(CElement::ELEMENTDESC_TABLECELL)) { _lTopPadding = lPadding[SIDE_TOP]; } else { _lPosSpace = max(_lPosSpace, lPadding[SIDE_TOP]); _lNegSpace = min(_lNegSpace, lPadding[SIDE_TOP]); _lTopPadding = 0; } } else _lTopPadding = 0; for (ptp = pMe->GetPtp(); fContinueLooking; ptp = ptp->NextTreePos()) { if(!ptp) break; if (ptp->IsPointer()) continue; if (ptp == ptpStop) break; if (ptp->IsNode()) { if (_fIsEditable && ptp->ShowTreePos()) pMe->_fMeasureFromTheStart = TRUE; pNode = ptp->Branch(); pElement = pNode->Element(); BOOL fShouldHaveLayout = pNode->ShouldHaveLayout(LC_TO_FC(_pci->GetLayoutContext())); if (pNode->HasInlineMBP(LC_TO_FC(_pci->GetLayoutContext()))) pMe->_fMeasureFromTheStart = TRUE; if (ptp->IsEndElementScope()) { if(pNode->IsRelative() && !fShouldHaveLayout) pMe->_fRelativePreChars = TRUE; if (pFlowLayout->IsElementBlockInContext(pElement)) { // // If we encounter a break on empty block end tag, then we should // give vertical space otherwise a <X*></X> where X is a block element // will not produce any vertical space. (Bug 45291). // if ( pElement->_fBreakOnEmpty && ( fSeenBeginBlockTag || ( pMe->_fLastWasBreak && _fIsEditable ) ) ) { break; } if (pMe->_fSeenAbsolute) break; // // If we are at an end LI it means that we have an // empty LI for which we need to create an empty // line. Hence we just break out of here. We will // fall into the measurer with the ptp positioned // at the end splay. The measurer will immly bail // out, creating an empty line. CalcAfterSpace will // go and then add the node char for the end LI to // the line. // if ( IsGenericListItem(pNode) && ( pMe->_li._fHasBulletOrNum || ( pMe->_fLastWasBreak && _fIsEditable ) ) ) { break; } // // Collect space info from the end node *only* if the previous // line does not end in a BR. If it did, then the end block // tag after does not contribute to the inter-paraspacing. // (Remember, that a subsequent begin block tag will still // contribute to the spacing!) // else if (!_fIsEditable || !pMe->_fLastWasBreak) { ENI_RETVAL retVal = CollectSpaceInfoFromEndNode(pMe, pNode, fFirstLineInLayout, TRUE, NULL); if (retVal == ENI_CONSUME_TERMINATE) { fContinueLooking = FALSE; } else if (retVal == ENI_TERMINATE) { pMe->_li._fIsPadBordLine = TRUE; fContinueLooking = FALSE; break; } } } // Else do nothing, just continue looking ahead // Just verifies that an element is block within itself. Assert(ptp != ptpStop); } else if (ptp->IsBeginElementScope()) { pCF = pNode->GetCharFormat(LC_TO_FC(_pci->GetLayoutContext())); pFF = pNode->GetFancyFormat(LC_TO_FC(_pci->GetLayoutContext())); pPF = pNode->GetParaFormat(LC_TO_FC(_pci->GetLayoutContext())); BOOL fNodeVertical = pCF->HasVerticalLayoutFlow(); BOOL fWritingModeUsed = pCF->_fWritingModeUsed; if (pCF->IsDisplayNone()) { // The extra one is added in the normal processing. pMe->_li._cch += pMe->GetNestedElementCch(pElement, &ptp); pMe->_li._cch -= ptp->GetCch(); } else if (pElement->Tag() == ETAG_BR) { break; } else { BOOL fBlockElement = pFlowLayout->IsElementBlockInContext(pElement); if(pNode->IsRelative(LC_TO_FC(_pci->GetLayoutContext())) && !fShouldHaveLayout) pMe->_fRelativePreChars = TRUE; if( (pFF->_fClearLeft || pFF->_fClearRight) // IE6 #32464 // Setting this bit will cause a cleared element to go searching for a text // line anchor. ON a new page, this won't exist, and the clear info is already // implicit in the page break. && !( _pci->GetLayoutContext() && _pci->GetLayoutContext()->ViewChain() && !_pci->_fHasContent ) ) { _marginInfo._fClearLeft |= pFF->_fClearLeft; _marginInfo._fClearRight |= pFF->_fClearRight; } if ( fBlockElement && pElement->IsInlinedElement()) { fSeenBeginBlockTag = TRUE; if (pMe->_fSeenAbsolute) break; LONG lFontHeight = pCF->GetHeightInTwips(pDoc); if (pElement->HasFlag(TAGDESC_LIST)) { Assert(pElement->IsBlockElement(LC_TO_FC(_pci->GetLayoutContext()))); if (pMe->_li._fHasBulletOrNum) { ptpFormatting = ptp; do { ptpFormatting = ptpFormatting->PreviousTreePos(); } while (ptpFormatting->GetCch() == 0); break; } } // // NOTE(SujalP): Bug 38806 points out a problem where an // abs pos'd LI does not have a bullet follow it. To fix that // one we decided that we will _not_ draw the bullet for LI's // with layout (&& !fHasLayout). However, 61373 and its dupes // indicate that this is overly restrictive. So we will change // this case and not draw a bullet for only abspos'd LI's. // else if ( IsListItem(pNode) && !pNode->IsAbsolute() ) { Assert(pElement->IsBlockElement(LC_TO_FC(_pci->GetLayoutContext()))); pMe->_li._fHasBulletOrNum = TRUE; _ptpStartForListItem = ptp; } // if a dd is comming into scope and is a // naked DD, then compute the first line indent if( pElement->Tag() == ETAG_DD && pPF->_fFirstLineIndentForDD) { CUnitValue cuv; cuv.SetPoints(LIST_INDENT_POINTS); _xLeadAdjust += cuv.XGetPixelValue(_pci, 0, 1); } // if a block element is comming into scope, it better be // the first line in the paragraph. Assert(pMe->_li._fFirstInPara || pMe->_fLastWasBreak); pMe->_li._fFirstInPara = TRUE; // compute padding and border height for the elements comming // into scope if( !fShouldHaveLayout && pCF->HasPadBord(FALSE)) { LONG yPadTop; const CUnitValue & cuvPaddingLeft = pFF->GetLogicalPadding(SIDE_LEFT, fNodeVertical, fWritingModeUsed); const CUnitValue & cuvPaddingRight = pFF->GetLogicalPadding(SIDE_RIGHT, fNodeVertical, fWritingModeUsed); if ( !pElement->_fDefinitelyNoBorders ) { CBorderInfo borderinfo; pElement->_fDefinitelyNoBorders = !GetBorderInfoHelper( pNode, _pci, &borderinfo, GBIH_NONE ); if ( !pElement->_fDefinitelyNoBorders ) { // If the blockelement has any border (or padding) and the // top padding is non zero then we need to // create a line to draw the border. The line // will just contain the start of the block element. // Similar thing happens at the end of the block element. if (borderinfo.aiWidths[SIDE_TOP]) { fContinueLooking = FALSE; _yBordTop += borderinfo.aiWidths[SIDE_TOP]; } _xBordLeftPerLine += borderinfo.aiWidths[SIDE_LEFT]; _xBordRightPerLine += borderinfo.aiWidths[SIDE_RIGHT]; } } yPadTop = pFF->GetLogicalPadding(SIDE_TOP, fNodeVertical, fWritingModeUsed).YGetPixelValue( _pci, _pci->_sizeParent.cx, lFontHeight); if (yPadTop) { fContinueLooking = FALSE; _yPadTop += yPadTop; } _xPadLeftPerLine += cuvPaddingLeft.XGetPixelValue(_pci, _pci->_sizeParent.cx, lFontHeight); _xPadRightPerLine += cuvPaddingRight.XGetPixelValue(_pci, _pci->_sizeParent.cx, lFontHeight); // If we have horizontal padding in percentages, flag the display // so it can do a full recalc pass when necessary (e.g. parent width changes) // Also see ApplyLineIndents() where we do this for horizontal indents. if (cuvPaddingLeft.IsPercent() || cuvPaddingRight.IsPercent()) { _pdp->_fContainsHorzPercentAttr = TRUE; } } // // CSS attributes page break before/after support. // There are two mechanisms that add to provide full support: // 1. CRecalcLinePtr::CalcBeforeSpace() and CRecalcLinePtr::CalcAfterSpace() // is used to set CLineCore::_fPageBreakBefore/After flags only(!) for // nested elements which have no their own layout (i.e. paragraphs). // 2. CEmbeddedILSObj::Fmt() sets CLineCore::_fPageBreakBefore for nested // element with their own layout that are NOT allowed to break (always) // and for nested elements with their own layout that ARE allowed to // break if this is the first layout in the view chain. // if ( // print view _pci->GetLayoutContext() && _pci->GetLayoutContext()->ViewChain() // and element is nested element without a layout && !fShouldHaveLayout ) { // does any block elements comming into scope force a // page break before this line if (GET_PGBRK_BEFORE(pFF->_bPageBreaks)) { CLayoutBreak * pLayoutBreak; pMe->_li._fPageBreakBefore = TRUE; _pci->_fPageBreakLeft |= IS_PGBRK_BEFORE_OF_STYLE(pFF->_bPageBreaks, stylePageBreakLeft); _pci->_fPageBreakRight |= IS_PGBRK_BEFORE_OF_STYLE(pFF->_bPageBreaks, stylePageBreakRight); _pci->GetLayoutContext()->GetEndingLayoutBreak(pFlowLayout->ElementOwner(), &pLayoutBreak); if (pLayoutBreak) { DYNCAST(CFlowLayoutBreak, pLayoutBreak)->_pElementPBB = pElement; } } } // If we're the first line in the scope, we only care about our // pre space if it has been explicitly set. if (( !pMe->_li._fHasBulletOrNum && !fFirstLineInLayout ) || pFF->HasExplicitLogicalMargin(SIDE_TOP, fNodeVertical, fWritingModeUsed) ) { // If this is in a PRE block, then we have no // interline spacing. if (!( pNode->Parent() && pNode->Parent()->GetParaFormat(LC_TO_FC(_pci->GetLayoutContext()))->HasPre(FALSE) ) ) { LONG lTemp; lTemp = pFF->_cuvSpaceBefore.YGetPixelValue(_pci, _pci->_sizeParent.cx, lFontHeight); // Maintain the positives. _lPosSpace = max(lTemp, _lPosSpace); // Keep the negatives separately. _lNegSpace = min(lTemp, _lNegSpace); } } } else if (!fBlockElement) { if (pCF->_fHasInlineBg) { pMe->_fMeasureFromTheStart = TRUE; } } // // If we have hit a nested layout then we quit so that it can be measured. // Note that we have noted the before space the site contributes in the // code above. // // Absolute positioned nested layouts at BOL are a part of the pre-chars // of the line. We also skip over them in FormattingNodeForLine. // if (fShouldHaveLayout) { pMe->_fHasNestedLayouts = TRUE; // // Should never be here for hidden layouts. They should be // skipped over earlier in this function. // Assert(!pCF->IsDisplayNone()); if (pNode->IsAbsolute(LC_TO_FC(_pci->GetLayoutContext()))) { LONG cchElement = pMe->GetNestedElementCch(pElement, &ptp); pMe->_fSeenAbsolute = TRUE; // The extra one is added in the normal processing. pMe->_li._cch += cchElement - ptp->GetCch(); pMe->_cchAbsPosdPreChars += cchElement; } else { break; } } } } } else { Assert(ptp->IsText()); if (ptp->Cch()) break; } pMe->_li._cch += ptp->GetCch(); } pMe->_fEmptyLineForPadBord = !fContinueLooking; if (ptp != pMe->GetPtp()) pMe->SetPtp(ptp, -1); _xBordLeft += _xBordLeftPerLine; _xBordRight += _xBordRightPerLine; _xPadLeft += _xPadLeftPerLine; _xPadRight += _xPadRightPerLine; return ptpFormatting ? ptpFormatting : ptp; } //+---------------------------------------------------------------------------- // // Member: CRecalcLinePtr::CollectSpaceInfoFromEndNode // // Synopsis: Computes the space info when we are at the end of a block element. // // Returns: A BOOL indicating if any space info was collected. // //----------------------------------------------------------------------------- ENI_RETVAL CRecalcLinePtr::CollectSpaceInfoFromEndNode( CLSMeasurer *pMe, CTreeNode * pNode, BOOL fFirstLineInLayout, BOOL fPadBordForEmptyBlock, BOOL * pfConsumedBlockElement) { Assert(pNode); ENI_RETVAL retVal = ENI_CONTINUE; const CFancyFormat *pFF = pNode->GetFancyFormat(LC_TO_FC(_pci->GetLayoutContext())); const CCharFormat *pCF = pNode->GetCharFormat(LC_TO_FC(_pci->GetLayoutContext())); BOOL fNodeVertical = pCF->HasVerticalLayoutFlow(); BOOL fWritingModeUsed = pCF->_fWritingModeUsed; CUnitValue cuv; Assert( _pdp->GetFlowLayout()->IsElementBlockInContext(pNode->Element()) || pNode->Element()->IsOwnLineElement(_pdp->GetFlowLayout()) ); CElement *pElement = pNode->Element(); CDoc *pDoc = pElement->Doc(); BOOL fPadBord = pCF->HasPadBord(FALSE); BOOL fShouldHaveLayout = pNode->ShouldHaveLayout(LC_TO_FC(_pci->GetLayoutContext())); // compute any padding or border height from elements // going out of scope if( !fShouldHaveLayout && fPadBord) { LONG lFontHeight = pCF->GetHeightInTwips(pDoc); LONG xBordLeft, xBordRight, xPadLeft, xPadRight; xBordLeft = xBordRight = xPadLeft = xPadRight = 0; if ( !pElement->_fDefinitelyNoBorders ) { CBorderInfo borderinfo; pElement->_fDefinitelyNoBorders = !GetBorderInfoHelper( pNode, _pci, &borderinfo, GBIH_NONE ); if ( !pElement->_fDefinitelyNoBorders ) { if (borderinfo.aiWidths[SIDE_BOTTOM]) { // If we are called from CalcBeforeSpace, and we run into an end node // which has border, then just terminate without processing the node // (ie dont collect spacing info, dont consume the character, dont // modify xBordLeft/xBordRight etc). This is because this node should // be consume in *CalcAfterSpace* since the width of the bottom border // needs to be added into _yBordBottom -- which will eventually find // its way into the descent of the line. This way we will get a line // similar to others, except its natural height will be 0, but will /// will eventually get a height after CalcAfterSpace is called. if(fPadBordForEmptyBlock) { // Cause the line to be no more than just this /div character retVal = ENI_TERMINATE; } // We got here during CalcBeforeSpace. 2 cases are worth mentioning: // 1) There was text before this ptp, which was collected during // measuring the line. // 2) We got here because measure line terminated right away because // it saw an end splay without seeing any characters. This would // happen if the line begins with a end splay (CalcBeforeSpace // would have terminated right away as we saw before). else { Assert(pfConsumedBlockElement); // Now, if during CalcAfterSpace, we saw an end block (block element A) // ptp which did not have a bottom border (in which case // *pfConsumeBlockElement will be TRUE) and then we see an end block // (block element B) ptp which had a bottom border then we should // terminate the line without consuming the end splay, since all the // content on the line belongs to block element A and putting more // content on the same line from block element B is incorrect (remember // rendered border constitues content). // Also note, that CalcAfterSpace always stops when it sees a beging // ptp for a block element. Hence *pfConsumedBlockElement is only // telling us whether we have seen an end ptp of a block element. if (*pfConsumedBlockElement) { retVal = ENI_TERMINATE; } // Finally, we have seen an end block element which has a bottom // border. Consume it and stop further consumption, since we cannot // add more stuff on this line now. else { _yBordBottom += borderinfo.aiWidths[SIDE_BOTTOM]; retVal = ENI_CONSUME_TERMINATE; } } } // Remember, if we are not consuming the character, we should not // adjust the borders. if (retVal != ENI_TERMINATE) { xBordLeft = borderinfo.aiWidths[SIDE_LEFT]; xBordRight = borderinfo.aiWidths[SIDE_RIGHT]; } } } // The same argument as for borders is valid for padding too. LONG yPadBottom = pFF->GetLogicalPadding(SIDE_BOTTOM, fNodeVertical, fWritingModeUsed).YGetPixelValue( _pci, _pci->_sizeParent.cx, lFontHeight); if (yPadBottom) { if(fPadBordForEmptyBlock) { retVal = ENI_TERMINATE; } else { Assert(pfConsumedBlockElement); if (*pfConsumedBlockElement) { retVal = ENI_TERMINATE; } else { _yPadBottom += yPadBottom; retVal = ENI_CONSUME_TERMINATE; } } } if (retVal != ENI_TERMINATE) { xPadLeft = pFF->GetLogicalPadding(SIDE_LEFT, fNodeVertical, fWritingModeUsed).XGetPixelValue( _pci, _pci->_sizeParent.cx, lFontHeight); xPadRight = pFF->GetLogicalPadding(SIDE_RIGHT, fNodeVertical, fWritingModeUsed).XGetPixelValue( _pci, _pci->_sizeParent.cx, lFontHeight); } // // If fPadBordForEmptyBlock is true it means that we are called from CalcBeforeSpace. // During CalcBeforeSpace, the padding and border is collected in the per-line variables // and then accounted into _x[Pad|Bord][Left|Right] variables at the end of the call. // Hence when we are measuring for empty block elements, we remove their padding // and border from the perline varaibles, but when we are called from CalcAfterSpace // we remove it from the actual _x[Pad|Bord][Left|Right] variables. // if (fPadBordForEmptyBlock) { _xBordLeftPerLine -= xBordLeft; _xBordRightPerLine -= xBordRight; _xPadLeftPerLine -= xPadLeft; _xPadRightPerLine -= xPadRight; } else { _xBordLeft -= xBordLeft; _xBordRight -= xBordRight; _xPadLeft -= xPadLeft; _xPadRight -= xPadRight; } } if ( !fFirstLineInLayout && retVal != ENI_TERMINATE ) { if (pfConsumedBlockElement) *pfConsumedBlockElement = TRUE; // Treading the fine line of Nav3, Nav4 and IE3 compat, // we include the bottom margin as long as we're not // the last line in the text site or not a P tag. This // is broadly Nav4 compatible. if ( pElement->_fExplicitEndTag || pFF->HasExplicitLogicalMargin(SIDE_BOTTOM, fNodeVertical, fWritingModeUsed) ) { // Deal with things proxied around text sites differently, // so we need to know when we're above the containing site. //if (pElement->GetLayout() == pFlowLayout) //break; // If this is in a PRE block, then we have no // interline spacing. if (!( pNode->Parent() && pNode->Parent()->GetParaFormat()->HasPre(TRUE) ) ) { LONG lTemp; cuv = pFF->_cuvSpaceAfter; lTemp = cuv.YGetPixelValue(_pci, _pci->_sizeParent.cx, pNode->GetFontHeightInTwips(&cuv)); _lPosSpace = max(lTemp, _lPosSpace); _lNegSpace = min(lTemp, _lNegSpace); if (pElement->Tag() != ETAG_P || pFF->HasExplicitLogicalMargin(SIDE_BOTTOM, fNodeVertical, fWritingModeUsed)) { _lPosSpaceNoP = max(lTemp, _lPosSpaceNoP); _lNegSpaceNoP = min(lTemp, _lNegSpaceNoP); } } } } // // CSS attributes page break before/after support. // There are two mechanisms that add to provide full support: // 1. CRecalcLinePtr::CalcBeforeSpace() and CRecalcLinePtr::CalcAfterSpace() // is used to set CLineCore::_fPageBreakBefore/After flags only(!) for // nested elements which have no their own layout (i.e. paragraphs). // 2. CEmbeddedILSObj::Fmt() sets CLineCore::_fPageBreakBefore for nested // element with their own layout that are NOT allowed to break (always) // and for nested elements with their own layout that ARE allowed to // break if this is the first layout in the view chain. // if ( // print view _pci->GetLayoutContext() && _pci->GetLayoutContext()->ViewChain() // and element is nested element without a layout && !fShouldHaveLayout ) { // does any blocks going out of scope force a page break if (fPadBordForEmptyBlock) { if (GET_PGBRK_AFTER(pFF->_bPageBreaks)) { CLayoutBreak * pLayoutBreak; // if this is an empty block set page break BEFORE for the line pMe->_li._fPageBreakBefore = TRUE; _pci->GetLayoutContext()->GetEndingLayoutBreak(_pdp->GetFlowLayout()->ElementOwner(), &pLayoutBreak); if (pLayoutBreak) { DYNCAST(CFlowLayoutBreak, pLayoutBreak)->_pElementPBB = pElement; } } } else { pMe->_li._fPageBreakAfter |= !!GET_PGBRK_AFTER(pFF->_bPageBreaks); } _pci->_fPageBreakLeft |= IS_PGBRK_AFTER_OF_STYLE(pFF->_bPageBreaks, stylePageBreakLeft); _pci->_fPageBreakRight |= IS_PGBRK_AFTER_OF_STYLE(pFF->_bPageBreaks, stylePageBreakRight); } return retVal; } BOOL CRecalcLinePtr::AlignFirstLetter(CLSMeasurer *pme, int iLineStart, int iLineFirst, LONG *pyHeight, LONG *pyAlignDescent, CTreeNode *pNodeFormatting ) { BOOL fRet = FALSE; LONG yHeight = *pyHeight; CLineFull lif; CLineCore *pli; CTreeNode *pNode; LONG yBS = pme->_li._yBeforeSpace; Assert(pme->_li._fHasFirstLetter); Assert(pme->_li._fHasFloatedFL); Assert(!pme->_li.IsFrame()); pNode = _pdp->GetMarkup()->SearchBranchForBlockElement(pNodeFormatting, pme->_pFlowLayout); Assert(pNode); Assert(pNode->GetFancyFormat()->_fHasFirstLetter); Reset(iLineStart); for (LONG i = 0; i < pme->_aryFLSlab.Size(); i++) { pli = AddLine(); if (!pli) goto Cleanup; lif = pme->_li; lif._iLOI = -1; lif._fLeftAligned = TRUE; lif._cchFirstLetter = lif._cch - lif._cchWhite; lif._cch = 0; lif._cchWhite = 0; lif._fClearBefore = i > 0; lif._fClearAfter = FALSE; lif._xLineWidth = (lif._xWidth - pme->_aryFLSlab[i]._xWidth) + lif._xLeft; lif._fFrameBeforeText = FALSE; lif._pNodeForFirstLetter = pNode; lif._yBeforeSpace = yBS; if (pme->_aryFLSlab.Size() > 1) lif._yHeight = pme->_aryFLSlab[i]._yHeight + yBS; yBS += pme->_aryFLSlab[i]._yHeight; pli->AssignLine(lif); if (i == 0) { _marginInfo._xLeftMargin += lif._xLineWidth; _marginInfo._fAddLeftFrameMargin = FALSE; _marginInfo._yLeftMargin = yHeight + lif._yHeight; } if (yHeight + lif._yHeight > _marginInfo._yBottomLeftMargin) { _marginInfo._yBottomLeftMargin = yHeight + lif._yHeight; if (yHeight + lif._yHeight > *pyAlignDescent) { *pyAlignDescent = yHeight + lif._yHeight; } } } fRet = TRUE; Cleanup: return fRet; } CSaveRLP::CSaveRLP(CRecalcLinePtr *prlp) { Assert(prlp); _prlp = prlp; _marginInfo = prlp->_marginInfo; _xLeadAdjust = prlp->_xLeadAdjust; _xBordLeftPerLine = prlp->_xBordLeftPerLine; _xBordLeft = prlp->_xBordLeft; _xBordRightPerLine = prlp->_xBordRightPerLine; _xBordRight = prlp->_xBordRight; _yBordTop = prlp->_yBordTop; _yBordBottom = prlp->_yBordBottom; _xPadLeftPerLine = prlp->_xPadLeftPerLine; _xPadLeft = prlp->_xPadLeft; _xPadRightPerLine = prlp->_xPadRightPerLine; _xPadRight = prlp->_xPadRight; _yPadTop = prlp->_yPadTop; _yPadBottom = prlp->_yPadBottom; _ptpStartForListItem = prlp->_ptpStartForListItem; _lTopPadding = prlp->_lTopPadding; _lPosSpace = prlp->_lPosSpace; _lNegSpace = prlp->_lNegSpace; _lPosSpaceNoP = prlp->_lPosSpaceNoP; _lNegSpaceNoP = prlp->_lNegSpaceNoP; } CSaveRLP::~CSaveRLP() { Assert(_prlp); _prlp->_marginInfo = _marginInfo; _prlp->_xLeadAdjust = _xLeadAdjust; _prlp->_xBordLeftPerLine = _xBordLeftPerLine; _prlp->_xBordLeft = _xBordLeft; _prlp->_xBordRightPerLine = _xBordRightPerLine; _prlp->_xBordRight = _xBordRight; _prlp->_yBordTop = _yBordTop; _prlp->_yBordBottom = _yBordBottom; _prlp->_xPadLeftPerLine = _xPadLeftPerLine; _prlp->_xPadLeft = _xPadLeft; _prlp->_xPadRightPerLine = _xPadRightPerLine; _prlp->_xPadRight = _xPadRight; _prlp->_yPadTop = _yPadTop; _prlp->_yPadBottom = _yPadBottom; _prlp->_ptpStartForListItem = _ptpStartForListItem; _prlp->_lTopPadding = _lTopPadding; _prlp->_lPosSpace = _lPosSpace; _prlp->_lNegSpace = _lNegSpace; _prlp->_lPosSpaceNoP = _lPosSpaceNoP; _prlp->_lNegSpaceNoP = _lNegSpaceNoP; }
40.052246
149
0.472126
[ "object" ]
53735de9b9521892edfdfda69bbae27af9643e5f
55,274
cc
C++
bloom_filter.cc
tlemane/HowDeSBT
d1dfb39c2784697f80c79451954c4cc45e1416eb
[ "MIT" ]
null
null
null
bloom_filter.cc
tlemane/HowDeSBT
d1dfb39c2784697f80c79451954c4cc45e1416eb
[ "MIT" ]
null
null
null
bloom_filter.cc
tlemane/HowDeSBT
d1dfb39c2784697f80c79451954c4cc45e1416eb
[ "MIT" ]
1
2021-04-08T07:37:45.000Z
2021-04-08T07:37:45.000Z
// bloom_filter.cc-- classes representing bloom filters. // // References: // // [1] Solomon, Brad, and Carl Kingsford. "Improved Search of Large // Transcriptomic Sequencing Databases Using Split Sequence Bloom // Trees." International Conference on Research in Computational // Molecular Biology. Springer, Cham, 2017. // [2] https://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives #include <string> #include <cstdlib> #include <cstdint> #include <cmath> #include <iostream> #include <vector> #include <chrono> #include "utilities.h" #include "bit_utilities.h" #include "hash.h" #include "file_manager.h" #include "bloom_filter_file.h" #include "bloom_filter.h" using std::string; using std::vector; using std::pair; using std::cerr; using std::endl; #define u32 std::uint32_t #define u64 std::uint64_t //---------- // // initialize class variables // //---------- bool BloomFilter::reportSimplify = false; bool BloomFilter::reportLoadTime = false; bool BloomFilter::reportSaveTime = false; bool BloomFilter::reportTotalLoadTime = false; bool BloomFilter::reportTotalSaveTime = false; double BloomFilter::totalLoadTime = 0.0; double BloomFilter::totalSaveTime = 0.0; bool BloomFilter::trackMemory = false; bool BloomFilter::reportCreation = false; bool BloomFilter::reportManager = false; bool BloomFilter::reportFileBytes = false; bool BloomFilter::countFileBytes = false; u64 BloomFilter::totalFileReads = 0; u64 BloomFilter::totalFileBytesRead = 0; //---------- // // BloomFilter-- // //---------- BloomFilter::BloomFilter (const string& _filename) : ready(false), manager(nullptr), filename(_filename), kmerSize(0), hasher1(nullptr), hasher2(nullptr), numHashes(0), hashSeed1(0), hashSeed2(0), hashModulus(0), numBits(0), setSizeKnown(false), setSize(0), numBitVectors(1) { // nota bene: we clear all maxBitVectors entries (instead of just // numBitVectors), because a subclass using this constructor // may increase numBitVectors for (int bvIx=0 ; bvIx<maxBitVectors ; bvIx++) bvs[bvIx] = nullptr; if (trackMemory) cerr << "@+" << this << " constructor BloomFilter(" << identity() << "), variant 1" << endl; } BloomFilter::BloomFilter (const string& _filename, u32 _kmerSize, u32 _numHashes, u64 _hashSeed1, u64 _hashSeed2, u64 _numBits, u64 _hashModulus) : ready(true), manager(nullptr), filename(_filename), kmerSize(_kmerSize), hasher1(nullptr), hasher2(nullptr), numHashes(_numHashes), hashSeed1(_hashSeed1), hashSeed2(_hashSeed2), numBits(_numBits), setSizeKnown(false), setSize(0), numBitVectors(1) { // (see note in first constructor) for (int bvIx=0 ; bvIx<maxBitVectors ; bvIx++) bvs[bvIx] = nullptr; setup_hashers(); if (_hashModulus == 0) hashModulus = _numBits; else hashModulus = _hashModulus; if (trackMemory) cerr << "@+" << this << " constructor BloomFilter(" << identity() << "), variant 2" << endl; } BloomFilter::BloomFilter (const BloomFilter* templateBf, const string& newFilename) : ready(true), manager(nullptr), kmerSize(templateBf->kmerSize), hasher1(nullptr), hasher2(nullptr), numHashes(templateBf->numHashes), hashSeed1(templateBf->hashSeed1), hashSeed2(templateBf->hashSeed2), hashModulus(templateBf->hashModulus), numBits(templateBf->numBits), setSizeKnown(false), setSize(0), numBitVectors(templateBf->numBitVectors) { // (see note in first constructor) for (int bvIx=0 ; bvIx<maxBitVectors ; bvIx++) bvs[bvIx] = nullptr; if (newFilename != "") filename = newFilename; else filename = templateBf->filename; setup_hashers(); if (trackMemory) cerr << "@+" << this << " constructor BloomFilter(" << identity() << "), variant 3" << endl; } BloomFilter::~BloomFilter() { if (trackMemory) cerr << "@-" << this << " destructor BloomFilter(" << identity() << ")" << endl; if (hasher1 != nullptr) delete hasher1; if (hasher2 != nullptr) delete hasher2; // nota bene: we only consider the first numBitVectors entries; the rest // are never used for (int bvIx=0 ; bvIx<numBitVectors ; bvIx++) { if (bvs[bvIx] != nullptr) delete bvs[bvIx]; } } string BloomFilter::identity() const { return class_identity() + ":\"" + filename + "\""; } void BloomFilter::setup_hashers() { // $$$ add trackMemory to hash constructor/destructor if ((numHashes > 0) && (hasher1 == nullptr)) hasher1 = new HashCanonical(kmerSize,hashSeed1); if ((numHashes > 1) && (hasher2 == nullptr)) hasher2 = new HashCanonical(kmerSize,hashSeed2); } bool BloomFilter::preload(bool bypassManager,bool stopOnMultipleContent) { // preload usually returns true; a return of false occurs when the // file contains more than one BF, and stopOnMultipleContent is true if (ready) return true; // $$$ should we also write the bvs back to disk? for (int bvIx=0 ; bvIx<numBitVectors ; bvIx++) { if (bvs[bvIx] != nullptr) { delete bvs[bvIx]; bvs[bvIx] = nullptr; } } if ((manager != nullptr) and (not bypassManager)) { // $$$ this should probably honor stopOnMultipleContent if (reportManager) cerr << "asking manager to preload " << identity() << " " << this << endl; manager->preload_content(filename); // manager will set ready = true } else { wall_time_ty startTime; if (reportLoadTime || reportTotalLoadTime) startTime = get_wall_time(); std::ifstream* in = FileManager::open_file(filename,std::ios::binary|std::ios::in, /* positionAtStart*/ true); if (not *in) fatal ("error: " + class_identity() + "::preload()" " failed to open \"" + filename + "\""); if (reportLoadTime || reportTotalLoadTime) { double elapsedTime = elapsed_wall_time(startTime); if (reportLoadTime) cerr << "[BloomFilter open] " << std::setprecision(6) << std::fixed << elapsedTime << " secs " << filename << endl; if (reportTotalLoadTime) totalLoadTime += elapsedTime; // $$$ danger of precision error? } vector<pair<string,BloomFilter*>> content = BloomFilter::identify_content(*in,filename); if ((stopOnMultipleContent) and (content.size() != 1)) { FileManager::close_file(in); return false; } if (content.size() != 1) fatal ("(internal?) error: in " + identity() + ".preload()" + " file contains multiple bloom filters" + " but we aren't using a file manager"); BloomFilter* templateBf = content[0].second; u32 bfKind = kind(); u32 templateBfKind = templateBf->kind(); if (templateBfKind != bfKind) fatal ("(internal?) error: in " + identity() + ".preload()" + " file contains incompatible" + "\n.. bloom filter, expected kind=" + filter_kind_to_string(bfKind,false) + " but file has kind=" + filter_kind_to_string(templateBfKind,false)); copy_properties(templateBf); setSizeKnown = templateBf->setSizeKnown; setSize = templateBf->setSize; steal_bits(templateBf); delete templateBf; FileManager::close_file(in); } if ((numHashes > 0) && (hasher1 == nullptr)) setup_hashers(); return true; } //……… we should have a reload() too //……… we shouldn't be able to load() a filter that didn't come from a file void BloomFilter::load (bool bypassManager, const string& whichNodeName) { //…… enable this test, non-null and resident and dirty // if (bv != nullptr) // fatal ("internal error for " + identity() // + "; attempt to load() onto non-null bit vector"); //…… if ((manager != nullptr) and (not bypassManager)) { if (reportManager) cerr << "asking manager to load " << identity() << " " << this << endl; manager->load_content(filename,whichNodeName); } else { // $$$ assert that whichNodeName == "" if (not ready) preload (); for (int bvIx=0 ; bvIx<numBitVectors ; bvIx++) { BitVector* bv = bvs[bvIx]; bv->reportLoad = reportLoad; bv->load(); } } } void BloomFilter::save() { for (int bvIx=0 ; bvIx<numBitVectors ; bvIx++) { if (bvs[bvIx] == nullptr) { if (bvIx == 0) fatal ("internal error for " + identity() + "; attempt to save null bloom filter"); else fatal ("internal error for " + identity() + "; attempt to save partially null bloom filter"); } } // $$$ this needs to make sure the file isn't currently opened for read!!!! // allocate the header, with enough room for a bfvectorinfo record for each // component // // note that we are assuming that the header size for the current file // format version is at least as large as that for any earlier versions u64 headerBytesNeeded = bffileheader_size(numBitVectors); headerBytesNeeded = round_up_16(headerBytesNeeded); u32 headerSize = (u32) headerBytesNeeded; if (headerSize != headerBytesNeeded) fatal ("error: header record for \"" + filename + "\"" " would be too large (" + std::to_string(headerSize) + " bytes)"); bffileheader* header = (bffileheader*) new char[headerSize]; if (header == nullptr) fatal ("error:" " failed to allocate " + std::to_string(headerSize) + " bytes" + " for header record for \"" + filename + "\""); if (trackMemory) cerr << "@+" << header << " allocating bf file header for BloomFilter(" << identity() << ")" << endl; // write a fake header to the file; after we write the rest of the file // we'll rewind and write the real header; we do this because we don't know // the component offsets and sizes until after we've written them if (reportSave) cerr << "Saving " << filename << endl; memset (header, 0, headerSize); header->magic = bffileheaderMagicUn; header->headerSize = (u32) sizeof(bffileprefix); std::ofstream out (filename, std::ios::binary | std::ios::trunc | std::ios::out); out.write ((char*)header, headerSize); size_t bytesWritten = headerSize; // (based on assumption of success) if (not out) fatal ("error: " + class_identity() + "::save(" + identity() + ")" + " failed to open \"" + filename + "\""); // start the real header header->magic = bffileheaderMagic; header->headerSize = headerSize; header->version = bffileheaderVersion; header->bfKind = kind(); header->padding1 = 0; header->kmerSize = kmerSize; header->numHashes = numHashes; header->hashSeed1 = hashSeed1; header->hashSeed2 = hashSeed2; header->hashModulus = hashModulus; header->numBits = numBits; header->numVectors = numBitVectors; header->setSizeKnown = setSizeKnown; header->setSize = (setSizeKnown)? setSize : 0; // write the component(s) for (int bvIx=0 ; bvIx<numBitVectors ; bvIx++) { BitVector* bv = bvs[bvIx]; header->info[bvIx].compressor = bv->compressor(); header->info[bvIx].name = 0; header->info[bvIx].offset = bytesWritten; if ((header->info[bvIx].compressor == bvcomp_rrr) || (header->info[bvIx].compressor == bvcomp_unc_rrr)) { header->info[bvIx].compressor |= (RRR_BLOCK_SIZE << 8); header->info[bvIx].compressor |= (RRR_RANK_PERIOD << 16); } size_t numBytes = bv->serialized_out (out, filename, header->info[bvIx].offset); bytesWritten += numBytes; header->info[bvIx].numBytes = numBytes; header->info[bvIx].filterInfo = bv->filterInfo; } // rewind and overwrite header out.seekp(std::ios::beg); out.write ((char*)header, headerSize); out.close(); // clean up if ((trackMemory) && (header != nullptr)) cerr << "@-" << header << " discarding bf file header for BloomFilter(" << identity() << ")" << endl; if (header != nullptr) delete[] header; // now we're in the equivalent of the "ready" state; actually we're beyond // that state, in the same state as the result of load() ready = true; } void BloomFilter::copy_properties (const BloomFilter* templateBf) { kmerSize = templateBf->kmerSize; numHashes = templateBf->numHashes; hashSeed1 = templateBf->hashSeed1; hashSeed2 = templateBf->hashSeed2; hashModulus = templateBf->hashModulus; numBits = templateBf->numBits; } void BloomFilter::steal_bits (BloomFilter* templateBf) { if (numBitVectors != templateBf->numBitVectors) fatal ("internal error for " + identity() + "; source filter has " + std::to_string(templateBf->numBitVectors) + " bitvectors" + " (this filter has " + std::to_string(numBitVectors) + ")"); discard_bits(); for (int bvIx=0 ; bvIx<numBitVectors ; bvIx++) { bvs[bvIx] = templateBf->bvs[bvIx]; templateBf->bvs[bvIx] = nullptr; } ready = true; } void BloomFilter::steal_bits (BloomFilter* templateBf, int whichBv) { steal_bits(templateBf,/*src*/whichBv,/*dst*/whichBv); } void BloomFilter::steal_bits (BloomFilter* templateBf, int whichSrcBv, int whichDstBv, u32 compressor) { if ((whichDstBv < 0) || (whichDstBv >= numBitVectors)) fatal ("internal error for " + identity() + "; request to set bitvector " + std::to_string(whichDstBv)); if ((whichSrcBv < 0) || (whichSrcBv >= templateBf->numBitVectors)) fatal ("internal error for " + identity() + "; request to get source filter's bitvector " + std::to_string(whichSrcBv)); discard_bits(whichDstBv); BitVector* srcBv = templateBf->bvs[whichSrcBv]; templateBf->bvs[whichSrcBv] = nullptr; if (compressor == srcBv->compressor()) bvs[whichDstBv] = srcBv; else { bvs[whichDstBv] = BitVector::bit_vector(compressor,srcBv); delete srcBv; } ready = true; } bool BloomFilter::is_consistent_with (const BloomFilter* bf, bool beFatal) const { if (bf->kmerSize != kmerSize) { if (not beFatal) return false; fatal ("error: inconsistent kmer size " + std::to_string(bf->kmerSize) + " in \"" + bf->filename + "\"" + " (expected " + std::to_string(kmerSize) + " like in \"" + filename + "\")" + "\n(all bloom filters are required to have the same kmer size)"); } if (bf->numHashes != numHashes) { if (not beFatal) return false; fatal ("error: inconsistent number of hashes " + std::to_string(bf->numHashes) + " in \"" + bf->filename + "\"" + " (expected " + std::to_string(numHashes) + " like in \"" + filename + "\")" + "\n(all bloom filters are required to have the same number of hashes)"); } if (bf->hashSeed1 != hashSeed1) { if (not beFatal) return false; fatal ("error: inconsistent hash seed " + std::to_string(bf->hashSeed1) + " in \"" + bf->filename + "\"" + " (expected " + std::to_string(hashSeed1) + " like in \"" + filename + "\")" + "\n(all bloom filters are required to have the same hash seeds)"); } if (bf->hashSeed2 != hashSeed2) { if (not beFatal) return false; fatal ("error: inconsistent hash seed 2 " + std::to_string(bf->hashSeed2) + " in \"" + bf->filename + "\"" + " (expected " + std::to_string(hashSeed2) + " like in \"" + filename + "\")" + "\n(all bloom filters are required to have the same hash seeds)"); } if (bf->hashModulus != hashModulus) { if (not beFatal) return false; fatal ("error: inconsistent hash modulus " + std::to_string(bf->hashModulus) + " in \"" + bf->filename + "\"" + " (expected " + std::to_string(hashModulus) + " like in \"" + filename + "\")" + "\n(all bloom filters are required to have the same hash modulus -- the same" + "\nnumber of bits)"); } if (bf->numBits != numBits) { if (not beFatal) return false; fatal ("error: inconsistent number of bits " + std::to_string(bf->numBits) + " in \"" + bf->filename + "\"" + " (expected " + std::to_string(numBits) + " like in \"" + filename + "\")" + "\n(all bloom filters are required to have the same number of bits)"); } if (bf->kind() != kind()) { if (not beFatal) return false; fatal ("error: inconsistent bloom filter kind " + std::to_string(bf->kind()) + " in \"" + bf->filename + "\"" + " (expected " + std::to_string(kind()) + " like in \"" + filename + "\")" + "\n(all bloom filters are required to be of the same kind)"); } return true; } void BloomFilter::discard_bits() { for (int bvIx=0 ; bvIx<numBitVectors ; bvIx++) { if (bvs[bvIx] != nullptr) { delete bvs[bvIx]; bvs[bvIx] = nullptr; } } } void BloomFilter::discard_bits (int whichBv) { if ((whichBv < 0) || (whichBv >= numBitVectors)) fatal ("internal error for " + identity() + "; request to discard bitvector " + std::to_string(whichBv)); if (bvs[whichBv] != nullptr) { delete bvs[whichBv]; bvs[whichBv] = nullptr; } } void BloomFilter::new_bits (u32 compressor, int whichBv) { if ((whichBv < -1) || (whichBv >= numBitVectors)) fatal ("internal error for " + identity() + "; request to replace bitvector " + std::to_string(whichBv)); if (whichBv >= 0) { if (bvs[whichBv] != nullptr) delete bvs[whichBv]; bvs[whichBv] = BitVector::bit_vector(compressor,numBits); } else { // nothing specified, so do them all for (int bvIx=0 ; bvIx<numBitVectors ; bvIx++) { if (bvs[bvIx] != nullptr) delete bvs[bvIx]; bvs[bvIx] = BitVector::bit_vector(compressor,numBits); } } } void BloomFilter::new_bits (BitVector* srcBv, u32 compressor, int whichBv) { if ((whichBv < 0) || (whichBv >= numBitVectors)) fatal ("internal error for " + identity() + "; request to set bitvector " + std::to_string(whichBv)); if (bvs[whichBv] != nullptr) delete bvs[whichBv]; if (srcBv->bits == nullptr) { u32 srcCompressor = srcBv->compressor(); if ((srcCompressor != bvcomp_zeros) && (srcCompressor != bvcomp_ones)) fatal ("internal error for " + identity() + "; attempt to copy bits from null or compressed bitvector " + srcBv->identity()); } bvs[whichBv] = BitVector::bit_vector(compressor,srcBv); } void BloomFilter::new_bits (const string& filename) // note that compressor etc. may be encoded in filename { for (int bvIx=0 ; bvIx<numBitVectors ; bvIx++) { if (bvs[bvIx] != nullptr) delete bvs[bvIx]; bvs[bvIx] = BitVector::bit_vector (filename); } } BitVector* BloomFilter::get_bit_vector (int whichBv) const { if ((whichBv < 0) || (whichBv >= numBitVectors)) fatal ("internal error for " + identity() + "; request to get bitvector " + std::to_string(whichBv)); return bvs[whichBv]; } BitVector* BloomFilter::surrender_bit_vector (int whichBv) { if ((whichBv < 0) || (whichBv >= numBitVectors)) fatal ("internal error for " + identity() + "; request to get bitvector " + std::to_string(whichBv)); BitVector* bv = bvs[whichBv]; bvs[whichBv] = nullptr; return bv; } BitVector* BloomFilter::simplify_bit_vector (int whichBv) { // if possible, replace the bit vector with a simpler version, such as // all-zeros or all-ones if ((whichBv < 0) || (whichBv >= numBitVectors)) fatal ("internal error for " + identity() + "; request to simplify bitvector " + std::to_string(whichBv)); BitVector* bv = bvs[whichBv]; u32 bvCompressor = bv->compressor(); if ((bvCompressor == bvcomp_zeros) || (bvCompressor == bvcomp_ones)) return bv; // bv is already a simple type if (bv->is_all_zeros()) { if (reportSimplify) cerr << "Simplifying " << filename << "." << whichBv << " to all-zeros" << endl; bvs[whichBv] = new ZerosBitVector(bv->size()); delete bv; return bvs[whichBv]; } if (bv->is_all_ones()) { if (reportSimplify) cerr << "Simplifying " << filename << "." << whichBv << " to all-ones" << endl; bvs[whichBv] = new OnesBitVector(bv->size()); delete bv; return bvs[whichBv]; } return bv; } void BloomFilter::complement (int whichDstBv) { if ((whichDstBv < -1) || (whichDstBv >= numBitVectors)) fatal ("internal error for " + identity() + "; request to complement bitvector " + std::to_string(whichDstBv)); if (whichDstBv >= 0) bvs[whichDstBv]->complement(); else // if (whichDstBv == -1) { for (int bvIx=0 ; bvIx<numBitVectors ; bvIx++) bvs[bvIx]->complement(); } } void BloomFilter::union_with (BitVector* srcBv, int whichDstBv) { if ((whichDstBv < 0) || (whichDstBv >= numBitVectors)) fatal ("internal error for " + identity() + "; request to union into bitvector " + std::to_string(whichDstBv)); switch (srcBv->compressor()) { case bvcomp_zeros: break; case bvcomp_ones: bvs[whichDstBv]->fill(1); break; default: bvs[whichDstBv]->union_with(srcBv->bits); break; } } void BloomFilter::union_with_complement (BitVector* srcBv, int whichDstBv) { if ((whichDstBv < 0) || (whichDstBv >= numBitVectors)) fatal ("internal error for " + identity() + "; request to union into bitvector " + std::to_string(whichDstBv)); switch (srcBv->compressor()) { case bvcomp_zeros: bvs[whichDstBv]->fill(1); break; case bvcomp_ones: break; default: bvs[whichDstBv]->union_with_complement(srcBv->bits); break; } } void BloomFilter::intersect_with (BitVector* srcBv, int whichDstBv) { if ((whichDstBv < 0) || (whichDstBv >= numBitVectors)) fatal ("internal error for " + identity() + "; request to intersection into bitvector " + std::to_string(whichDstBv)); switch (srcBv->compressor()) { case bvcomp_zeros: bvs[whichDstBv]->fill(0); break; case bvcomp_ones: break; default: bvs[whichDstBv]->intersect_with(srcBv->bits); break; } } void BloomFilter::mask_with (BitVector* srcBv, int whichDstBv) { if ((whichDstBv < 0) || (whichDstBv >= numBitVectors)) fatal ("internal error for " + identity() + "; request to mask bitvector " + std::to_string(whichDstBv)); switch (srcBv->compressor()) { case bvcomp_zeros: break; case bvcomp_ones: bvs[whichDstBv]->fill(0); break; default: bvs[whichDstBv]->mask_with(srcBv->bits); break; } } void BloomFilter::xor_with (BitVector* srcBv, int whichDstBv) { if ((whichDstBv < 0) || (whichDstBv >= numBitVectors)) fatal ("internal error for " + identity() + "; request to xor into bitvector " + std::to_string(whichDstBv)); switch (srcBv->compressor()) { case bvcomp_zeros: break; case bvcomp_ones: bvs[whichDstBv]->complement(); break; default: bvs[whichDstBv]->xor_with(srcBv->bits); break; } } void BloomFilter::squeeze_by (BitVector* srcBv, int whichDstBv) { if ((whichDstBv < 0) || (whichDstBv >= numBitVectors)) fatal ("internal error for " + identity() + "; request to squeeze bitvector " + std::to_string(whichDstBv)); // …… require that whichDstBv is uncompressed? u32 compressor = srcBv->compressor(); switch (compressor) { default: bvs[whichDstBv]->squeeze_by(srcBv->bits); break; case bvcomp_zeros: case bvcomp_ones: int fillValue = (compressor == bvcomp_zeros)? 0 : 1; u64 resultNumBits = bitwise_count(srcBv->bits->data(),numBits); sdslbitvector* resultBits = new sdslbitvector(resultNumBits,fillValue); if (trackMemory) cerr << "@+" << resultBits << " creating sdslbitvector for BitVector " << bvs[whichDstBv]->identity() << endl; bvs[whichDstBv]->replace_bits(resultBits); break; } } void BloomFilter::squeeze_by (const sdslbitvector* srcBits, int whichDstBv) { if ((whichDstBv < 0) || (whichDstBv >= numBitVectors)) fatal ("internal error for " + identity() + "; request to squeeze bitvector " + std::to_string(whichDstBv)); bvs[whichDstBv]->squeeze_by(srcBits); } // mer_to_position-- // Report the position of a kmer in the filter; we return BloomFilter::npos if // the kmer's position is not within the filter (this is *not* the same as the // kmer being present in the set represent by the filter); the kmer can be a // string or 2-bit encoded data u64 BloomFilter::mer_to_position (const string& mer) const { // nota bene: we don't enforce numHashes == 1 u64 pos = hasher1->hash(mer) % hashModulus; if (pos < numBits) return pos; else return npos; // position is *not* in the filter } u64 BloomFilter::mer_to_position (const u64* merData) const { // nota bene: we don't enforce numHashes == 1 u64 pos = hasher1->hash(merData) % hashModulus; if (pos < numBits) return pos; else return npos; // position is *not* in the filter } // add-- // Add a kmer to the filter; the kmer can be a string or 2-bit encoded data void BloomFilter::add (const string& mer) { // nota bene: we don't enforce mer.length == kmerSize // nota bene: we don't canonicalize the string; revchash handles that BitVector* bv = bvs[0]; u64 h1 = hasher1->hash(mer); u64 pos = h1 % hashModulus; if (pos < numBits) { (*bv).write_bit(pos); } if (numHashes > 1) { u64 hashValues[numHashes]; Hash::fill_hash_values(hashValues,numHashes,h1,hasher2->hash(mer)); for (u32 h=1 ; h<numHashes ; h++) { pos = hashValues[h] % hashModulus; if (pos < numBits) { (*bv).write_bit(pos); // $$$ MULTI_VECTOR write each bit to a different vector } } } } void BloomFilter::add (const u64* merData) { BitVector* bv = bvs[0]; u64 h1 = hasher1->hash(merData); u64 pos = h1 % hashModulus; if (pos < numBits) { (*bv).write_bit(pos); } if (numHashes > 1) { u64 hashValues[numHashes]; Hash::fill_hash_values(hashValues,numHashes,h1,hasher2->hash(merData)); for (u32 h=1 ; h<numHashes ; h++) { pos = hashValues[h] % hashModulus; if (pos < numBits) { (*bv).write_bit(pos); // $$$ MULTI_VECTOR write each bit to a different vector } } } } // contains-- // returns true if the bloom filter contains the given kmer (or false // positive), false otherwise; the kmer can be a string or 2-bit encoded data bool BloomFilter::contains (const string& mer) const { // nota bene: we don't enforce mer.length == kmerSize // nota bene: we don't canonicalize the string; revchash handles that BitVector* bv = bvs[0]; u64 h1 = hasher1->hash(mer); u64 pos = h1 % hashModulus; if (pos < numBits) { if ((*bv)[pos] == 0) return false; } if (numHashes > 1) { u64 hashValues[numHashes]; Hash::fill_hash_values(hashValues,numHashes,h1,hasher2->hash(mer)); for (u32 h=1 ; h<numHashes ; h++) { pos = hashValues[h] % hashModulus; if (pos < numBits) { if ((*bv)[pos] == 0) return false; // $$$ MULTI_VECTOR read each bit from a different vector } } } return true; } bool BloomFilter::contains (const u64* merData) const { BitVector* bv = bvs[0]; u64 h1 = hasher1->hash(merData); u64 pos = h1 % hashModulus; if (pos < numBits) { if ((*bv)[pos] == 0) return false; } if (numHashes > 1) { u64 hashValues[numHashes]; Hash::fill_hash_values(hashValues,numHashes,h1,hasher2->hash(merData)); for (u32 h=1 ; h<numHashes ; h++) { pos = hashValues[h] % hashModulus; if (pos < numBits) { if ((*bv)[pos] == 0) return false; // $$$ MULTI_VECTOR read each bit from a different vector } } } return true; } int BloomFilter::lookup (const u64 pos) const { BitVector* bv = bvs[0]; // we assume, without checking, that 0 <= pos < numBits if ((*bv)[pos] == 0) return absent; else return unresolved; } //---------- // // AllSomeFilter-- // //---------- AllSomeFilter::AllSomeFilter (const string& _filename) : BloomFilter(_filename) { numBitVectors = 2; } AllSomeFilter::AllSomeFilter (const string& _filename, u32 _kmerSize, u32 _numHashes, u64 _hashSeed1, u64 _hashSeed2, u64 _numBits, u64 _hashModulus) : BloomFilter(_filename, _kmerSize, _numHashes, _hashSeed1, _hashSeed2, _numBits, _hashModulus) { numBitVectors = 2; } AllSomeFilter::AllSomeFilter (const BloomFilter* templateBf, const string& newFilename) : BloomFilter(templateBf, newFilename) { numBitVectors = 2; } AllSomeFilter::~AllSomeFilter() { if (trackMemory) cerr << "@-" << this << " destructor AllSomeFilter(" << identity() << ")" << endl; } // add-- void AllSomeFilter::add (const string& mer) { fatal ("internal error: attempt to add a mer to " + class_identity()); } void AllSomeFilter::add (const u64* merData) { fatal ("internal error: attempt to add a mer to " + class_identity()); } // contains-- bool AllSomeFilter::contains (const string& mer) const { fatal ("internal error: \"is mer contained\" request in " + class_identity()); return false; } bool AllSomeFilter::contains (const u64* merData) const { fatal ("internal error: \"is mer contained\" request in " + class_identity()); return false; } int AllSomeFilter::lookup (const u64 pos) const { BitVector* bvAll = bvs[0]; BitVector* bvSome = bvs[1]; // we assume, without checking, that 0 <= pos < numBits if ((*bvAll) [pos] == 1) return present; else if ((*bvSome)[pos] == 0) return absent; else return unresolved; } //---------- // // DeterminedFilter-- // //---------- DeterminedFilter::DeterminedFilter (const string& _filename) : BloomFilter(_filename) { numBitVectors = 2; } DeterminedFilter::DeterminedFilter (const string& _filename, u32 _kmerSize, u32 _numHashes, u64 _hashSeed1, u64 _hashSeed2, u64 _numBits, u64 _hashModulus) : BloomFilter(_filename, _kmerSize, _numHashes, _hashSeed1, _hashSeed2, _numBits, _hashModulus) { numBitVectors = 2; } DeterminedFilter::DeterminedFilter (const BloomFilter* templateBf, const string& newFilename) : BloomFilter(templateBf, newFilename) { numBitVectors = 2; } DeterminedFilter::~DeterminedFilter() { if (trackMemory) cerr << "@-" << this << " destructor DeterminedFilter(" << identity() << ")" << endl; } int DeterminedFilter::lookup (const u64 pos) const { BitVector* bvDet = bvs[0]; BitVector* bvHow = bvs[1]; // we assume, without checking, that 0 <= pos < numBits if ((*bvDet)[pos] == 0) return unresolved; else if ((*bvHow)[pos] == 1) return present; else return absent; } //---------- // // DeterminedBriefFilter-- // // Attribution: the use of rank/select and removal of inactive bits was // inspired by [1], but the application of it to a determined/brief split is // original with this program. // //---------- DeterminedBriefFilter::DeterminedBriefFilter (const string& _filename) : DeterminedFilter(_filename) { numBitVectors = 2; } DeterminedBriefFilter::DeterminedBriefFilter (const string& _filename, u32 _kmerSize, u32 _numHashes, u64 _hashSeed1, u64 _hashSeed2, u64 _numBits, u64 _hashModulus) : DeterminedFilter(_filename, _kmerSize, _numHashes, _hashSeed1, _hashSeed2, _numBits, _hashModulus) { numBitVectors = 2; } DeterminedBriefFilter::DeterminedBriefFilter (const BloomFilter* templateBf, const string& newFilename) : DeterminedFilter(templateBf, newFilename) { numBitVectors = 2; } DeterminedBriefFilter::~DeterminedBriefFilter() { if (trackMemory) cerr << "@-" << this << " destructor DeterminedBriefFilter(" << identity() << ")" << endl; } int DeterminedBriefFilter::lookup (const u64 pos) const { // we assume, without checking, that 0 <= pos < numBits BitVector* bvDet = bvs[0]; if ((*bvDet)[pos] == 0) return unresolved; BitVector* bvHow = bvs[1]; u64 howPos = bvDet->rank1(pos); if ((*bvHow)[howPos] == 1) return present; else return absent; } void DeterminedBriefFilter::adjust_positions_in_list (vector<u64> &kmerPositions, u64 numUnresolved) { BitVector* bvDet = bvs[0]; for (u64 posIx=0 ; posIx<numUnresolved ; posIx++) { u64 pos = kmerPositions[posIx]; u64 rank = bvDet->rank1(pos); kmerPositions[posIx] = pos - rank; // $$$ isn't this just rank0(pos)? } } void DeterminedBriefFilter::restore_positions_in_list (vector<u64> &kmerPositions, u64 numUnresolved) { BitVector* bvDet = bvs[0]; for (u64 posIx=0 ; posIx<numUnresolved ; posIx++) { u64 pos = kmerPositions[posIx]; kmerPositions[posIx] = bvDet->select0(pos); } } //---------- // // strip_filter_suffix-- // Remove any of the standard bloom filter suffixes from a file name. // //---------- // // Arguments: // const string& filename: The name of the bloom filter file. // const int complete: How much to remove // 1 => remove, e.g. ".bf" // 2 => remove, e.g. ".rrr.bf" // 3 => remove, e.g. ".det.bf" or ".det.rrr.bf" // // Returns: // A filename, with the suffix removed. // //---------- string BloomFilter::strip_filter_suffix (const string& filename, const int complete) { string name = filename; if (is_suffix_of (name, ".bf")) name = strip_suffix(name,".bf"); if (is_suffix_of (name, ".unity")) name = strip_suffix(name,".unity"); if (complete >= 2) { string compSuffix = "." + BitVector::compressor_to_string(bvcomp_rrr); if (is_suffix_of(name,compSuffix)) name = strip_suffix(name,compSuffix); else { compSuffix = "." + BitVector::compressor_to_string(bvcomp_roar); if (is_suffix_of(name,compSuffix)) name = strip_suffix(name,compSuffix); } } if (complete >= 3) { if (is_suffix_of(name,".allsome")) // bfkind_allsome name = strip_suffix(name,".allsome"); else if (is_suffix_of(name,".det")) // bfkind_determined name = strip_suffix(name,".det"); else if (is_suffix_of(name,".detbrief")) // bfkind_determined_brief name = strip_suffix(name,".detbrief"); } return name; } //---------- // // default_filter_name-- // Derive a name for a bloom filter, from its file name. // //---------- // // Arguments: // const string& filename: The name of the bloom filter file. // const int componentNumber: The index of the bloom filter in the // file's components. The value -1 // indicates that this index is not // relevant. // // Returns: // A name for the filter. // //---------- string BloomFilter::default_filter_name (const string& filename, const int componentNumber) { string name = strip_file_path(filename); name = BloomFilter::strip_filter_suffix(name); if (componentNumber >= 0) name += "." + std::to_string(componentNumber); return name; } //---------- // // filter_kind_to_string-- // Convert a bloom filter kind to a string, often used for constructing // filenames. // //---------- // // Arguments: // u32 bfKind: The type of bloom filter; one of bfkind_xxx. // bool shortString: true => produce a short string, suitable for use // .. as a file extension // false => produce a longer string, suitable for // .. error text // // Returns: // A short string representing the bloom filter type. // //---------- string BloomFilter::filter_kind_to_string (u32 bfKind, bool shortString) { switch (bfKind) { case bfkind_simple: return (shortString)? "" : "simple"; case bfkind_allsome: return (shortString)? "allsome" : "allsome"; case bfkind_determined: return (shortString)? "det" : "determined"; case bfkind_determined_brief: return (shortString)? "detbrief" : "determined,brief"; case bfkind_intersection: return (shortString)? "cap" : "intersection"; // nota bene: when new file extensions are added here, they should also // .. be added in BloomFilter::strip_filter_suffix() default: fatal ("error: in filter_kind_to_string():" " bad filter code: \"" + std::to_string(bfKind) + "\""); } return ""; // should never get here } //---------- // // vectors_per_filter-- // Figure out how many bit vectors a particular type of filter will have. // //---------- // // Arguments: // const u32 bfKind: The type of bloom filter; one of bfkind_xxx. // // Returns: // The number of bit vectors that a filter of that type will have. This will // be the same as the numBitVectors instance variable for the corresponding // filter class. // //---------- int BloomFilter::vectors_per_filter (const u32 bfKind) { switch (bfKind) { case bfkind_simple: case bfkind_intersection: return 1; break; case bfkind_allsome: case bfkind_determined: case bfkind_determined_brief: return 2; break; default: fatal ("error: in vectors_per_filter():" " bad filter code: \"" + std::to_string(bfKind) + "\""); } return 0; // never reaches here } //---------- // // bloom_filter-- // Create a specified kind of BloomFilter object. // //---------- // // Arguments (variant 1): // const std::string& filename: A filename for the new bloom filter. The // .. type of the bloom filter is derived from // .. the suffix. // // Arguments (variant 2): // const u32 bfKind: The type of bloom filter to create; one of // .. bfkind_xxx. // filename..hashModulus: The same as for the BloomFilter constructors. // // Arguments (variant 3): // const BloomFilter* templateBf: A bloom filter to mimic; only in the sense // .. of its type and properties. // const std::string& newFilename: A different filename for the new bloom // .. filter. // // Returns: // A BloomFilter (or subclass of BloomFilter) object. // //---------- //=== variant 1 === BloomFilter* BloomFilter::bloom_filter (const string& filename) { string reducedName = filename; string compSuffix = "." + BitVector::compressor_to_string(bvcomp_rrr) + ".bf"; if (is_suffix_of(reducedName,compSuffix)) reducedName = strip_suffix(reducedName,compSuffix) + ".bf"; else { compSuffix = "." + BitVector::compressor_to_string(bvcomp_roar) + ".bf"; if (is_suffix_of(reducedName,compSuffix)) reducedName = strip_suffix(reducedName,compSuffix) + ".bf"; } if (is_suffix_of(reducedName,".detbrief.bf")) // bfkind_determined_brief return new DeterminedBriefFilter (filename); if (is_suffix_of(reducedName,".det.bf")) // bfkind_determined return new DeterminedFilter (filename); if (is_suffix_of(reducedName,".allsome.bf")) // bfkind_allsome return new AllSomeFilter (filename); if (is_suffix_of(reducedName,".bf")) // bfkind_simple return new BloomFilter (filename); fatal ("error: BloomFilter::bloom_filter(\"" + filename + "\"" + " is not implemented (file extension not recognized)"); return nullptr; // never reaches here } //=== variant 2 === BloomFilter* BloomFilter::bloom_filter (const u32 bfKind, const string& filename, u32 kmerSize, u32 numHashes, u64 hashSeed1, u64 hashSeed2, u64 numBits, u64 hashModulus) { switch (bfKind) { case bfkind_simple: case bfkind_intersection: // internally treated the same as bfkind_simple return new BloomFilter (filename,kmerSize, numHashes,hashSeed1,hashSeed2, numBits,hashModulus); case bfkind_allsome: return new AllSomeFilter (filename,kmerSize, numHashes,hashSeed1,hashSeed2, numBits,hashModulus); case bfkind_determined: return new DeterminedFilter (filename,kmerSize, numHashes,hashSeed1,hashSeed2, numBits,hashModulus); case bfkind_determined_brief: return new DeterminedBriefFilter (filename,kmerSize, numHashes,hashSeed1,hashSeed2, numBits,hashModulus); default: fatal ("error: BloomFilter::bloom_filter(\"" + std::to_string(bfKind) + "\"" + " is not implemented"); } return nullptr; // never reaches here } //=== variant 3 === BloomFilter* BloomFilter::bloom_filter (const BloomFilter* templateBf, const std::string& newFilename) { switch (templateBf->kind()) { case bfkind_simple: case bfkind_intersection: // internally treated the same as bfkind_simple return new BloomFilter(templateBf,newFilename); case bfkind_allsome: return new AllSomeFilter(templateBf,newFilename); case bfkind_determined: return new DeterminedFilter(templateBf,newFilename); case bfkind_determined_brief: return new DeterminedBriefFilter(templateBf,newFilename); default: fatal ("error: BloomFilter::bloom_filter()" " doesn't understand filter type " + std::to_string(templateBf->kind())); } return nullptr; // never reaches here } //---------- // // identify_content-- // Read a header from a bloom filter file, and determine the content of the // file. "Content" consists of one-or-more named bloom filters. // //---------- // // Arguments: // std::ifstream& in: The stream to read from. This should have been // opened with std::ios::binary | std::ios::in. // const string& filename: The name of the bloom filter file to read from. // This is only used for error messages, and can // be blank. // // Returns: // The contents; this is a vector of (name,bloom filter) pairs. The name is // the bloom filter's name from the file header, if the header has one. If // not, it is derived from the file name. // //---------- // // Notes: // (1) Each bloom filter created also has a bit vector (or bit vectors) // created for it. The bit vector has the proper information about where // to find its bits (file, offset, number of bytes, compression type), but // does not have its bits loaded. // //---------- vector<pair<string,BloomFilter*>> BloomFilter::identify_content (std::ifstream& in, const string& filename) { wall_time_ty startTime; double elapsedTime = 0.0; vector<pair<string,BloomFilter*>> content; //---- read and validate the header prefix ---- bffileprefix prefix; if (reportLoadTime || reportTotalLoadTime) startTime = get_wall_time(); in.read ((char*) &prefix, sizeof(prefix)); if (reportLoadTime || reportTotalLoadTime) elapsedTime = elapsed_wall_time(startTime); if (!in.good()) fatal ("error: BloomFilter::identify_content(" + filename + ")" " problem reading header from \"" + filename + "\""); size_t prevFilePos = 0; size_t currentFilePos = in.gcount(); if (currentFilePos != sizeof(prefix)) fatal ("error: BloomFilter::identify_content(" + filename + ")" " read(\"" + filename + "\"," + std::to_string(sizeof(prefix)) + ")" + " produced " + std::to_string(currentFilePos) + " bytes"); if (reportFileBytes) cerr << "[BloomFilter identify_content] read " << sizeof(prefix) << " bytes " << filename << endl; if (countFileBytes) { totalFileReads++; totalFileBytesRead += sizeof(prefix); } if (prefix.magic == bffileheaderMagicUn) fatal ("error: BloomFilter::identify_content(" + filename + ")" " looks like an incomplete bloom filter file" " (it seems the file was not completely written)"); if (prefix.magic != bffileheaderMagic) fatal ("error: BloomFilter::identify_content(" + filename + ")" " doesn't look like a bloom filter file" " (incorrect magic number)"); if ((prefix.version != bffileheaderVersion) && (prefix.version != bffileheaderVersion1)) fatal ("error: BloomFilter::identify_content(" + filename + ")" " bloom filter file version " + std::to_string(prefix.version) + " is not supported by this program"); if (prefix.headerSize <= sizeof(prefix)) fatal ("error: BloomFilter::identify_content(" + filename + ")" " header impossibly small (" + std::to_string(prefix.headerSize) + " bytes)"); if (prefix.headerSize > max_bffileheader_size) fatal ("error: BloomFilter::identify_content(" + filename + ")" " headers larger than " + std::to_string(max_bffileheader_size) + " bytes are not supported," + " this file's header claims to be " + std::to_string(prefix.headerSize) + " bytes"); //---- read the rest of the header, and validate ---- bffileheader* header = (bffileheader*) new char[prefix.headerSize]; if (header == nullptr) fatal ("error: BloomFilter::identify_content(" + filename + ")" " failed to allocate " + std::to_string(prefix.headerSize) + " bytes" + " for file header"); std::memcpy (/*to*/ header, /*from*/ &prefix, /*how much*/ sizeof(prefix)); if (trackMemory) cerr << "@+" << header << " allocating bf file header for \"" << filename << "\"" << endl; size_t remainingBytes = prefix.headerSize - sizeof(prefix); if (reportLoadTime || reportTotalLoadTime) startTime = get_wall_time(); in.read (((char*) header) + sizeof(prefix), remainingBytes); if (reportLoadTime || reportTotalLoadTime) elapsedTime += elapsed_wall_time(startTime); prevFilePos = currentFilePos; currentFilePos += in.gcount(); if (currentFilePos != prefix.headerSize) fatal ("error: BloomFilter::identify_content(" + filename + ")" " read(\"" + filename + "\"," + std::to_string(remainingBytes) + ")" + " produced " + std::to_string(currentFilePos-prevFilePos) + " bytes"); if (reportFileBytes) cerr << "[BloomFilter identify_content] read " << remainingBytes << " bytes " << filename << endl; if (countFileBytes) totalFileBytesRead += remainingBytes; // (we intentionally don't do totalFileReads++) if (reportLoadTime) cerr << "[BloomFilter load-header] " << std::setprecision(6) << std::fixed << elapsedTime << " secs " << filename << endl; if (reportTotalLoadTime) totalLoadTime += elapsedTime; // $$$ danger of precision error? if ((header->bfKind != bfkind_simple) && (header->bfKind != bfkind_allsome) && (header->bfKind != bfkind_determined) && (header->bfKind != bfkind_determined_brief) && (header->bfKind != bfkind_intersection)) fatal ("error: BloomFilter::identify_content(" + filename + ")" " bad filter type: " + std::to_string(header->bfKind)); // make sure header size and number of vectors make sense size_t minHeaderSize = bffileheader_size(header->numVectors); if (header->headerSize < minHeaderSize) fatal ("error: BloomFilter::identify_content(" + filename + ")" " expected " + std::to_string(minHeaderSize) + " byte header (or larger)" + " but header says it is " + std::to_string(header->headerSize) + " bytes"); if (header->numVectors < 1) fatal ("error: BloomFilter::identify_content(" + filename + ")" " bad number of vectors: " + std::to_string(header->numVectors)); int vectorsPerFilter = BloomFilter::vectors_per_filter(header->bfKind); int numFilters = header->numVectors / vectorsPerFilter; if (header->numVectors % vectorsPerFilter != 0) fatal ("error: BloomFilter::identify_content(" + filename + ")" " number of vectors (" + std::to_string(header->numVectors) + ")" + " is not a multiple of the number of vectors per filter" + "(" + std::to_string(vectorsPerFilter) + ")"); if (header->padding1 != 0) fatal ("error: BloomFilter::identify_content(" + filename + ")" " non-zero padding field 1: " + std::to_string(header->padding1)); if (prefix.version == bffileheaderVersion1) { u32* padding2 = (u32*) &header->setSizeKnown; u32* padding3 = (u32*) &header->setSize; u32* padding4 = (u32*) ((((char*)padding3)+sizeof(u32))); if (*padding2 != 0) fatal ("error: BloomFilter::identify_content(" + filename + ")" " non-zero padding field 2: " + std::to_string(*padding2)); if (*padding3 != 0) fatal ("error: BloomFilter::identify_content(" + filename + ")" " non-zero padding field 3: " + std::to_string(*padding3)); if (*padding4 != 0) fatal ("error: BloomFilter::identify_content(" + filename + ")" " non-zero padding field 4: " + std::to_string(*padding4)); } if (header->numHashes < 1) fatal ("error: BloomFilter::identify_content(" + filename + ")" " bad number of hash functions: " + std::to_string(header->numHashes)); if (header->numBits < 2) fatal ("error: BloomFilter::identify_content(" + filename + ")" " too few bits in vector: " + std::to_string(header->numBits)); if (header->hashModulus < header->numBits) fatal ("error: BloomFilter::identify_content(" + filename + ")" " hash modulus (" + std::to_string(header->hashModulus) + ")" + " is less than bits in vector (" + std::to_string(header->numBits) + ")"); // extract the info for each bitvector vector<BitVectorInfo> bvInfoList; u64 expectedOffset = header->headerSize; for (u32 bvIx=0 ; bvIx<header->numVectors ; bvIx++) { BitVectorInfo bvInfo; bvInfo.compressor = header->info[bvIx].compressor; bvInfo.offset = header->info[bvIx].offset; bvInfo.numBytes = header->info[bvIx].numBytes; u32 nameOffset = header->info[bvIx].name; // we'll copy header->info[bvIx].filterInfo when we create the bit vector if (bvInfo.offset < header->headerSize) fatal ("error: BloomFilter::identify_content(" + filename + ")" " offset to bitvector-" + std::to_string(bvIx) + " data is within header: " + std::to_string(bvInfo.offset)); if (bvInfo.offset != expectedOffset) fatal ("error: BloomFilter::identify_content(" + filename + ")" " offset to bitvector-" + std::to_string(bvIx) + " is " + std::to_string(bvInfo.offset) + " but we expected it to be " + std::to_string(expectedOffset)); if (nameOffset >= header->headerSize) fatal ("error: BloomFilter::identify_content(" + filename + ")" " offset to bitvector-" + std::to_string(bvIx) + " name is beyond header: " + std::to_string(nameOffset)); u32 rrrBlockSize, rrrRankPeriod; switch (bvInfo.compressor & 0x000000FF) { case bvcomp_uncompressed: case bvcomp_roar: case bvcomp_unc_roar: case bvcomp_zeros: case bvcomp_ones: if ((bvInfo.compressor & 0xFFFFFF00) != 0) goto bad_compressor_code; break; case bvcomp_rrr: case bvcomp_unc_rrr: if ((bvInfo.compressor & 0xFF000000) != 0) goto bad_compressor_code; rrrBlockSize = (bvInfo.compressor >> 8) & 0x000000FF; rrrRankPeriod = (bvInfo.compressor >> 16) & 0x000000FF; if (rrrBlockSize != RRR_BLOCK_SIZE) fatal ("error: BloomFilter::identify_content(" + filename + ")" " bitvector-" + std::to_string(bvIx) + ", rrr block size mismatch" + "\nthe file's block size is " + std::to_string(rrrBlockSize) + ", program's block size is " + std::to_string(RRR_BLOCK_SIZE) + "\n(see notes regarding RRR_BLOCK_SIZE in bit_vector.h)"); if (rrrRankPeriod == 0) rrrRankPeriod = DEFAULT_RRR_RANK_PERIOD; if (rrrRankPeriod != RRR_RANK_PERIOD) fatal ("error: BloomFilter::identify_content(" + filename + ")" " bitvector-" + std::to_string(bvIx) + ", rrr rank period mismatch" + "\nthe file's rank period is " + std::to_string(rrrRankPeriod) + ", program's rank period is " + std::to_string(RRR_RANK_PERIOD) + "\n(see notes regarding RRR_RANK_PERIOD in bit_vector.h)"); bvInfo.compressor &= 0x000000FF; break; default: bad_compressor_code: fatal ("error: BloomFilter::identify_content(" + filename + ")" " bitvector-" + std::to_string(bvIx) + ", bad compressor code: " + std::to_string(bvInfo.compressor)); } if (nameOffset != 0) { bvInfo.name = string(((char*) header) + nameOffset); int whichBv = bvIx % vectorsPerFilter; if (whichBv != 0) { string expectedName = bvInfoList[bvIx-whichBv].name; if (bvInfo.name != expectedName) fatal ("error: BloomFilter::identify_content(" + filename + ")" " bitvector-" + std::to_string(bvIx) + ", name is \"" + bvInfo.name + "\"" + " but we expected it to be \"" + expectedName + "\""); } } else if (numFilters == 1) bvInfo.name = default_filter_name(filename); else bvInfo.name = default_filter_name(filename,bvIx); bvInfoList.emplace_back(bvInfo); expectedOffset += bvInfo.numBytes; } // create the bloom filters and bit vectors; note that this will *not* // usually load the bit vectors // // nota bene: we assume that for, e.g. all/some filters, the bit vectors // .. are in the file in the same order as they are in the filter's bvs // .. array; this *should* be the same order in which they were written // .. to the file BloomFilter* bf = nullptr; int infoIx = -1; for (const auto& bvInfo : bvInfoList) { int whichBv = (++infoIx) % vectorsPerFilter; if (whichBv == 0) { if (reportCreation) cerr << "about to construct BloomFilter for " << filename << " content " << whichBv << endl; bf = bloom_filter(header->bfKind, filename, header->kmerSize, header->numHashes, header->hashSeed1, header->hashSeed2, header->numBits, header->hashModulus); if (prefix.version == bffileheaderVersion1) { bf->setSizeKnown = false; bf->setSize = 0; } else { if (header->setSizeKnown > 1) fatal ("error: BloomFilter::identify_content(" + filename + ")" " set size known flag (" + std::to_string(header->setSizeKnown) + ")" + " is not zero or one"); bf->setSizeKnown = (header->setSizeKnown == 1); bf->setSize = header->setSize; } if (reportCreation) cerr << "about to construct BitVector for " << filename << " content " << whichBv << endl; bf->bvs[0] = BitVector::bit_vector(filename,bvInfo.compressor,bvInfo.offset,bvInfo.numBytes); } else { if (reportCreation) cerr << "about to construct BitVector for " << filename << " content " << whichBv << endl; bf->bvs[whichBv] = BitVector::bit_vector(filename,bvInfo.compressor,bvInfo.offset,bvInfo.numBytes); } bf->bvs[whichBv]->filterInfo = header->info[infoIx].filterInfo; if (whichBv == vectorsPerFilter-1) { bf->ready = true; //…… do we really want to do this here? content.emplace_back(bvInfo.name,bf); } } if ((trackMemory) && (header != nullptr)) cerr << "@-" << header << " discarding bf file header for \"" << filename << "\"" << endl; if (header != nullptr) delete[] header; return content; } //---------- // // false_positive_rate-- // Estimate the kmer false positive rate of a bloom filter. // //---------- // // Arguments: // u32 numHashes: The bloom filter's number of hash functions. // u64 numBits: The number of bits in the bloom filter's (conceptual) // bit vector. // u64 numItems: The number of distinct items that have been inserted // into the bloom filter. This is the size of the set the // bloom filter represents. // // Returns: // An estimate of the false positive rate. // //---------- // // Implementation notes: // (1) The formula comes from the bloom filter wikipedia page (reference [2]). // In that description, k is the number of hash functions, m is the number // of bits, and n is the number of inserted elements. // //---------- double BloomFilter::false_positive_rate (u32 numHashes, u64 numBits, u64 numItems) { double fpRate; if (numHashes < 1) fpRate = 1.0; else if (numHashes == 1) fpRate = 1 - exp(-double(numItems)/double(numBits)); else fpRate = pow(1 - exp(-double(numHashes*numItems)/double(numBits)),numHashes); return fpRate; }
28.954426
124
0.646488
[ "object", "vector" ]
5378ffca59ccaa6a4dcbed21673bd6ee9604e1f7
4,043
cpp
C++
src/Entities/Entity.cpp
Gegel85/GameJam2020
c6f9f0fd83ddea9a069b1775b7e3de6d38e0d59d
[ "CC0-1.0" ]
1
2020-01-31T19:17:42.000Z
2020-01-31T19:17:42.000Z
src/Entities/Entity.cpp
Gegel85/GameJam2020
c6f9f0fd83ddea9a069b1775b7e3de6d38e0d59d
[ "CC0-1.0" ]
null
null
null
src/Entities/Entity.cpp
Gegel85/GameJam2020
c6f9f0fd83ddea9a069b1775b7e3de6d38e0d59d
[ "CC0-1.0" ]
3
2020-01-31T19:18:38.000Z
2020-02-15T13:24:16.000Z
// // Created by andgel on 31/01/2020 // #include <iostream> #include "../Rendering/Screen.hpp" #include "Entity.hpp" #include "../Game.hpp" namespace DungeonIntern { Entity::Entity(unsigned maxHealth, EntityConfig cfg, float maxSpeed, float x, float y, unsigned sx, unsigned sy, Orientation r) : _entity(cfg.screen.addEntity(cfg.entityJsonPath)), _maxSpeed(maxSpeed), _maxHealth(maxHealth), _health(maxHealth), _pos(x, y, r), _size(sx, sy / 2), _map(cfg.map), _screen(cfg.screen) { this->_entity.setSize({sx + 8, sy + 8}); } const Position<float> &Entity::getOldPosition() const { return _old_position; } void Entity::setSpeed(float speed) { _speed = speed; } bool Entity::destroyed() const { return this->_destroyed; } void Entity::destroy() { this->_destroyed = true; } void Entity::render() { if (this->isDead()) this->_entity.setAnimation(Rendering::DEAD); else this->_entity.setAnimation(this->_speed != 0 ? Rendering::WALK : Rendering::IDLE); this->_entity.setPosition({this->_pos.x - 4, this->_pos.y - 4}); this->_entity.update(); } const Position<float> &Entity::getPos() const { return _pos; } void Entity::setPos(const Position<float> &pos) { _pos = pos; } Entity::~Entity() { this->_screen.removeEntity(this->_entity); logger.debug("Entity destroyed"); } void Entity::move(double angle, bool dontmoveangle) { this->_old_position = this->_pos; this->_pos.x += std::cos(angle) * this->_speed; this->_pos.y += std::sin(angle) * this->_speed; if (dontmoveangle) return; while (angle < 0) angle += 2 * M_PI; angle = std::fmod(angle, 2 * M_PI); if (std::abs(std::cos(angle)) * this->_speed > M_PI_4) this->_entity.setDirection((angle > M_PI_2 && angle < 3 * M_PI_2) ? Rendering::WEST : Rendering::EAST); if (angle < M_PI_4) this->_pos.r = Orientation::EAST; else if (angle < M_PI_4 * 3) this->_pos.r = Orientation::SOUTH; else if (angle < M_PI + M_PI_4) this->_pos.r = Orientation::WEST; else this->_pos.r = Orientation::NORTH; } float Entity::getSpeed() const { return _speed; } void Entity::takeDamage(unsigned damages) { if (this->isDead()) return; if (damages > this->_health) this->_health = 0; else this->_health -= damages; if (this->_health == 0) { onDeath(); this->_dead = true; } } void Entity::update() { for (auto &block : this->_map.getObjects()) { auto &pos = block->getPosition(); auto &size = block->getSize(); if (this->collideWith(pos, size)) { block->onWalk(*this); } } for (auto &entity_ptr : this->_map.getEntities()) { if (&*entity_ptr != this && this->collideWith(entity_ptr->_pos, entity_ptr->_size)) this->onCollide(*entity_ptr); } } bool Entity::collideWith(const Position<int> &pos, const Size<unsigned> &size) const { return ( (pos.x <= this->_pos.x + this->_size.x * 0.3 && this->_pos.x + this->_size.x * 0.3 < pos.x + size.x) || (pos.x <= this->_pos.x + this->_size.x - this->_size.x * 0.3 && this->_pos.x + this->_size.x - this->_size.x * 0.3 < pos.x + size.x) ) && ( (pos.y <= this->_pos.y + this->_size.y && this->_pos.y + this->_size.y < pos.y + size.y) || (pos.y <= this->_pos.y + this->_size.y * 2 && this->_pos.y + this->_size.y * 2 < pos.y + size.y) ); } bool Entity::collideWith(const Position<float> &pos, const Size<unsigned> &size) const { return ( (pos.x <= this->_pos.x + this->_size.x * 0.3 && this->_pos.x + this->_size.x * 0.3 < pos.x + size.x) || (pos.x <= this->_pos.x + this->_size.x - this->_size.x * 0.3 && this->_pos.x + this->_size.x - this->_size.x * 0.3 < pos.x + size.x) ) && ( (pos.y <= this->_pos.y + this->_size.y && this->_pos.y + this->_size.y < pos.y + size.y) || (pos.y <= this->_pos.y + this->_size.y * 2 && this->_pos.y + this->_size.y * 2 < pos.y + size.y) ); } const Size<unsigned> & Entity::getSize() const { return _size; } bool Entity::isDead() const { return this->_dead; } }
25.111801
140
0.613159
[ "render" ]
53828f224ea3562f7587d8c1633664a3770edb42
952
cpp
C++
classwork/04_assign/main.cpp
acc-cosc-1337-spring-2019/acc-cosc-1337-spring-2019-RJMcManamy
9bc28fa87c5efebc512f71c61620875b690ce95b
[ "MIT" ]
null
null
null
classwork/04_assign/main.cpp
acc-cosc-1337-spring-2019/acc-cosc-1337-spring-2019-RJMcManamy
9bc28fa87c5efebc512f71c61620875b690ce95b
[ "MIT" ]
null
null
null
classwork/04_assign/main.cpp
acc-cosc-1337-spring-2019/acc-cosc-1337-spring-2019-RJMcManamy
9bc28fa87c5efebc512f71c61620875b690ce95b
[ "MIT" ]
null
null
null
#include "sequence.h" /* Write code to create a vector of string names, add the values "John", "Mary", "Patty", "Sam" to the vector, call the function display_vector and pass the names vector as an argument, prompt user for a name to search for and a value to replace searched value with. Afterward, call the update_vector_element with the names vector and call the display_vector function. Don't worry about displaying a message for values that aren't found. Assume user will give you a valid name. */ int main() { string search_value = ""; string replace_value = ""; vector <string> str = {"John", "Mary", "Patty", "Sam"}; display_vector(str); cout << "\n" << "Please enter a name to search for: "; cin >> search_value; cout << "\n" << "Please enter a name to replace it with: "; cin >> replace_value; cout << "\n"; update_vector_element(str, search_value, replace_value); display_vector(str); return 0; }
32.827586
94
0.693277
[ "vector" ]
5388d44c6f5ad13fbe09a8d0aa825446fe4a4f26
13,150
cc
C++
content/browser/indexed_db/leveldb/leveldb_transaction.cc
MIPS/external-chromium_org
e31b3128a419654fd14003d6117caa8da32697e7
[ "BSD-3-Clause" ]
2
2018-11-24T07:58:44.000Z
2019-02-22T21:02:46.000Z
content/browser/indexed_db/leveldb/leveldb_transaction.cc
carlosavignano/android_external_chromium_org
2b5652f7889ccad0fbdb1d52b04bad4c23769547
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/indexed_db/leveldb/leveldb_transaction.cc
carlosavignano/android_external_chromium_org
2b5652f7889ccad0fbdb1d52b04bad4c23769547
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2017-07-31T19:09:52.000Z
2019-01-04T18:48:50.000Z
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/indexed_db/leveldb/leveldb_transaction.h" #include "base/logging.h" #include "content/browser/indexed_db/leveldb/leveldb_database.h" #include "content/browser/indexed_db/leveldb/leveldb_write_batch.h" #include "third_party/leveldatabase/src/include/leveldb/db.h" using base::StringPiece; namespace content { LevelDBTransaction::LevelDBTransaction(LevelDBDatabase* db) : db_(db), snapshot_(db), comparator_(db->Comparator()), finished_(false) { tree_.abstractor().comparator_ = comparator_; } LevelDBTransaction::AVLTreeNode::AVLTreeNode() {} LevelDBTransaction::AVLTreeNode::~AVLTreeNode() {} void LevelDBTransaction::ClearTree() { TreeType::Iterator iterator; iterator.StartIterLeast(&tree_); std::vector<AVLTreeNode*> nodes; while (*iterator) { nodes.push_back(*iterator); ++iterator; } tree_.Purge(); for (size_t i = 0; i < nodes.size(); ++i) delete nodes[i]; } LevelDBTransaction::~LevelDBTransaction() { ClearTree(); } void LevelDBTransaction::Set(const StringPiece& key, std::string* value, bool deleted) { DCHECK(!finished_); bool new_node = false; AVLTreeNode* node = tree_.Search(key); if (!node) { node = new AVLTreeNode; node->key = key.as_string(); tree_.Insert(node); new_node = true; } node->value.swap(*value); node->deleted = deleted; if (new_node) NotifyIteratorsOfTreeChange(); } void LevelDBTransaction::Put(const StringPiece& key, std::string* value) { Set(key, value, false); } void LevelDBTransaction::Remove(const StringPiece& key) { std::string empty; Set(key, &empty, true); } bool LevelDBTransaction::Get(const StringPiece& key, std::string* value, bool* found) { *found = false; DCHECK(!finished_); AVLTreeNode* node = tree_.Search(key); if (node) { if (node->deleted) return true; *value = node->value; *found = true; return true; } bool ok = db_->Get(key, value, found, &snapshot_); if (!ok) { DCHECK(!*found); return false; } return true; } bool LevelDBTransaction::Commit() { DCHECK(!finished_); if (tree_.IsEmpty()) { finished_ = true; return true; } scoped_ptr<LevelDBWriteBatch> write_batch = LevelDBWriteBatch::Create(); TreeType::Iterator iterator; iterator.StartIterLeast(&tree_); while (*iterator) { AVLTreeNode* node = *iterator; if (!node->deleted) write_batch->Put(node->key, node->value); else write_batch->Remove(node->key); ++iterator; } if (!db_->Write(*write_batch)) return false; ClearTree(); finished_ = true; return true; } void LevelDBTransaction::Rollback() { DCHECK(!finished_); finished_ = true; ClearTree(); } scoped_ptr<LevelDBIterator> LevelDBTransaction::CreateIterator() { return TransactionIterator::Create(this).PassAs<LevelDBIterator>(); } scoped_ptr<LevelDBTransaction::TreeIterator> LevelDBTransaction::TreeIterator::Create(LevelDBTransaction* transaction) { return make_scoped_ptr(new TreeIterator(transaction)); } bool LevelDBTransaction::TreeIterator::IsValid() const { return !!*iterator_; } void LevelDBTransaction::TreeIterator::SeekToLast() { iterator_.StartIterGreatest(tree_); if (IsValid()) key_ = (*iterator_)->key; } void LevelDBTransaction::TreeIterator::Seek(const StringPiece& target) { iterator_.StartIter(tree_, target, TreeType::EQUAL); if (!IsValid()) iterator_.StartIter(tree_, target, TreeType::GREATER); if (IsValid()) key_ = (*iterator_)->key; } void LevelDBTransaction::TreeIterator::Next() { DCHECK(IsValid()); ++iterator_; if (IsValid()) { DCHECK_GE(transaction_->comparator_->Compare((*iterator_)->key, key_), 0); key_ = (*iterator_)->key; } } void LevelDBTransaction::TreeIterator::Prev() { DCHECK(IsValid()); --iterator_; if (IsValid()) { DCHECK_LT(tree_->abstractor().comparator_->Compare((*iterator_)->key, key_), 0); key_ = (*iterator_)->key; } } StringPiece LevelDBTransaction::TreeIterator::Key() const { DCHECK(IsValid()); return key_; } StringPiece LevelDBTransaction::TreeIterator::Value() const { DCHECK(IsValid()); DCHECK(!IsDeleted()); return (*iterator_)->value; } bool LevelDBTransaction::TreeIterator::IsDeleted() const { DCHECK(IsValid()); return (*iterator_)->deleted; } void LevelDBTransaction::TreeIterator::Reset() { DCHECK(IsValid()); iterator_.StartIter(tree_, key_, TreeType::EQUAL); DCHECK(IsValid()); } LevelDBTransaction::TreeIterator::~TreeIterator() {} LevelDBTransaction::TreeIterator::TreeIterator(LevelDBTransaction* transaction) : tree_(&transaction->tree_), transaction_(transaction) {} scoped_ptr<LevelDBTransaction::TransactionIterator> LevelDBTransaction::TransactionIterator::Create( scoped_refptr<LevelDBTransaction> transaction) { return make_scoped_ptr(new TransactionIterator(transaction)); } LevelDBTransaction::TransactionIterator::TransactionIterator( scoped_refptr<LevelDBTransaction> transaction) : transaction_(transaction), comparator_(transaction_->comparator_), tree_iterator_(TreeIterator::Create(transaction_.get())), db_iterator_(transaction_->db_->CreateIterator(&transaction_->snapshot_)), current_(0), direction_(FORWARD), tree_changed_(false) { transaction_->RegisterIterator(this); } LevelDBTransaction::TransactionIterator::~TransactionIterator() { transaction_->UnregisterIterator(this); } bool LevelDBTransaction::TransactionIterator::IsValid() const { return !!current_; } void LevelDBTransaction::TransactionIterator::SeekToLast() { tree_iterator_->SeekToLast(); db_iterator_->SeekToLast(); direction_ = REVERSE; HandleConflictsAndDeletes(); SetCurrentIteratorToLargestKey(); } void LevelDBTransaction::TransactionIterator::Seek(const StringPiece& target) { tree_iterator_->Seek(target); db_iterator_->Seek(target); direction_ = FORWARD; HandleConflictsAndDeletes(); SetCurrentIteratorToSmallestKey(); } void LevelDBTransaction::TransactionIterator::Next() { DCHECK(IsValid()); if (tree_changed_) RefreshTreeIterator(); if (direction_ != FORWARD) { // Ensure the non-current iterator is positioned after Key(). LevelDBIterator* non_current = (current_ == db_iterator_.get()) ? tree_iterator_.get() : db_iterator_.get(); non_current->Seek(Key()); if (non_current->IsValid() && !comparator_->Compare(non_current->Key(), Key())) non_current->Next(); // Take an extra step so the non-current key is // strictly greater than Key(). DCHECK(!non_current->IsValid() || comparator_->Compare(non_current->Key(), Key()) > 0); direction_ = FORWARD; } current_->Next(); HandleConflictsAndDeletes(); SetCurrentIteratorToSmallestKey(); } void LevelDBTransaction::TransactionIterator::Prev() { DCHECK(IsValid()); if (tree_changed_) RefreshTreeIterator(); if (direction_ != REVERSE) { // Ensure the non-current iterator is positioned before Key(). LevelDBIterator* non_current = (current_ == db_iterator_.get()) ? tree_iterator_.get() : db_iterator_.get(); non_current->Seek(Key()); if (non_current->IsValid()) { // Iterator is at first entry >= Key(). // Step back once to entry < key. // This is why we don't check for the keys being the same before // stepping, like we do in Next() above. non_current->Prev(); } else { non_current->SeekToLast(); // Iterator has no entries >= Key(). Position // at last entry. } DCHECK(!non_current->IsValid() || comparator_->Compare(non_current->Key(), Key()) < 0); direction_ = REVERSE; } current_->Prev(); HandleConflictsAndDeletes(); SetCurrentIteratorToLargestKey(); } StringPiece LevelDBTransaction::TransactionIterator::Key() const { DCHECK(IsValid()); if (tree_changed_) RefreshTreeIterator(); return current_->Key(); } StringPiece LevelDBTransaction::TransactionIterator::Value() const { DCHECK(IsValid()); if (tree_changed_) RefreshTreeIterator(); return current_->Value(); } void LevelDBTransaction::TransactionIterator::TreeChanged() { tree_changed_ = true; } void LevelDBTransaction::TransactionIterator::RefreshTreeIterator() const { DCHECK(tree_changed_); tree_changed_ = false; if (tree_iterator_->IsValid() && tree_iterator_.get() == current_) { tree_iterator_->Reset(); return; } if (db_iterator_->IsValid()) { // There could be new nodes in the tree that we should iterate over. if (direction_ == FORWARD) { // Try to seek tree iterator to something greater than the db iterator. tree_iterator_->Seek(db_iterator_->Key()); if (tree_iterator_->IsValid() && !comparator_->Compare(tree_iterator_->Key(), db_iterator_->Key())) tree_iterator_->Next(); // If equal, take another step so the tree // iterator is strictly greater. } else { // If going backward, seek to a key less than the db iterator. DCHECK_EQ(REVERSE, direction_); tree_iterator_->Seek(db_iterator_->Key()); if (tree_iterator_->IsValid()) tree_iterator_->Prev(); } } } bool LevelDBTransaction::TransactionIterator::TreeIteratorIsLower() const { return comparator_->Compare(tree_iterator_->Key(), db_iterator_->Key()) < 0; } bool LevelDBTransaction::TransactionIterator::TreeIteratorIsHigher() const { return comparator_->Compare(tree_iterator_->Key(), db_iterator_->Key()) > 0; } void LevelDBTransaction::TransactionIterator::HandleConflictsAndDeletes() { bool loop = true; while (loop) { loop = false; if (tree_iterator_->IsValid() && db_iterator_->IsValid() && !comparator_->Compare(tree_iterator_->Key(), db_iterator_->Key())) { // For equal keys, the tree iterator takes precedence, so move the // database iterator another step. if (direction_ == FORWARD) db_iterator_->Next(); else db_iterator_->Prev(); } // Skip over delete markers in the tree iterator until it catches up with // the db iterator. if (tree_iterator_->IsValid() && tree_iterator_->IsDeleted()) { if (direction_ == FORWARD && (!db_iterator_->IsValid() || TreeIteratorIsLower())) { tree_iterator_->Next(); loop = true; } else if (direction_ == REVERSE && (!db_iterator_->IsValid() || TreeIteratorIsHigher())) { tree_iterator_->Prev(); loop = true; } } } } void LevelDBTransaction::TransactionIterator::SetCurrentIteratorToSmallestKey() { LevelDBIterator* smallest = 0; if (tree_iterator_->IsValid()) smallest = tree_iterator_.get(); if (db_iterator_->IsValid()) { if (!smallest || comparator_->Compare(db_iterator_->Key(), smallest->Key()) < 0) smallest = db_iterator_.get(); } current_ = smallest; } void LevelDBTransaction::TransactionIterator::SetCurrentIteratorToLargestKey() { LevelDBIterator* largest = 0; if (tree_iterator_->IsValid()) largest = tree_iterator_.get(); if (db_iterator_->IsValid()) { if (!largest || comparator_->Compare(db_iterator_->Key(), largest->Key()) > 0) largest = db_iterator_.get(); } current_ = largest; } void LevelDBTransaction::RegisterIterator(TransactionIterator* iterator) { DCHECK(iterators_.find(iterator) == iterators_.end()); iterators_.insert(iterator); } void LevelDBTransaction::UnregisterIterator(TransactionIterator* iterator) { DCHECK(iterators_.find(iterator) != iterators_.end()); iterators_.erase(iterator); } void LevelDBTransaction::NotifyIteratorsOfTreeChange() { for (std::set<TransactionIterator*>::iterator i = iterators_.begin(); i != iterators_.end(); ++i) { TransactionIterator* transaction_iterator = *i; transaction_iterator->TreeChanged(); } } scoped_ptr<LevelDBWriteOnlyTransaction> LevelDBWriteOnlyTransaction::Create( LevelDBDatabase* db) { return make_scoped_ptr(new LevelDBWriteOnlyTransaction(db)); } LevelDBWriteOnlyTransaction::LevelDBWriteOnlyTransaction(LevelDBDatabase* db) : db_(db), write_batch_(LevelDBWriteBatch::Create()), finished_(false) {} LevelDBWriteOnlyTransaction::~LevelDBWriteOnlyTransaction() { write_batch_->Clear(); } void LevelDBWriteOnlyTransaction::Remove(const StringPiece& key) { DCHECK(!finished_); write_batch_->Remove(key); } bool LevelDBWriteOnlyTransaction::Commit() { DCHECK(!finished_); if (!db_->Write(*write_batch_)) return false; finished_ = true; write_batch_->Clear(); return true; } } // namespace content
27.568134
80
0.678859
[ "vector" ]
538f6c406f08a53cfce4a158c33a0dbe9163898d
2,676
cpp
C++
test/Group-test.cpp
jpunzel/jray
a78792356f8ffafdb41fd958f24b4bcebc165507
[ "Unlicense" ]
null
null
null
test/Group-test.cpp
jpunzel/jray
a78792356f8ffafdb41fd958f24b4bcebc165507
[ "Unlicense" ]
null
null
null
test/Group-test.cpp
jpunzel/jray
a78792356f8ffafdb41fd958f24b4bcebc165507
[ "Unlicense" ]
null
null
null
#include "gtest/gtest.h" #include "Tuple.h" #include "Vector.h" #include "Point.h" #include "Ray.h" #include "Sphere.h" #include "Group.h" #include <iostream> #include <memory> TEST(GroupTest, intersectEmptyGroup) { auto g = Group::make(); Ray r = Ray(Point(0,0,0), Vector(0,0,1)); Iset xs; bool hit = g->localIntersect(r, xs); EXPECT_FALSE(hit); EXPECT_EQ(xs.size(), 0); } TEST(GroupTest, intersectNonemptyGroup) { auto g = Group::make(); auto s1 = Sphere::make(); auto s2 = Sphere::make(); s2->setTransform(Matrix::translation(0,0,-3)); auto s3 = Sphere::make(); s3->setTransform(Matrix::translation(5,0,0)); g->addChild(s1); g->addChild(s2); g->addChild(s3); Ray r = Ray(Point(0,0,-5), Vector(0,0,1)); Iset xs; bool hit = g->localIntersect(r, xs); EXPECT_TRUE(hit); EXPECT_EQ(xs.size(), 4); auto it = xs.begin(); EXPECT_EQ(it->obj, s2); EXPECT_EQ(it->obj->getParent(), g); EXPECT_EQ((++it)->obj, s2); EXPECT_EQ((++it)->obj, s1); EXPECT_EQ((++it)->obj, s1); } TEST(GroupTest, intersectTransformedGroup) { auto g = Group::make(); g->setTransform(Matrix::scaling(2,2,2)); auto s = Sphere::make(); s->setTransform(Matrix::translation(5,0,0)); g->addChild(s); Ray r = Ray(Point(10,0,-10), Vector(0,0,1)); Iset xs; g->intersect(r, xs); EXPECT_EQ(xs.size(), 2); } TEST(GroupTest, worldToObject) { auto g1 = Group::make(); auto g2 = Group::make(); g1->setTransform(Matrix::rotation_y(PI/2)); g2->setTransform(Matrix::scaling(2,2,2)); g1->addChild(g2); auto s = Sphere::make(); s->setTransform(Matrix::translation(5,0,0)); g2->addChild(s); Point p = s->world_to_object(Point(-2,0,-10)); EXPECT_EQ(p, Point(0,0,-1)); } TEST(GroupTest, normalObjectToWorld) { auto g1 = Group::make(); auto g2 = Group::make(); g1->setTransform(Matrix::rotation_y(PI/2)); g2->setTransform(Matrix::scaling(1,2,3)); g1->addChild(g2); auto s = Sphere::make(); s->setTransform(Matrix::translation(5,0,0)); g2->addChild(s); Vector n = s->normal_to_world(Vector(sqrt(3)/3, sqrt(3)/3, sqrt(3)/3)); EXPECT_EQ(n, Vector(0.285714, 0.428571, -0.857143)); } TEST(GroupTest, normalOnChildObject) { auto g1 = Group::make(); auto g2 = Group::make(); g1->setTransform(Matrix::rotation_y(PI/2)); g2->setTransform(Matrix::scaling(1,2,3)); g1->addChild(g2); auto s = Sphere::make(); s->setTransform(Matrix::translation(5,0,0)); g2->addChild(s); Vector n = s->normalAt(Point(1.7321, 1.1547, -5.5774)); EXPECT_EQ(n, Vector(0.285704, 0.428543, -0.857161)); }
28.774194
75
0.608371
[ "vector" ]
5391cd7ad0a736ca8c4906a85b256ece973afeae
5,707
cpp
C++
src/cg/data/model.cpp
ref2401/cg
4654377f94fe54945c33156911ca25e807c96236
[ "MIT" ]
2
2019-04-02T14:19:01.000Z
2021-05-27T13:42:20.000Z
src/cg/data/model.cpp
ref2401/cg
4654377f94fe54945c33156911ca25e807c96236
[ "MIT" ]
4
2016-11-05T14:17:14.000Z
2017-03-30T15:03:37.000Z
src/cg/data/model.cpp
ref2401/cg
4654377f94fe54945c33156911ca25e807c96236
[ "MIT" ]
null
null
null
#include "cg/data/model.h" #include "cg/base/base.h" #include "cg/data/model_assimp.h" namespace { using cg::data::Assimp_postprocess_flags; using cg::data::Model_geometry_data; using cg::data::Model_geometry_vertex; using cg::data::vertex_attribs; using cg::data::make_cg_vector; template<vertex_attribs attribs> Model_geometry_data<attribs> load_model(const char* filename, const Assimp_postprocess_flags& flags) { Assimp::Importer importer; const aiScene* scene = cg::data::load_model(importer, filename, flags); size_t base_vertex = 0; size_t index_offset = 0; Model_geometry_data<attribs> geometry_data(scene->mNumMeshes); for (size_t mi = 0; mi < scene->mNumMeshes; ++mi) { const aiMesh* mesh = scene->mMeshes[mi]; geometry_data.push_back_mesh(mesh->mNumVertices, base_vertex, mesh->mNumFaces * 3, index_offset); for (size_t vi = 0; vi < mesh->mNumVertices; ++vi) { process_vertex(geometry_data, mesh, vi); } for (size_t fi = 0; fi < mesh->mNumFaces; ++fi) { const aiFace& face = mesh->mFaces[fi]; assert(face.mNumIndices == 3); geometry_data.push_back_indices(face.mIndices[0], face.mIndices[1], face.mIndices[2]); } base_vertex += mesh->mNumVertices; index_offset = mesh->mNumFaces * 3; } return geometry_data; } void process_vertex(Model_geometry_data<vertex_attribs::p>& geometry_data, const aiMesh* mesh, size_t vertex_index) { assert(mesh); assert(vertex_index < mesh->mNumVertices); Model_geometry_vertex<vertex_attribs::p> vertex( make_cg_vector(mesh->mVertices[vertex_index]) ); geometry_data.push_back_vertex(vertex); } void process_vertex(Model_geometry_data<vertex_attribs::p_n>& geometry_data, const aiMesh* mesh, size_t vertex_index) { assert(mesh); assert(vertex_index < mesh->mNumVertices); Model_geometry_vertex<vertex_attribs::p_n> vertex( make_cg_vector(mesh->mVertices[vertex_index]), normalize(make_cg_vector(mesh->mNormals[vertex_index]))); geometry_data.push_back_vertex(vertex); } void process_vertex(Model_geometry_data<vertex_attribs::p_n_tc>& geometry_data, const aiMesh* mesh, size_t vertex_index) { assert(mesh); assert(vertex_index < mesh->mNumVertices); Model_geometry_vertex<vertex_attribs::p_n_tc> vertex( make_cg_vector(mesh->mVertices[vertex_index]), normalize(make_cg_vector(mesh->mNormals[vertex_index])), make_cg_vector(mesh->mTextureCoords[0][vertex_index]).xy()); geometry_data.push_back_vertex(vertex); } void process_vertex(Model_geometry_data<vertex_attribs::p_tc>& geometry_data, const aiMesh* mesh, size_t vertex_index) { assert(mesh); assert(vertex_index < mesh->mNumVertices); Model_geometry_vertex<vertex_attribs::p_tc> vertex( make_cg_vector(mesh->mVertices[vertex_index]), make_cg_vector(mesh->mTextureCoords[0][vertex_index]).xy()); geometry_data.push_back_vertex(vertex); } void process_vertex(Model_geometry_data<vertex_attribs::p_n_tc_ts>& geometry_data, const aiMesh* mesh, size_t vertex_index) { assert(mesh); assert(vertex_index < mesh->mNumVertices); // NOTE(ref2401): bitangent is negated because assimp computes it in the wrong direction. float3 position = make_cg_vector(mesh->mVertices[vertex_index]); float3 normal = normalize(make_cg_vector(mesh->mNormals[vertex_index])); float2 tex_coord = make_cg_vector(mesh->mTextureCoords[0][vertex_index]).xy(); float3 tangent = normalize(make_cg_vector(mesh->mTangents[vertex_index])); float3 bitangent = -normalize(make_cg_vector(mesh->mBitangents[vertex_index])); float4 tangent_h = cg::data::compute_tangent_handedness(tangent, bitangent, normal); Model_geometry_vertex<vertex_attribs::p_n_tc_ts> vertex( position, normal, tex_coord, tangent_h); geometry_data.push_back_vertex(vertex); } } // namespace namespace cg { namespace data { // ----- funcs ----- std::ostream& operator<<(std::ostream& o, const Model_mesh_info& mi) { o << "Model_mesh_info(" << mi.vertex_count << ", " << mi.base_vertex << ", " << mi.index_count << ", " << mi.index_offset << ")"; return o; } std::wostream& operator<<(std::wostream& o, const Model_mesh_info& mi) { o << "Model_mesh_info(" << mi.vertex_count << ", " << mi.base_vertex << ", " << mi.index_count << ", " << mi.index_offset << ")"; return o; } template<> Model_geometry_data<vertex_attribs::p> load_model<vertex_attribs::p>(const char* filename) { Assimp_postprocess_flags flags = default_load_flags; return ::load_model<vertex_attribs::p>(filename, flags); } template<> Model_geometry_data<vertex_attribs::p_n> load_model<vertex_attribs::p_n>(const char* filename) { Assimp_postprocess_flags flags = default_load_flags | aiProcess_GenNormals; return ::load_model<vertex_attribs::p_n>(filename, flags); } template<> Model_geometry_data<vertex_attribs::p_n_tc> load_model<vertex_attribs::p_n_tc>(const char* filename) { Assimp_postprocess_flags flags = default_load_flags | aiProcess_GenNormals; return ::load_model<vertex_attribs::p_n_tc>(filename, flags); } template<> Model_geometry_data<vertex_attribs::p_tc> load_model<vertex_attribs::p_tc>(const char* filename) { Assimp_postprocess_flags flags = default_load_flags; return ::load_model<vertex_attribs::p_tc>(filename, flags); } template<> Model_geometry_data<vertex_attribs::p_n_tc_ts> load_model<vertex_attribs::p_n_tc_ts>(const char* filename) { Assimp_postprocess_flags flags = default_load_flags | aiProcess_GenNormals | aiProcess_CalcTangentSpace; return ::load_model<vertex_attribs::p_n_tc_ts>(filename, flags); } } // namespace data } // namespace cg
30.848649
107
0.73734
[ "mesh", "model" ]
5395011b94c89d1f93ec90f811b65f92d2878da6
6,418
hpp
C++
Noxis/Node.hpp
mr-linch/noxis
7b8015bc36f478a81aafa3fb7ef84156ff642343
[ "MIT" ]
null
null
null
Noxis/Node.hpp
mr-linch/noxis
7b8015bc36f478a81aafa3fb7ef84156ff642343
[ "MIT" ]
3
2017-07-28T12:56:52.000Z
2017-07-28T12:56:52.000Z
Noxis/Node.hpp
mr-linch/noxis
7b8015bc36f478a81aafa3fb7ef84156ff642343
[ "MIT" ]
null
null
null
#pragma once #include "ns.hpp" #include "Transform.hpp" #include <list> #include <string> NOXIS_NS_BEGIN; class Renderer; class Node { public: /** * @brief Create node * @param name name of this node * @param parent pointer to parent of this node in scene tree, if this is root set to nullptr */ Node(const std::string &name = "noname", Node *parent = nullptr); Node(Node *parent = nullptr); virtual ~Node(); /** * @brief Attach child to node * * Attach child to this node, its parent automatically * set this node. * * @param child pointer to child * * @return this */ Node* attachChild(Node *child); /** * @brief Detach child of the node * @param child pointer to child */ void detachChild(Node *child); /** * @brief Detach child of the node with specific name * @param name name of the child * @see destroyChild * @return if to the node attached child with specific name, then pointer to him, else nullptr */ Node* detachChild(const std::string &name); /** * @brief Detach all child of this node */ void detachAllChildren(); /** * @brief Detach and destroy all child of this node */ void destroyAllChildren(); /** * @brief Detach current node from parent */ void detachFromParent(); /** * @brief Detach and destroy child of this node * @param child child node */ void destroyChild(Node *child); /** * @brief Detach and destroy child of this node, by specific name * @param name name of child node */ void destroyChild(const std::string &name); /** * @brief Get child with specific name * @param name name of child node * @return pointer to child or nullptr */ Node* getChild(const std::string &name); /** * @brief Get children list */ const std::list<Node*>& getChildren() const; /** * @brief Check if to the node attached child * @param child pointer to child * @return true, if child is attached */ bool hasChild(const Node *child) const; /** * @brief Check if to the node attached child with specific name * @param name name of the child * @return true, if child is attached */ bool hasChild(const std::string &name) const; /** * @brief Check if this node is root */ bool isRoot() const; /** * @brief Get root of tree */ Node* getRoot() const; /** * @brief Get name of node */ const std::string& getName() const; /** * @brief Set name of node */ void setName(const std::string &name); /** * @brief Get parent of this node */ Node* getParent() const; /** * @brief Set parent of this node */ void setParent(Node *node); /** * @brief Called every frame for update object state */ virtual void onUpdate(unsigned deltatime); /** * @brief Update this node and all children recursive */ void update(unsigned deltatime); /** * @brief Called every frame for draw object state */ virtual void onRender(Renderer* render); /** * @brief Render this node and all children recursice */ void render(Renderer *render); /** * @brief Find first node with specific name */ Node* find(const std::string &name) const; /** * @brief Find all nodes with specific name */ std::list<Node*> finds(const std::string &name) const; /** * @brief Check if node is visible */ bool isVisible() const; /** * @brief Set visible */ void setVisible(bool value); /** * @brief Check if node is sleep */ bool isSleeping() const; /** * @brief Update transform */ void updateTransform(bool dirty); /** * @brief Set sleep */ void setSleep(bool value); /** * @brief Get local transform of node */ const Transform& getLocalTransform() const; Transform& getLocalTransform(); /** * @brief Get world transform of node */ const Transform& getWorldTransform() const; /** * @brief Set local X position */ void setX(int x); /** * @brief Set local Y position */ void setY(int y); /** * @brief Get local X position */ int getX() const; /** * @brief Get local Y position */ int getY() const; /** * @brief Get world X position */ int getWorldX() const; /** * @brief Get world Y position */ int getWorldY() const; /** * @brief Get position of node */ const Vector2i& getPosition() const; /** * @brief Set position of node */ void setPosition(int x, int y); void setPosition(const Vector2i &center); /** * @brief Get size of node */ const Size& getSize() const; /** * @brief Get width of node */ int getWidth() const; /** * @brief Get height of node */ int getHeight() const; protected: const Transform& getParentWorldTransform() const; void setSize(const Size &size); private: Transform localTransform; Transform worldTransform; Size size; std::string name; Node *parent = nullptr; std::list<Node*> children; bool visible = true; bool sleep; }; NOXIS_NS_END;
22.758865
102
0.492365
[ "render", "object", "transform" ]
5395dbfa42b19f5e46f16b4294333acbdc0d86f2
8,672
cpp
C++
src/RequestHandler.cpp
nicledomaS/BinaryMapper
8ad99c0d39d530b6409ccd6fa4340d6b7086eeb3
[ "Apache-2.0" ]
null
null
null
src/RequestHandler.cpp
nicledomaS/BinaryMapper
8ad99c0d39d530b6409ccd6fa4340d6b7086eeb3
[ "Apache-2.0" ]
null
null
null
src/RequestHandler.cpp
nicledomaS/BinaryMapper
8ad99c0d39d530b6409ccd6fa4340d6b7086eeb3
[ "Apache-2.0" ]
null
null
null
#include "RequestHandler.h" #include "BinaryMapper.h" #include "BinaryObject.h" #include "BinaryData.h" #include "CallData.h" #include "ExecType.h" #include "cpprest/http_msg.h" #include "cpprest/json.h" #include <iostream> #include <functional> #include <map> namespace { constexpr auto NameKey = "name"; constexpr auto TypeKey = "type"; constexpr auto BinaryDataKey = "binary_data"; constexpr auto NamesKey = "Names"; constexpr auto Factories = "Factories"; constexpr auto ErrorTag = "ErrorTag"; constexpr auto ErrorMessage = "ErrorMessage"; constexpr auto UriNamesPath = "/binary/names"; constexpr auto UriFactoriesPath = "/binary/factories"; constexpr auto UriAddBinaryDataPath = "/binary/AddBinaryData"; constexpr auto UriDoCallPath = "/binary/DoCall"; Handler findHandler(const std::map<std::string, Handler>& handlers, const std::string& path) { auto it = handlers.find(path); return it == handlers.end() ? Handler() : it->second; } void handle(const std::map<std::string, Handler>& handlers, web::http::http_request request) { if(auto handler = findHandler(handlers, request.request_uri().path())) { handler(request); } else { request.reply(web::http::status_codes::NotFound); } } web::json::value prepareError(const std::string& tag, const std::string& message) { auto error = web::json::value::object(); error[ErrorTag] = web::json::value::string(tag); error[ErrorMessage] = web::json::value::string(message); return error; } std::unique_ptr<binary_data::BinaryData> toBinaryData(const web::json::value& value) { if(value.is_object()) { auto obj = value.as_object(); auto binaryData = std::make_unique<binary_data::BinaryData>(); binaryData->name = obj[NameKey].as_string(); binaryData->type = binary_data::fromString(obj[TypeKey].as_string()); binaryData->data = utility::conversions::from_base64(obj[BinaryDataKey].as_string()); return binaryData; } return nullptr; } void setString(CallData& callData, const std::string& name, const web::json::value& value) { callData.setValue(name, value.as_string()); } void setBool(CallData& callData, const std::string& name, const web::json::value& value) { callData.setValue(name, value.as_bool()); } void setNumber(CallData& callData, const std::string& name, const web::json::value& value) { if(value.is_integer()) { callData.setValue(name, value.as_integer()); } else if(value.is_double()) { callData.setValue(name, value.as_double()); } else { std::cout << "Number do not support" << std::endl; } } using ValueHandler = std::function<void(CallData&, const std::string&, const web::json::value&)>; static std::map<web::json::value::value_type, ValueHandler> valueHandlers = { { web::json::value::value_type::String, &setString }, { web::json::value::value_type::Boolean, &setBool }, { web::json::value::value_type::Number, &setNumber } }; std::unique_ptr<CallData> toCallData(const web::json::value& value) { if(value.is_object()) { auto obj = value.as_object(); auto callData = std::make_unique<CallData>(); for(const auto& item : obj) { auto it = valueHandlers.find(item.second.type()); if(it != valueHandlers.end()) { it->second(*callData, item.first, item.second); } else { std::cout << "Type do not support" << std::endl; } } return callData; } return nullptr; } } // anonymous RequestHandler::RequestHandler() : m_binaryMapper(createMapper()) { m_getHandlers.insert({ UriNamesPath, [&](web::http::http_request request) { auto names = getBinaryNames(); std::vector<web::json::value> jValues(names.begin(), names.end()); auto answer = web::json::value::object(); answer[NamesKey] = web::json::value::array(std::move(jValues)); request.reply(web::http::status_codes::OK, answer); } }); m_getHandlers.insert({ UriFactoriesPath, [&](web::http::http_request request) { auto names = getFactoryNames(); std::vector<web::json::value> jValues(names.begin(), names.end()); auto answer = web::json::value::object(); answer[Factories] = web::json::value::array(std::move(jValues)); request.reply(web::http::status_codes::OK, answer); } }); m_postHandlers.insert({ UriAddBinaryDataPath, [&](web::http::http_request request) { web::json::value error; try { auto obj = request.extract_json().get(); if(auto binData = toBinaryData(obj)) { addBinaryData(std::move(binData)); request.reply(web::http::status_codes::OK); return; } error = prepareError(UriAddBinaryDataPath, "Bad body"); } catch(const std::exception& ex) { error = prepareError(UriAddBinaryDataPath, ex.what()); } request.reply(web::http::status_codes::BadRequest, error); } }); m_postHandlers.insert({ UriDoCallPath, [&](web::http::http_request request) { web::json::value error; try { auto obj = request.extract_json().get(); if(auto callData = toCallData(obj)) { doCall(std::move(callData)); request.reply(web::http::status_codes::OK); return; } error = prepareError(UriAddBinaryDataPath, "Bad body"); } catch(const std::exception& ex) { error = prepareError(UriAddBinaryDataPath, ex.what()); } request.reply(web::http::status_codes::BadRequest, error); } }); m_deleteHandlers.insert({ UriNamesPath, [&](web::http::http_request request) { web::json::value error; try { auto value = request.extract_json().get(); if(value.is_object()) { auto obj = value.as_object(); auto arrayNames = obj[NamesKey].as_array(); if(arrayNames.size()) { std::vector<std::string> names; std::transform( arrayNames.begin(), arrayNames.end(), std::back_inserter(names), [](const auto& item) { return item.as_string(); }); deleteBinaryData(names); request.reply(web::http::status_codes::OK); return; } } error = prepareError(UriNamesPath, "Bad body"); } catch(const std::exception& ex) { error = prepareError(UriNamesPath, ex.what()); } request.reply(web::http::status_codes::BadRequest, error); } }); } RequestHandler::~RequestHandler() { } void RequestHandler::getHandler(web::http::http_request request) { handle(m_getHandlers, request); } void RequestHandler::putHandler(web::http::http_request request) { handle(m_putHandlers, request); } void RequestHandler::postHandler(web::http::http_request request) { handle(m_postHandlers, request); } void RequestHandler::deleteHandler(web::http::http_request request) { handle(m_deleteHandlers, request); } std::vector<std::string> RequestHandler::getBinaryNames() const { pplx::extensibility::scoped_critical_section_t lck(m_respLock); return m_binaryMapper->getBinaryNames(); } std::vector<std::string> RequestHandler::getFactoryNames() const { pplx::extensibility::scoped_critical_section_t lck(m_respLock); return m_binaryMapper->getFactoryNames(); } bool RequestHandler::addBinaryData(std::unique_ptr<binary_data::BinaryData> binaryData) { pplx::extensibility::scoped_critical_section_t lck(m_respLock); auto obj = m_binaryMapper->create(std::move(binaryData)); return obj != nullptr; } void RequestHandler::deleteBinaryData(const std::vector<std::string>& names) { pplx::extensibility::scoped_critical_section_t lck(m_respLock); for(const auto& name : names) { m_binaryMapper->destroy(name); } } void RequestHandler::doCall(std::unique_ptr<CallData> callData) { pplx::extensibility::scoped_critical_section_t lck(m_respLock); if(auto binaryData = m_binaryMapper->find(callData->getValue<std::string>(NameKey))) { binaryData->execute(*callData); } }
28.620462
97
0.613699
[ "object", "vector", "transform" ]
539d7189f79c2efac01658f1661dbde6ba239c2c
12,147
hpp
C++
src/snake_publisher/include/SnakeGame.hpp
Desperationis/rviz-snake
f54cc3ce921ac9dbbf9b21f769cc57c4505c2149
[ "MIT" ]
null
null
null
src/snake_publisher/include/SnakeGame.hpp
Desperationis/rviz-snake
f54cc3ce921ac9dbbf9b21f769cc57c4505c2149
[ "MIT" ]
null
null
null
src/snake_publisher/include/SnakeGame.hpp
Desperationis/rviz-snake
f54cc3ce921ac9dbbf9b21f769cc57c4505c2149
[ "MIT" ]
null
null
null
#ifndef SNAKEGAME_HPP #define SNAKEGAME_HPP #include <memory> #include <thread> #include <functional> #include <chrono> #include <vector> #include <ncurses.h> #include <csignal> #include <list> #include "rclcpp/rclcpp.hpp" #include "rclcpp/executor.hpp" #include "visualization_msgs/msg/marker.hpp" #include "geometry_msgs/msg/point.hpp" #include "std_msgs/msg/color_rgba.hpp" #include "Markers.hpp" using namespace std::chrono_literals; /** * Snake.hpp * * This files holds classes that directly relate to running "Snake". Everything * is managed interally as simply points, and only get turned into cubes the * moment they are rendered; This allows for multiple possible ways to render * the game. */ /** * Details the color of each game piece. */ struct GamePieceColors { std_msgs::msg::ColorRGBA snakeColor; std_msgs::msg::ColorRGBA fruitColor; std_msgs::msg::ColorRGBA gridColor; }; /** * Wrapper for GridMarker so that origin is at the topleft, x-axis is positive * to the right, y-axis is positive downwards, and the grid is drawn. This is * where points are turned into cubes. */ class SnakeGrid { public: enum GRID_PIECES {EMPTY, SNAKE, FRUIT}; private: int sideLength; int worldXOffset, worldYOffset; std::vector<std::vector<GRID_PIECES>> gridElements; public: /** * Creates a grid that is at maximum size `sideLength` on each side. */ SnakeGrid(int sideLength) { this->sideLength = sideLength; worldXOffset = -sideLength / 2; worldYOffset = -sideLength / 2; for(int i = 0; i < sideLength; i++) { gridElements.push_back(std::vector<GRID_PIECES>()); for(int j = 0; j < sideLength; j++) { gridElements[i].push_back(EMPTY); } } } /** * Determine whether a point is within the bounds of [0, side_length). */ bool InBounds(int x, int y) { return x < sideLength && x >= 0 && y < sideLength && y >= 0; } /** * Reserve a specific spot to be drawn as a snake in the next frame, given * that it is in bounds. If it is not in bounds, nothing will happen. */ void ReserveSnake(int x, int y) { if (this->InBounds(x, y)) { gridElements[y][x] = SNAKE; } } /** * Reserve a specific spot to be drawn as a fruit in the next frame, given * that it is in bounds. If it is not in bounds, nothing will happen. */ void ReserveFruit(int x, int y) { if (this->InBounds(x, y)) { gridElements[y][x] = FRUIT; } } /** * Get the type of piece that is currently reserved. By default, every * square on the grid is reserved EMPTY on every frame. */ GRID_PIECES GetReserved(int x, int y) { return gridElements[y][x]; } /** * Returns the side length of the grid. */ int GetSideLength() { return sideLength; } /** * Draws the grid by iterating through all reserved portions and drawing a * specific cube based on its type. For SNAKE and FRUIT, the square is * elevated by 1 unit in order to give the apperance of 3D. */ void Draw(std::shared_ptr<MarkerPublisher> publisher, GamePieceColors colors) { GridMarker grid; for(size_t i = 0; i < gridElements.size(); i++) { for(size_t j = 0; j < gridElements[i].size(); j++) { GRID_PIECES type = gridElements[i][j]; Cube cube; cube.SetPos(i + worldXOffset, j + worldYOffset, 1); switch(type) { case EMPTY: cube.SetPos(i + worldXOffset, j + worldYOffset, 0); cube.color = colors.gridColor; break; case SNAKE: cube.color = colors.snakeColor; break; case FRUIT: cube.color = colors.fruitColor; break; }; grid.AddCube(cube); } } publisher->PublishMarker(grid); } /** * Completely clears the grid with EMPTY tiles. */ void Clear() { for(int i = 0; i < sideLength; i++) { for(int j = 0; j < sideLength; j++) { gridElements[i][j] = EMPTY; } } } }; struct Fruit { Fruit(int x, int y) { p.x = x; p.y = y; } geometry_msgs::msg::Point p; }; /** * Manager for controlling the spawning and erasing of fruits on the board. */ class FruitManager { public: FruitManager() { requestedFruit = 0; } /** * Randomly spawn a single fruit that is not occupied by a SNAKE tile. * TODO: Prevent this from being an infinite loop should a player good * enough completely fill up the board. */ void SpawnFruit(SnakeGrid snakeGrid) { while(requestedFruit > 0) { int x = rand() % snakeGrid.GetSideLength(); int y = rand() % snakeGrid.GetSideLength(); if(snakeGrid.GetReserved(x, y) == SnakeGrid::EMPTY) { fruits.push_back(Fruit(x, y)); snakeGrid.ReserveFruit(x, y); requestedFruit--; } } } /** * Request a single fruit to be drawn the next frame. Can be called * multiple times for multiple fruits. */ void RequestFruit() { requestedFruit++; } /** * Try to eat a fruit at a specific point. If there is not fruit at that * point, return false. If there is, return true and erase the fruit from * existence. */ bool Eat(int x, int y) { for(size_t i = 0; i < fruits.size(); i++) { auto fruit = fruits[i]; if(fruit.p.x == x && fruit.p.y == y) { fruits.erase(fruits.begin() + i); return true; } } return false; } /** * Get the list of points that occupy fruits. */ std::vector<Fruit> GetFruits() { return fruits; } private: std::vector<Fruit> fruits; // This variable holds the amount of requested fruit that should be spawned // on the next frame. int requestedFruit; }; /** * The Snake. Body is completely represented by points. */ class Snake { public: enum DIRECTION {LEFT, RIGHT, UP, DOWN}; Snake(int x, int y) { Respawn(x, y); } std::list<geometry_msgs::msg::Point> GetBody() { return body; } /** * Updates the snake by a single frame. Essentially, it determines when it * dies, how to move, and how to eat fruits. */ void Update(SnakeGrid& snakeGrid, FruitManager& fruitManager) { if(!dead) { geometry_msgs::msg::Point nextPoint; nextPoint = body.front(); switch(currentDirection) { case LEFT: nextPoint.x -= 1; break; case RIGHT: nextPoint.x += 1; break; case UP: nextPoint.y -= 1; break; case DOWN: nextPoint.y += 1; break; }; actualDirection = currentDirection; dead = WillDie(nextPoint.x, nextPoint.y, snakeGrid); if(!dead) { body.push_front(nextPoint); bool fruitEaten = fruitManager.Eat(nextPoint.x, nextPoint.y); if(!fruitEaten) { body.pop_back(); } else { fruitManager.RequestFruit(); } } } } void SetDirection(DIRECTION dir) { currentDirection = dir; } DIRECTION GetDirection() { return currentDirection; } DIRECTION GetActualDirection() { return actualDirection; } bool IsDead() { return dead; } /** * Checks whether or not the head is out of bounds our intersected its own * body to determine if it died. */ bool WillDie(int x, int y, SnakeGrid& snakeGrid) { if(!snakeGrid.InBounds(x, y)) return true; for(auto point : body) { if (point.x == x && point.y == y) { return true; } } return false; } /** * Respawn the snake at a specific point. */ void Respawn(int x, int y) { body.clear(); geometry_msgs::msg::Point p; p.x = x; p.y = y; body.push_front(p); dead = false; currentDirection = RIGHT; } private: // First element is head, final element is tail. std::list<geometry_msgs::msg::Point> body; bool dead; DIRECTION currentDirection; // User input and the game are asynchronous as run at different hertz, so // this gives the direction the snake is headed based on the last frame so // that the user doesn't circumnavigate the input-checking code to prevent // crashing directly backwards. DIRECTION actualDirection; }; /** * ROS Node that actually runs the game. Due to not being able to create a * standard game loop with a delay, this node runs the loop via wall timers and * asynchronously receives input from the terminal via ncurses. */ class GameNode : public rclcpp::Node { private: void OnGameFPSChange(const rclcpp::Parameter& p) { SetGameFPS(p.as_int()); } void OnInputFPSChange(const rclcpp::Parameter& p) { SetInputFPS(p.as_int()); } void SetGameFPS(int FPS) { int millisecondsToDelay = static_cast<int>(1000.0 / FPS); auto duration = std::chrono::duration<int, std::milli>(millisecondsToDelay); this->renderTimer = this->create_wall_timer(duration, std::bind(&GameNode::Loop, this)); } void SetInputFPS(int FPS) { int millisecondsToDelay = static_cast<int>(1000.0 / FPS); auto duration = std::chrono::duration<int, std::milli>(millisecondsToDelay); this->inputTimer = this->create_wall_timer(duration, std::bind(&GameNode::UserInput, this)); } public: GameNode(std::shared_ptr<MarkerPublisher> publisher) : Node("game_node"), snake(5,5), snakeGrid(15) { snake.SetDirection(Snake::RIGHT); this->declare_parameter("game_fps", 12); this->declare_parameter("input_fps", 100); this->declare_parameter("snake_color_r", 0); this->declare_parameter("snake_color_g", 255); this->declare_parameter("snake_color_b", 0); this->declare_parameter("fruit_color_r", 255); this->declare_parameter("fruit_color_g", 0); this->declare_parameter("fruit_color_b", 0); this->declare_parameter("grid_color_r", 255); this->declare_parameter("grid_color_g", 255); this->declare_parameter("grid_color_b", 255); this->SetGameFPS(get_parameter("game_fps").as_int()); this->SetInputFPS(get_parameter("input_fps").as_int()); // Handle parameter changes paramSubscriber = std::make_shared<rclcpp::ParameterEventHandler>(this); gameFPSHandle = paramSubscriber->add_parameter_callback("game_fps", std::bind(&GameNode::OnGameFPSChange, this, std::placeholders::_1)); inputFPSHandle = paramSubscriber->add_parameter_callback("input_fps", std::bind(&GameNode::OnInputFPSChange, this, std::placeholders::_1)); this->publisher = publisher; fruitManager.RequestFruit(); fruitManager.SpawnFruit(snakeGrid); } /** * Game loop. */ void Loop() { snake.Update(snakeGrid, fruitManager); for(auto body : snake.GetBody()) { snakeGrid.ReserveSnake(body.x, body.y); } fruitManager.SpawnFruit(snakeGrid); for(auto fruit : fruitManager.GetFruits()) { snakeGrid.ReserveFruit(fruit.p.x, fruit.p.y); } snakeGrid.Draw(publisher, GetColors()); snakeGrid.Clear(); } /** * Sole place for handling user input. */ void UserInput() { int c = getch(); auto currentDirection = snake.GetActualDirection(); if (c != -1) { if(c == 'w' && currentDirection != Snake::DOWN) snake.SetDirection(Snake::UP); if(c == 'a' && currentDirection != Snake::RIGHT) snake.SetDirection(Snake::LEFT); if(c == 's' && currentDirection != Snake::UP) snake.SetDirection(Snake::DOWN); if(c == 'd' && currentDirection != Snake::LEFT) snake.SetDirection(Snake::RIGHT); if(c == '\n') snake.Respawn(5,5); } } GamePieceColors GetColors() { GamePieceColors colors; colors.snakeColor.r = this->get_parameter("snake_color_r").as_int() / 255; colors.snakeColor.g = this->get_parameter("snake_color_g").as_int() / 255; colors.snakeColor.b = this->get_parameter("snake_color_b").as_int() / 255; colors.snakeColor.a = 1; colors.gridColor.r = this->get_parameter("grid_color_r").as_int() / 255; colors.gridColor.g = this->get_parameter("grid_color_g").as_int() / 255; colors.gridColor.b = this->get_parameter("grid_color_b").as_int() / 255; colors.gridColor.a = 1; colors.fruitColor.r = this->get_parameter("fruit_color_r").as_int() / 255; colors.fruitColor.g = this->get_parameter("fruit_color_g").as_int() / 255; colors.fruitColor.b = this->get_parameter("fruit_color_b").as_int() / 255; colors.fruitColor.a = 1; return colors; } private: Snake snake; SnakeGrid snakeGrid; std::shared_ptr<MarkerPublisher> publisher; FruitManager fruitManager; rclcpp::TimerBase::SharedPtr renderTimer, inputTimer; std::shared_ptr<rclcpp::ParameterEventHandler> paramSubscriber; std::shared_ptr<rclcpp::ParameterCallbackHandle> gameFPSHandle; std::shared_ptr<rclcpp::ParameterCallbackHandle> inputFPSHandle; }; #endif
24.993827
141
0.678439
[ "render", "vector", "3d" ]
539f0170728684714504b335b9523558d7144fff
13,547
hpp
C++
src/gc/identity.hpp
Gwenio/synafis
37176e965318ae555fdc542fc87ffb79866f770f
[ "ISC" ]
1
2019-01-27T14:44:50.000Z
2019-01-27T14:44:50.000Z
src/gc/identity.hpp
Gwenio/synafis
37176e965318ae555fdc542fc87ffb79866f770f
[ "ISC" ]
null
null
null
src/gc/identity.hpp
Gwenio/synafis
37176e965318ae555fdc542fc87ffb79866f770f
[ "ISC" ]
null
null
null
/* ISC License (ISC) Copyright 2018-2019 Adam Armstrong Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /** \file src/gc/identity.hpp * \brief Defines tools for identifying types to the garbage collector. * \ingroup gc_interface */ #include "../config/gc.hpp" #include "../unit_test.hpp" #include "callbacks.hpp" #include "traits.hpp" #ifndef SYNAFIS_GC_IDENTITY_HPP #define SYNAFIS_GC_IDENTITY_HPP #pragma once namespace gc { /** \class identity * \brief Contains callbacks used for the type the identity stands for. * \details Allows types to be interacted with by the collector in the * \details way it needs to without knowing their type. * \invariant acb != nullptr * \note This could be done with a base class with virtual methods, * \note but the collector has nothing to do with the class hierarchy. * \note * \note In particular, having all types used with the collector * \note inherit from a common base class means that if multiple * \note inheritance is used it may lead to messy diamond inheritance. * \note * \note Also, separating the identity from the class hierarchy means * \note a type can have additional identities for the presence of * \note const and/or volatile as qualifiers. * \ingroup gc_interface */ class identity { //! \cond friends friend unit_test::tester<identity>; //! \endcond public: /** \class access * \brief Type to access restricted parts of the identity class. * \note Should be defined where only the garbage collector has access * \note to the members of this class. * \ingroup gc_interface */ class access; //! \cond friends // So the garbage collector internals can get more access. friend access; //! \endcond /** \class iallocator * \brief Defines the interface for underlying allocators. */ class iallocator { /** \fn iallocator(iallocator const &) * \brief Deleted. */ iallocator(iallocator const &) = delete; /** \fn iallocator(iallocator &&) * \brief Deleted. */ iallocator(iallocator &&) = delete; protected: /** \fn iallocator() noexcept * \brief Default. */ constexpr iallocator() noexcept = default; public: /** \fn ~iallocator() * \brief Default. */ virtual ~iallocator() noexcept = default; /** \fn allocate() * \brief Allocates memory for an object. * \returns Returns a pointer to the allocated memory. * \throws std::bad_alloc if memory could not be allocated. */ virtual void *allocate() = 0; /** \fn allocate(std::nothrow_t) noexcept * \brief Allocates memory for an object. * \returns Returns a pointer to the allocated memory or nullptr on failure. */ virtual void *allocate(std::nothrow_t) noexcept = 0; /** \fn discarded(void *addr) noexcept * \brief Informs the allocator that an allocated object was not initialized. * \param addr The address of the previously allocated memory. */ virtual void discarded(void *addr) noexcept = 0; }; private: /** \var alloc * \brief The allocator for the identified type. * \invariant alloc != nullptr after the constructor successfully completes. * \see select_alloc */ iallocator *alloc; /** \var fcb * \brief The callback used to clean up an object. */ finalize_cb fcb; /** \var tcb * \brief The callback used to enumerate pointers reachable from an object. */ traverse_cb tcb; /** \var rcb * \brief The callback used to relocate objects and remap their pointers. */ relocate_cb rcb; /** \var ecb * \brief The callback used check if two objects will always be equal. */ equality_cb ecb; /** \fn unit_size() noexcept * \brief Gets the amount of memory to allocate to objects of a type. * \tparam T The type to get the allocation unit for. * \returns Returns the size of the allocation unit for objects of type T. * \details The return value is to be at least sizeof(T) and a multiple of alignof(T). */ template<typename T> static constexpr std::size_t unit_size() noexcept { return (sizeof(T) % alignof(T) == 0) ? sizeof(T) : ((sizeof(T) / alignof(T)) + 1) * alignof(T); } /** \fn select_alloc(identity const &id, std::size_t unit, traits::flag_type flags) * \brief Gets the allocator for the identified type. * \param id The identity of the type to get an allocator for. * \param unit The return value of unit_size for the type to select an allocator for. * \param flags The flags from traits::get_flags(). * \returns Returns non-null pointer to the allocator. * \pre Is to only be called once per identity object. * \see traits::get_flags() */ iallocator *select_alloc(identity const &id, std::size_t unit, traits::flag_type flags); /** \fn fetch_impl(void *obj) noexcept * \brief Gets the identity of an object. * \param obj The object to get the identity for. * \returns Returns a pointer to the identity of the object or nullptr if * \returns the object was not allocated by the collector. * \pre obj != nullptr */ static identity const *fetch_impl(void *obj) noexcept; /** \fn identity(finalize_cb f, traverse_cb t, relocate_cb r, equality_cb e) noexcept * \brief Sets up the parts that can be done as a constexpr. * \param f The finalizer callback. * \param t The traversal callback. * \param r The relocation and remapping callback. * \param e The equality check callback. */ constexpr identity(finalize_cb f, traverse_cb t, relocate_cb r, equality_cb e) noexcept : alloc(nullptr), fcb(f), tcb(t), rcb(r), ecb(e) {} /** \fn finalize(void *obj) const noexcept * \brief Calls the finalizer callback if it is present. * \param obj The address of the object to clean up. * \pre The object is unreachable outside the collector. * \pre obj != nullptr * \details Private so it is not accessible to the program. * \details The collector should access this function via detail::idaccess. */ void finalize(void *obj) const noexcept { if (fcb) { SYNAFIS_ASSERT(obj != nullptr); (*fcb)(obj); } } /** \fn traverse(void const *obj, void *data, enumerate_cb cb) const noexcept * \brief Calls the traversal callback if it is present. * \param obj The address of the object to traverse. * \param data Optional data for the callback, may be nullptr. * \param cb The callback for passing pointers in obj to. * \pre obj != nullptr && cb != nullptr * \details The callback 'cb' expects data as the first parameter and the pointer second. * \details * \details Private so it is not accessible to the program. * \details The collector should access this function via detail::idaccess. */ void traverse(void const *obj, void *data, enumerate_cb cb) const noexcept { if (tcb) { SYNAFIS_ASSERT(obj != nullptr); SYNAFIS_ASSERT(cb != nullptr); (*tcb)(obj, data, cb); } } /** \fn relocate(void *orig, void *dest, void *data, remap_cb cb) const noexcept * \brief Moves an object and remaps its pointers. * \param orig The address to move the object from. * \param dest The address to move the object to. * \param data Optional data for the callback, may be nullptr. * \param cb The callback for passing pointers in obj to which then provides the new address for. * \pre dest != nullptr && cb != nullptr * \details The parameters 'orig' and 'dest' will be equal if the object does not move. * \details * \details The callback 'cb' expects data as the first parameter and the pointer second. * \details * \details Private so it is not accessible to the program. * \details The collector should access this function via detail::idaccess. */ void relocate(void *orig, void *dest, void *data, remap_cb cb) const noexcept { if (rcb) { SYNAFIS_ASSERT(dest != nullptr); SYNAFIS_ASSERT(cb != nullptr); (*rcb)(orig, dest, data, cb); } } public: /** \fn identity(T *) * \brief Constructs the identity for a type. * \tparam T The type to construct an identity for. * \post acb != nullptr * \post !traits::%pointers\<T\> || (tcb && rcb) * \post std::is_trivially_destructible_v\<T\> || fcb != nullptr * \post !traits::%movable\<T\> || std::is_trivially_copyable_v\<T\> || rcb != nullptr * \details Sets the allocator and preforms sanity checks if * \details assertion are enabled. */ template<typename T> identity(T *) : identity( traits::finalizer<T>, traits::traverser<T>, traits::relocator<T>, traits::equalizer<T>) { alloc = select_alloc(*this, unit_size<T>(), traits::get_flags<T>()); SYNAFIS_ASSERT(alloc != nullptr); SYNAFIS_ASSERT(!traits::pointers<T> || (tcb && rcb)); SYNAFIS_ASSERT(std::is_trivially_destructible_v<T> || fcb != nullptr); SYNAFIS_ASSERT(!traits::movable<T> || std::is_trivially_copyable_v<T> || rcb != nullptr); } /** \fn ~identity() * \brief Cleans up the allocator if needed. * \note This is to be implemented in the garbage collector implementation. */ ~identity(); /** \fn allocate() const * \brief Allocates an object of the type the identity represents. * \returns Returns a pointer to the allocated object. * \pre The collector lock must be held by the calling thread. * \throws std::bad_alloc if memory could not be allocated. */ void *allocate() const { return alloc->allocate(); } /** \fn allocate(std::nothrow_t) const noexcept * \brief Allocates an object of the type the identity represents. * \returns Returns a pointer to the allocated object or nullptr. * \returns If nullptr is returned, then it means allocation failed and * \returns the collector could not free enough memory at this time. * \pre The collector lock must be held by the calling thread. */ void *allocate(std::nothrow_t) const noexcept { return alloc->allocate(std::nothrow); } /** \fn discarded(void *addr) noexcept * \brief Informs the allocator if an allocated object uninitialized. * \param addr The address of the previously allocated memory. * \details Prevents the finalizer from being run on uninitialized objects. * \details The memory may be reclaimed immediately. * \warning The collector must be locked from before allocate() is called until after * \warning discarded() returns. * \note The allocator is only informed if there is a finalizer. * \note Otherwise the object can wait for a normal collection cycle. */ void discarded(void *addr) noexcept { if (fcb) { alloc->discarded(addr); } } /** \fn equal(void const *lhs, void const *rhs) const noexcept * \brief Checks that two objects will always be equal. * \param lhs The first object. * \param rhs The second object. * \pre lhs != rhs && lhs != nullptr && rhs != nullptr * \returns Returns true if the objects will never not be equal. * \details Public so that the program can use it to make sure objects * \details that should be considered as the same object will be treated as such. */ bool equal(void const *lhs, void const *rhs) const noexcept { SYNAFIS_ASSERT(lhs != rhs); if (ecb) { SYNAFIS_ASSERT(lhs != nullptr); SYNAFIS_ASSERT(rhs != nullptr); return (*ecb)(lhs, rhs); } else { // Objects are not equal if their equality cannot be checked. return false; } } /** \fn fetch(T *obj) * \brief Gets the identity of an object. * \tparam T The apperent type of obj. * \param obj The object to get the identity for. * \returns Returns a reference to the identity of the object. * \throws Throws std::runtime_error if the object was not allocated by the collector. * \pre obj != nullptr * \pre obj points to an area of memory allocated the the collector. */ template<typename T> static identity const &fetch(T *obj) { SYNAFIS_ASSERT(obj != nullptr); identity const *temp{ fetch_impl(static_cast<void *>(const_cast<std::remove_cv_t<T> *>(obj)))}; if (temp) { return *temp; } else { throw std::runtime_error("Object was not allocated by the garbage collector."); } } /** \fn fetch(T *obj, std::nothrow_t) noexcept * \brief Gets the identity of an object. * \tparam T The apperent type of obj. * \param obj The object to get the identity for. * \returns Returns a pointer to the identity of the object or nullptr if * \returns the object was not allocated by the collector. * \pre obj != nullptr */ template<typename T> static identity const *fetch(T *obj, std::nothrow_t) noexcept { SYNAFIS_ASSERT(obj != nullptr); return fetch_impl(static_cast<void *>(const_cast<std::remove_cv_t<T> *>(obj))); } }; /** \fn get_id() noexcept * \brief Function to the identity for a type T. * \tparam The type to get the identity for. * \returns Returns a reference to the identity for the type. * \note A type may have separate identities for the presence of const or volatile * \note as qualifies. * \todo Work out the best way for providing the identities for types. * \ingroup gc_interface */ template<typename T> identity const &get_id() noexcept; } #endif
35.095855
98
0.704879
[ "object" ]
53a8887b846b431b982f1314a50d3c265c82cda1
4,747
cpp
C++
ICPC/Repechaje2021/c.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
ICPC/Repechaje2021/c.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
ICPC/Repechaje2021/c.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <stdio.h> #include <string> #include <vector> #include <map> #include <math.h> #include <numeric> #include <queue> #include <stack> #include <utility> #include <queue> #include <set> #include <iomanip> using namespace std; typedef int64_t ll; typedef pair<int,ll> pill; typedef pair<int,int> pii; #define INF 1000000000000 #define MOD 1000000007 #define loop(i,a,b) for(int i = a; i < b; ++i) const int maxW = 8; int w,h,t; int porArreglar; char matriz[maxW][maxW]; int bucket[27]; map<char, map<int, int> >activosFilas, activosColumnas; map<char, map<int, bool> > fijoFila, fijoColumna; bool borrados[maxW][maxW]; int borradosCaso, limiteBorra; pii dir [4] = {pii(0, 1), pii(1, 0), pii(-1, 0), pii(0, -1)}; bool noPuedoBorrarme(int f, int c){ int x, y; loop(i, 0, 4){ x = f + dir[i].first; y = c + dir[i].second; if(x >= 0 && x< w && y>=0 && y < h && borrados[x][y]) return true; } return false; } // letra, fila, columna bool backTrack(char x, int f, int c){ //cout<<x<<" "<<f<<" "<<c<<endl; if(f == w){ if(x < 'Z') return backTrack(x+1, 0, 0); else return porArreglar > 0; } if(borradosCaso == limiteBorra && porArreglar>0) return false; //si esta celda no es de esta letra me voy a la siguiente if(matriz[f][c] != x){ if(c < h-1) return backTrack(x, f, c+1); else return backTrack(x, f+1, 0); } //sí hay letras activas en esta fila //borro o no borro //borro if(!noPuedoBorrarme(f, c)){ ++borradosCaso; borrados[f][c] = true; --activosColumnas[x][c]; --activosFilas[x][f]; if(activosColumnas[x][c] == 1) --porArreglar; if(activosFilas[x][f] == 1) --porArreglar; if(porArreglar == 0) return true; //procedo al back track //si funciona, return true if(c < h-1){ if(backTrack(x, f, c+1)) return true; } else{ if(backTrack(x, f+1, 0)) return true; } //deshago los cambios if(activosColumnas[x][c] == 1) ++porArreglar; if(activosFilas[x][f] == 1) ++porArreglar; ++activosColumnas[x][c]; ++activosFilas[x][f]; borrados[f][c] = false; --borradosCaso; } //si ya hay otro en fila o col que no borre2 y no puedo borrarme else if(fijoFila[x][f] || fijoColumna[x][c]) return false; //no la borro if(fijoFila[x][f]== false && fijoColumna[x][c] == false){ fijoColumna[x][c] = true; fijoFila[x][f] = true; if(c < h-1){ if(backTrack(x, f, c+1)) return true; } else{ if(backTrack(x, f+1, 0)) return true; } //deshago los cambios fijoColumna[x][c] = false; fijoFila[x][f] = false; } //si no se pudo en ningun caso return false; } bool sePuede(){ char x; loop(i, 0, w) fill(borrados[i], borrados[i] + h, 0); activosColumnas.clear(); activosFilas.clear(); loop(i, 0, w){ loop(j, 0, h){ x = matriz[i][j]; ++activosColumnas[x][j]; ++activosFilas[x][i]; } } porArreglar = 0; for(x = 'A'; x <= 'Z'; ++x){ loop(i, 0, w){ fijoFila[x][i] = 0; if(activosFilas[x][i] > 1) ++porArreglar; } loop(i, 0, h){ fijoColumna[x][i] = 0; if(activosColumnas[x][i] > 1) ++porArreglar; } } if(porArreglar == 0) return true; borradosCaso = 0; return backTrack('A', 0, 0); } void lee(){ char x; cin>>h>>w>>t; loop(i, 0, w){ loop(j, 0, h){ cin>>x; matriz[i][j] = x; ++activosColumnas[x][j]; ++activosFilas[x][i]; ++bucket[x-'A']; } } } void solve(){ lee(); //cota inferior int borroCols, borroFilas; char x; int ini = 0, mitad, fin = (w*h+1)/2; while(ini != fin){ mitad = (ini+fin)/2; limiteBorra = mitad; //cout<<"entro con "<<mitad<<endl; if(sePuede()){ //cout<<"se puede con "<<mitad<<"\n"; fin = mitad; } else{ //cout<<"no se puede con "<<mitad<<"\n"; ini = mitad + 1; } } cout<<ini<<endl; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); if(fopen("case.txt", "r")) freopen("case.txt", "r", stdin); int t = 1; //int t; cin>>t; loop(i, 0, t){ solve(); } return 0; }
22.49763
69
0.492943
[ "vector" ]
53c220ec9333c111cc94a0be7fb4b9a2dec62617
8,481
cpp
C++
src/qt/qtwebkit/Source/WebKit2/UIProcess/efl/TextCheckerClientEfl.cpp
viewdy/phantomjs
eddb0db1d253fd0c546060a4555554c8ee08c13c
[ "BSD-3-Clause" ]
1
2015-05-27T13:52:20.000Z
2015-05-27T13:52:20.000Z
src/qt/qtwebkit/Source/WebKit2/UIProcess/efl/TextCheckerClientEfl.cpp
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtwebkit/Source/WebKit2/UIProcess/efl/TextCheckerClientEfl.cpp
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
1
2017-03-19T13:03:23.000Z
2017-03-19T13:03:23.000Z
/* * Copyright (C) 2013 Samsung Electronics * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "TextCheckerClientEfl.h" #if ENABLE(SPELLCHECK) #include "EwkView.h" #include "TextChecker.h" #include "TextCheckerState.h" #include "WKAPICast.h" #include "WKEinaSharedString.h" #include "WKMutableArray.h" #include "WKRetainPtr.h" #include "WKString.h" #include "WebPageProxy.h" #include "ewk_text_checker_private.h" #include <Eina.h> using namespace WebCore; using namespace WebKit; static inline TextCheckerClientEfl* toTextCheckerClientEfl(const void* clientInfo) { return static_cast<TextCheckerClientEfl*>(const_cast<void*>(clientInfo)); } TextCheckerClientEfl::TextCheckerClientEfl() : m_languagesUpdateTimer(this, &TextCheckerClientEfl::languagesUpdateTimerFired) , m_spellCheckingSettingChangeTimer(this, &TextCheckerClientEfl::spellCheckingSettingChangeTimerFired) , m_textCheckerEnchant(TextCheckerEnchant::create()) { memset(&m_clientCallbacks, 0, sizeof(ClientCallbacks)); WKTextCheckerClient wkTextCheckerClient = { kWKTextCheckerClientCurrentVersion, this, 0, // continuousSpellCheckingAllowed isContinuousSpellCheckingEnabledCallback, setContinuousSpellCheckingEnabledCallback, 0, // grammarCheckingEnabled 0, // setGrammarCheckingEnabled uniqueSpellDocumentTagCallback, closeSpellDocumentWithTagCallback, checkSpellingOfStringCallback, 0, // checkGrammarOfString, 0, // spellingUIIsShowing 0, // toggleSpellingUIIsShowing 0, // updateSpellingUIWithMisspelledWord 0, // updateSpellingUIWithGrammarString guessesForWordCallback, learnWordCallback, ignoreWordCallback }; WKTextCheckerSetClient(&wkTextCheckerClient); } TextCheckerClientEfl& TextCheckerClientEfl::instance() { DEFINE_STATIC_LOCAL(TextCheckerClientEfl, textCheckerClient, ()); return textCheckerClient; } bool TextCheckerClientEfl::isContinuousSpellCheckingEnabled() const { return isContinuousSpellCheckingEnabledCallback(0 /* clientInfo */); } void TextCheckerClientEfl::ensureSpellCheckingLanguage() { if (!m_textCheckerEnchant->hasDictionary()) updateSpellCheckingLanguages(); } void TextCheckerClientEfl::updateSpellCheckingLanguages(const Vector<String>& defaultLanguages) { m_spellCheckingLanguages = defaultLanguages; m_languagesUpdateTimer.startOneShot(0); } void TextCheckerClientEfl::languagesUpdateTimerFired(Timer<TextCheckerClientEfl>*) { m_textCheckerEnchant->updateSpellCheckingLanguages(m_spellCheckingLanguages); } void TextCheckerClientEfl::spellCheckingSettingChangeTimerFired(Timer<TextCheckerClientEfl>*) { m_clientCallbacks.continuous_spell_checking_change( isContinuousSpellCheckingEnabledCallback(0 /* clientInfo */) ); } Vector<String> TextCheckerClientEfl::availableSpellCheckingLanguages() const { return m_textCheckerEnchant->availableSpellCheckingLanguages(); } Vector<String> TextCheckerClientEfl::loadedSpellCheckingLanguages() const { return m_textCheckerEnchant->loadedSpellCheckingLanguages(); } void TextCheckerClientEfl::callContinuousSpellCheckingChangeCallbackAsync() { m_spellCheckingSettingChangeTimer.startOneShot(0); } bool TextCheckerClientEfl::isContinuousSpellCheckingEnabledCallback(const void*) { return TextChecker::state().isContinuousSpellCheckingEnabled; } void TextCheckerClientEfl::setContinuousSpellCheckingEnabledCallback(bool, const void* clientInfo) { TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); if (textCheckerClient->clientCallbacks().continuous_spell_checking_change) textCheckerClient->callContinuousSpellCheckingChangeCallbackAsync(); } uint64_t TextCheckerClientEfl::uniqueSpellDocumentTagCallback(WKPageRef page, const void* clientInfo) { TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); if (textCheckerClient->clientCallbacks().unique_spell_document_tag_get) return textCheckerClient->clientCallbacks().unique_spell_document_tag_get(EwkView::toEvasObject(page)); return 0; } void TextCheckerClientEfl::closeSpellDocumentWithTagCallback(uint64_t tag, const void* clientInfo) { TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); if (textCheckerClient->clientCallbacks().unique_spell_document_tag_close) textCheckerClient->clientCallbacks().unique_spell_document_tag_close(tag); } void TextCheckerClientEfl::checkSpellingOfStringCallback(uint64_t tag, WKStringRef text, int32_t* misspellingLocation, int32_t* misspellingLength, const void* clientInfo) { TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); if (textCheckerClient->clientCallbacks().string_spelling_check) textCheckerClient->clientCallbacks().string_spelling_check(tag, WKEinaSharedString(text), misspellingLocation, misspellingLength); else textCheckerClient->m_textCheckerEnchant->checkSpellingOfString(toWTFString(text), *misspellingLocation, *misspellingLength); } WKArrayRef TextCheckerClientEfl::guessesForWordCallback(uint64_t tag, WKStringRef word, const void* clientInfo) { WKMutableArrayRef suggestionsForWord = WKMutableArrayCreate(); TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); if (textCheckerClient->clientCallbacks().word_guesses_get) { Eina_List* list = textCheckerClient->clientCallbacks().word_guesses_get(tag, WKEinaSharedString(word)); void* item; EINA_LIST_FREE(list, item) { WKRetainPtr<WKStringRef> suggestion(AdoptWK, WKStringCreateWithUTF8CString(static_cast<const char*>(item))); WKArrayAppendItem(suggestionsForWord, suggestion.get()); free(item); } } else { const Vector<String>& guesses = textCheckerClient->m_textCheckerEnchant->getGuessesForWord(toWTFString(word)); size_t numberOfGuesses = guesses.size(); for (size_t i = 0; i < numberOfGuesses; ++i) { WKRetainPtr<WKStringRef> suggestion(AdoptWK, WKStringCreateWithUTF8CString(guesses[i].utf8().data())); WKArrayAppendItem(suggestionsForWord, suggestion.get()); } } return suggestionsForWord; } void TextCheckerClientEfl::learnWordCallback(uint64_t tag, WKStringRef word, const void* clientInfo) { TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); if (textCheckerClient->clientCallbacks().word_learn) textCheckerClient->clientCallbacks().word_learn(tag, WKEinaSharedString(word)); else textCheckerClient->m_textCheckerEnchant->learnWord(toWTFString(word)); } void TextCheckerClientEfl::ignoreWordCallback(uint64_t tag, WKStringRef word, const void* clientInfo) { TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); if (textCheckerClient->clientCallbacks().word_ignore) textCheckerClient->clientCallbacks().word_ignore(tag, WKEinaSharedString(word)); else textCheckerClient->m_textCheckerEnchant->ignoreWord(toWTFString(word)); } #endif // ENABLE(SPELLCHECK)
39.816901
170
0.780568
[ "vector" ]
53cb4bf6b2ad93fe904c281871fcedfc09a794df
1,380
cpp
C++
essential/udacity-cpp-nano/Chapters/3_Object_Oriented_Programming/2_14_Encapsulation/main.cpp
disono/cp-cheat-sheet
02edee3d822f56770e1a1a3cc4db6be3691a7a38
[ "MIT" ]
null
null
null
essential/udacity-cpp-nano/Chapters/3_Object_Oriented_Programming/2_14_Encapsulation/main.cpp
disono/cp-cheat-sheet
02edee3d822f56770e1a1a3cc4db6be3691a7a38
[ "MIT" ]
null
null
null
essential/udacity-cpp-nano/Chapters/3_Object_Oriented_Programming/2_14_Encapsulation/main.cpp
disono/cp-cheat-sheet
02edee3d822f56770e1a1a3cc4db6be3691a7a38
[ "MIT" ]
null
null
null
#include <cassert> class Date { public: Date(int day, int month, int year); int Day() const { return day_; } void Day(int day); int Month() const { return month_; } void Month(int month); int Year() const { return year_; } void Year(int year); private: int day_{1}; int month_{1}; int year_{0}; int DaysInMonth(int m, int y) const; // const means it is not going to change the state of the object of the class bool LeapYear(int y) const; }; bool Date::LeapYear(int y) const { if (y % 4 != 0) return false; else if (y % 100 != 0) return true; else if (y % 400 != 0) return false; else return true; } int Date::DaysInMonth(int m, int y) const { if (m == 2) return LeapYear(y) ? 29 : 28; else if (m == 4 || m == 6 || m == 9 || m == 11) return 30; else return 31; } Date::Date(int day, int month, int year) { Year(year); Month(month); Day(day); } void Date::Day(int day) { if (day >= 1 && day <= DaysInMonth(Month(), Year())) day_ = day; } void Date::Month(int month) { if (month >= 1 && month <= 12) month_ = month; } void Date::Year(int year) { year_ = year; } // Test int main() { Date date(29, 8, 1981); assert(date.Day() == 29); assert(date.Month() == 8); assert(date.Year() == 1981); }
19.166667
118
0.544928
[ "object" ]
53d37651d29f7e8bdde070f97ba94a527e10bcae
8,725
cpp
C++
src/qt/pivx/moc_coldstakingwidget.cpp
PlutusCapital/core
9a02ab820245afdb2b3ab4bea621a78bfef37590
[ "MIT" ]
null
null
null
src/qt/pivx/moc_coldstakingwidget.cpp
PlutusCapital/core
9a02ab820245afdb2b3ab4bea621a78bfef37590
[ "MIT" ]
null
null
null
src/qt/pivx/moc_coldstakingwidget.cpp
PlutusCapital/core
9a02ab820245afdb2b3ab4bea621a78bfef37590
[ "MIT" ]
null
null
null
/**************************************************************************** ** Meta object code from reading C++ file 'coldstakingwidget.h' ** ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "qt/pivx/coldstakingwidget.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'coldstakingwidget.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.5.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_ColdStakingWidget_t { QByteArrayData data[36]; char stringdata0[500]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_ColdStakingWidget_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_ColdStakingWidget_t qt_meta_stringdata_ColdStakingWidget = { { QT_MOC_LITERAL(0, 0, 17), // "ColdStakingWidget" QT_MOC_LITERAL(1, 18, 12), // "walletSynced" QT_MOC_LITERAL(2, 31, 0), // "" QT_MOC_LITERAL(3, 32, 4), // "sync" QT_MOC_LITERAL(4, 37, 11), // "changeTheme" QT_MOC_LITERAL(5, 49, 12), // "isLightTheme" QT_MOC_LITERAL(6, 62, 8), // "QString&" QT_MOC_LITERAL(7, 71, 5), // "theme" QT_MOC_LITERAL(8, 77, 20), // "handleAddressClicked" QT_MOC_LITERAL(9, 98, 5), // "index" QT_MOC_LITERAL(10, 104, 26), // "handleMyColdAddressClicked" QT_MOC_LITERAL(11, 131, 6), // "rIndex" QT_MOC_LITERAL(12, 138, 20), // "onCoinControlClicked" QT_MOC_LITERAL(13, 159, 18), // "onColdStakeClicked" QT_MOC_LITERAL(14, 178, 17), // "updateDisplayUnit" QT_MOC_LITERAL(15, 196, 8), // "showList" QT_MOC_LITERAL(16, 205, 4), // "show" QT_MOC_LITERAL(17, 210, 13), // "onSendClicked" QT_MOC_LITERAL(18, 224, 18), // "onDelegateSelected" QT_MOC_LITERAL(19, 243, 8), // "delegate" QT_MOC_LITERAL(20, 252, 13), // "onEditClicked" QT_MOC_LITERAL(21, 266, 15), // "onDeleteClicked" QT_MOC_LITERAL(22, 282, 13), // "onCopyClicked" QT_MOC_LITERAL(23, 296, 18), // "onCopyOwnerClicked" QT_MOC_LITERAL(24, 315, 20), // "onAddressCopyClicked" QT_MOC_LITERAL(25, 336, 20), // "onAddressEditClicked" QT_MOC_LITERAL(26, 357, 11), // "onTxArrived" QT_MOC_LITERAL(27, 369, 4), // "hash" QT_MOC_LITERAL(28, 374, 11), // "isCoinStake" QT_MOC_LITERAL(29, 386, 11), // "isCSAnyType" QT_MOC_LITERAL(30, 398, 17), // "onContactsClicked" QT_MOC_LITERAL(31, 416, 8), // "ownerAdd" QT_MOC_LITERAL(32, 425, 8), // "clearAll" QT_MOC_LITERAL(33, 434, 14), // "onLabelClicked" QT_MOC_LITERAL(34, 449, 27), // "onMyStakingAddressesClicked" QT_MOC_LITERAL(35, 477, 22) // "onDelegationsRefreshed" }, "ColdStakingWidget\0walletSynced\0\0sync\0" "changeTheme\0isLightTheme\0QString&\0" "theme\0handleAddressClicked\0index\0" "handleMyColdAddressClicked\0rIndex\0" "onCoinControlClicked\0onColdStakeClicked\0" "updateDisplayUnit\0showList\0show\0" "onSendClicked\0onDelegateSelected\0" "delegate\0onEditClicked\0onDeleteClicked\0" "onCopyClicked\0onCopyOwnerClicked\0" "onAddressCopyClicked\0onAddressEditClicked\0" "onTxArrived\0hash\0isCoinStake\0isCSAnyType\0" "onContactsClicked\0ownerAdd\0clearAll\0" "onLabelClicked\0onMyStakingAddressesClicked\0" "onDelegationsRefreshed" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_ColdStakingWidget[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 22, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 1, 124, 2, 0x0a /* Public */, 4, 2, 127, 2, 0x08 /* Private */, 8, 1, 132, 2, 0x08 /* Private */, 10, 1, 135, 2, 0x08 /* Private */, 12, 0, 138, 2, 0x08 /* Private */, 13, 0, 139, 2, 0x08 /* Private */, 14, 0, 140, 2, 0x08 /* Private */, 15, 1, 141, 2, 0x08 /* Private */, 17, 0, 144, 2, 0x08 /* Private */, 18, 1, 145, 2, 0x08 /* Private */, 20, 0, 148, 2, 0x08 /* Private */, 21, 0, 149, 2, 0x08 /* Private */, 22, 0, 150, 2, 0x08 /* Private */, 23, 0, 151, 2, 0x08 /* Private */, 24, 0, 152, 2, 0x08 /* Private */, 25, 0, 153, 2, 0x08 /* Private */, 26, 3, 154, 2, 0x08 /* Private */, 30, 1, 161, 2, 0x08 /* Private */, 32, 0, 164, 2, 0x08 /* Private */, 33, 0, 165, 2, 0x08 /* Private */, 34, 0, 166, 2, 0x08 /* Private */, 35, 0, 167, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Bool, 3, QMetaType::Void, QMetaType::Bool, 0x80000000 | 6, 5, 7, QMetaType::Void, QMetaType::QModelIndex, 9, QMetaType::Void, QMetaType::QModelIndex, 11, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Bool, 16, QMetaType::Void, QMetaType::Void, QMetaType::Bool, 19, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::QString, QMetaType::Bool, QMetaType::Bool, 27, 28, 29, QMetaType::Void, QMetaType::Bool, 31, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void ColdStakingWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { ColdStakingWidget *_t = static_cast<ColdStakingWidget *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->walletSynced((*reinterpret_cast< bool(*)>(_a[1]))); break; case 1: _t->changeTheme((*reinterpret_cast< bool(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break; case 2: _t->handleAddressClicked((*reinterpret_cast< const QModelIndex(*)>(_a[1]))); break; case 3: _t->handleMyColdAddressClicked((*reinterpret_cast< const QModelIndex(*)>(_a[1]))); break; case 4: _t->onCoinControlClicked(); break; case 5: _t->onColdStakeClicked(); break; case 6: _t->updateDisplayUnit(); break; case 7: _t->showList((*reinterpret_cast< bool(*)>(_a[1]))); break; case 8: _t->onSendClicked(); break; case 9: _t->onDelegateSelected((*reinterpret_cast< bool(*)>(_a[1]))); break; case 10: _t->onEditClicked(); break; case 11: _t->onDeleteClicked(); break; case 12: _t->onCopyClicked(); break; case 13: _t->onCopyOwnerClicked(); break; case 14: _t->onAddressCopyClicked(); break; case 15: _t->onAddressEditClicked(); break; case 16: _t->onTxArrived((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const bool(*)>(_a[2])),(*reinterpret_cast< const bool(*)>(_a[3]))); break; case 17: _t->onContactsClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 18: _t->clearAll(); break; case 19: _t->onLabelClicked(); break; case 20: _t->onMyStakingAddressesClicked(); break; case 21: _t->onDelegationsRefreshed(); break; default: ; } } } const QMetaObject ColdStakingWidget::staticMetaObject = { { &PWidget::staticMetaObject, qt_meta_stringdata_ColdStakingWidget.data, qt_meta_data_ColdStakingWidget, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *ColdStakingWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *ColdStakingWidget::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_ColdStakingWidget.stringdata0)) return static_cast<void*>(const_cast< ColdStakingWidget*>(this)); return PWidget::qt_metacast(_clname); } int ColdStakingWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = PWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 22) qt_static_metacall(this, _c, _id, _a); _id -= 22; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 22) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 22; } return _id; } QT_END_MOC_NAMESPACE
39.840183
173
0.625444
[ "object" ]
53d69d1a00eba88b532d8b9109df7e437e61d8cf
1,057
cpp
C++
tests/answer_bonus_2_b_smorse_main.cpp
ThomasPDye/smorse
9714539a1606974af0870e7cf03b98385ba14106
[ "MIT" ]
null
null
null
tests/answer_bonus_2_b_smorse_main.cpp
ThomasPDye/smorse
9714539a1606974af0870e7cf03b98385ba14106
[ "MIT" ]
null
null
null
tests/answer_bonus_2_b_smorse_main.cpp
ThomasPDye/smorse
9714539a1606974af0870e7cf03b98385ba14106
[ "MIT" ]
null
null
null
#include "answer_bonus_2_b_smorse.hpp" #include <iostream> int main(int argc, char **argv) { int result = -1; if (argc == 4) { std::string ifname(argv[1]); std::string charstr(argv[2]); std::string countstr(argv[3]); if (charstr.size() == 1ul) { char c = charstr[0]; unsigned int count = (unsigned int)std::stoi(countstr); std::map<std::string, std::vector<std::string>> answer_map = answer_smorse::answer_bonus_2_b(ifname, c, count); for (std::map<std::string, std::vector<std::string>>::iterator ai = answer_map.begin(); ai != answer_map.end(); ai++) { std::cout << ai->first << " " << ai->second.size() << " "; for (std::vector<std::string>::iterator wi = ai->second.begin(); wi != ai->second.end(); wi++) { std::cout << " " << *wi.base(); } std::cout << std::endl; } result = 0; } } return result; }
34.096774
129
0.486282
[ "vector" ]
53dd3d3142427b33e3cc8e7db2f22e11de9554af
6,049
hpp
C++
include/wui/control/list.hpp
ud84/wui
354260df9882c3e582c2a337a4bbb8be6e030e13
[ "BSL-1.0" ]
1
2021-12-18T16:38:30.000Z
2021-12-18T16:38:30.000Z
include/wui/control/list.hpp
ud84/wui
354260df9882c3e582c2a337a4bbb8be6e030e13
[ "BSL-1.0" ]
null
null
null
include/wui/control/list.hpp
ud84/wui
354260df9882c3e582c2a337a4bbb8be6e030e13
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2021-2022 Anton Golovkov (udattsk at gmail dot com) // // 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) // // Official repository: https://github.com/ud84/wui // #pragma once #include <wui/control/i_control.hpp> #include <wui/graphic/graphic.hpp> #include <wui/event/event.hpp> #include <wui/common/rect.hpp> #include <wui/common/color.hpp> #include <string> #include <vector> #include <functional> #include <memory> #include <atomic> #include <thread> namespace wui { class list : public i_control, public std::enable_shared_from_this<list> { public: list(const std::string &theme_control_name = tc, std::shared_ptr<i_theme> theme_ = nullptr); ~list(); virtual void draw(graphic &gr, const rect &); virtual void set_position(const rect &position, bool redraw = true); virtual rect position() const; virtual void set_parent(std::shared_ptr<window> window_); virtual std::weak_ptr<window> parent() const; virtual void clear_parent(); virtual void set_topmost(bool yes); virtual bool topmost() const; virtual void update_theme(std::shared_ptr<i_theme> theme_ = nullptr); virtual void show(); virtual void hide(); virtual bool showed() const; virtual void enable(); virtual void disable(); virtual bool enabled() const; virtual bool focused() const; virtual bool focusing() const; public: /// List's interface struct column { int32_t width; std::string caption; }; void update_columns(const std::vector<column> &columns); enum class list_mode { simple, auto_select, simple_topmost }; void set_mode(list_mode mode); void select_item(int32_t n_item); int32_t selected_item() const; void set_column_width(int32_t n_item, int32_t width); void set_item_height(int32_t height); int32_t get_item_height() const; void set_item_count(int32_t count); enum class item_state { normal, active, selected }; void set_draw_callback(std::function<void(graphic&, int32_t, const rect&, item_state state, const std::vector<column> &columns)> draw_callback_); void set_item_click_callback(std::function<void(int32_t, int32_t)> item_click_callback_); void set_item_change_callback(std::function<void(int32_t)> item_change_callback_); void set_item_activate_callback(std::function<void(int32_t)> item_activate_callback_); void set_column_click_callback(std::function<void(int32_t)> column_click_callback_); void set_item_right_click_callback(std::function<void(int32_t, int32_t , int32_t)> item_right_click_callback_); public: /// Control name in theme static constexpr const char *tc = "list"; /// Used theme values static constexpr const char *tv_background = "background"; static constexpr const char *tv_border = "border"; static constexpr const char *tv_focused_border = "focused_border"; static constexpr const char *tv_border_width = "border_width"; static constexpr const char *tv_title = "title"; static constexpr const char *tv_title_text = "title_text"; static constexpr const char *tv_scrollbar = "scrollbar"; static constexpr const char *tv_scrollbar_slider = "scrollbar_slider"; static constexpr const char *tv_scrollbar_slider_acive = "scrollbar_slider_active"; static constexpr const char *tv_selected_item = "selected_item"; static constexpr const char *tv_active_item = "active_item"; static constexpr const char *tv_round = "round"; static constexpr const char *tv_font = "font"; private: std::string tcn; /// control name in theme std::shared_ptr<i_theme> theme_; rect position_; std::weak_ptr<window> parent_; std::string my_control_sid, my_plain_sid; bool showed_, enabled_, focused_, mouse_on_control; std::vector<column> columns; list_mode mode; std::atomic<int32_t> item_height, item_count, selected_item_, active_item_, start_item; enum class worker_action { undefined = 0, scroll_up, scroll_down, scrollbar_show }; worker_action worker_action_; std::thread worker; bool worker_runned; int32_t progress; enum class scrollbar_state { hide, tiny, full }; scrollbar_state scrollbar_state_; bool slider_scrolling; int32_t prev_scroll_pos; int32_t title_height; static const int32_t tiny_scrollbar_width = 3; static const int32_t full_scrollbar_width = 14; std::function<void(graphic&, int32_t, const rect&, item_state state, const std::vector<column> &columns)> draw_callback; std::function<void(int32_t, int32_t)> item_click_callback; std::function<void(int32_t)> item_change_callback; std::function<void(int32_t)> item_activate_callback; std::function<void(int32_t)> column_click_callback; std::function<void(int32_t, int32_t, int32_t)> item_right_click_callback; void receive_control_events(const event &ev); void receive_plain_events(const event &ev); void redraw(); void redraw_item(int32_t item); void draw_titles(graphic &gr_); void draw_items(graphic &gr_); bool has_scrollbar(); void draw_scrollbar(graphic &gr_); void draw_arrow_up(graphic &gr, rect button_pos); void draw_arrow_down(graphic &gr, rect button_pos); int32_t get_visible_item_count() const; void move_slider(int32_t y); void scroll_up(); void scroll_down(); void calc_scrollbar_params(bool drawing_coordinates, rect *bar_rect = nullptr, rect *top_button_rect = nullptr, rect *bottom_button_rect = nullptr, rect *slider_rect = nullptr); bool is_click_on_scrollbar(int32_t x); void update_selected_item(int32_t y); void update_active_item(int32_t y); void start_work(worker_action action); void work(); void end_work(); }; }
28.942584
181
0.709539
[ "vector" ]
53deede37665e539bbbadf47c8fbed17422c50c7
3,626
hpp
C++
Core/BufferMgr.hpp
Calvin-Ruiz/EntityCore
04361a2597c71078ac676067a71cfc1a005c2ff8
[ "MIT" ]
4
2021-12-20T16:33:40.000Z
2022-03-08T12:09:07.000Z
Core/BufferMgr.hpp
Calvin-Ruiz/EntityCore
04361a2597c71078ac676067a71cfc1a005c2ff8
[ "MIT" ]
null
null
null
Core/BufferMgr.hpp
Calvin-Ruiz/EntityCore
04361a2597c71078ac676067a71cfc1a005c2ff8
[ "MIT" ]
null
null
null
#ifndef BUFFER_MGR_HPP #define BUFFER_MGR_HPP #include <vulkan/vulkan.h> #include "EntityCore/SubMemory.hpp" #include "EntityCore/SubBuffer.hpp" #include <vector> #include <memory> #include <list> #include <thread> #include <mutex> class VulkanMgr; /** * \brief Manage SubBuffer allocation like MemoryManager * There must never been concurrent access to SubBuffer memory acquired from the same BufferMgr */ class BufferMgr { public: BufferMgr(VulkanMgr &master, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkMemoryPropertyFlags preferedProperties, uint32_t bufferBlocSize = 512*1024, const std::string &name = "\0", bool uniformBuffer = false); ~BufferMgr(); SubBuffer acquireBuffer(int size); void releaseBuffer(SubBuffer &subBuffer); //! For per-frame buffer allocation (don't use acquireBuffer nor releaseBuffer on this BufferMgr when using this) SubBuffer fastAcquireBuffer(uint32_t size); // Release every previously acquired SubBuffer, mustn't be used with acquireBuffer void reset(); // Return a pointer to the beginning of the SubBuffer // If BufferMgr is not HOST_VISIBLE, return (void *) subBuffer.offset void *getPtr(SubBuffer &subBuffer); // Return a pointer to the beginning of the BufferMgr, or nullptr if not HOST_VISIBLE void *getPtr() {return data;} // Make the changes from the device visible (if host_cached) void invalidate(); // Make the changes from the device visible (if host_cached) void invalidate(SubBuffer &subBuffer); // Make the changes from the device visible (if host_cached) void invalidate(const std::vector<SubBuffer> &subBuffers); // Make the changes from the gpu visible (if host_cached) void flush(); // Make the changes from the gpu visible (if host_cached) void flush(SubBuffer &subBuffer); // Make the changes from the gpu visible (if host_cached) void flush(const std::vector<SubBuffer> &subBuffers); // Set a name to the Buffer hold by BufferMgr (visible from debug layer and nvidia nsight graphics) void setName(const std::string &name); // internally used, set the alignment requirement for uniform static void setUniformOffsetAlignment(int alignment) {uniformOffsetAlignment = alignment;} // Record a copy from one SubBuffer to another SubBuffer static void copy(VkCommandBuffer &cmd, SubBuffer &src, SubBuffer &dst); // Record a copy of size octects from one SubBuffer to another SubBuffer static void copy(VkCommandBuffer &cmd, SubBuffer &src, SubBuffer &dst, int size); // Record a copy of size octects from one SubBuffer to another SubBuffer with an offset static void copy(VkCommandBuffer &cmd, SubBuffer &src, SubBuffer &dst, int size, int srcOffset, int dstOffset); inline VkBuffer &getBuffer() { return buffer; } private: void releaseBuffer(); // Release next buffer in stack static void startMainloop(BufferMgr *self); std::unique_ptr<std::thread> releaseThread; std::vector<SubBuffer> releaseStack; bool isAlive = false; std::mutex mutex, mutexQueue; uint32_t maxOffset = 0; VulkanMgr &master; VkBuffer buffer; SubMemory memory; std::string name; void *data = nullptr; void insert(SubBuffer &subBuffer); static int uniformOffsetAlignment; //! each std::list in this std::list are equally sized SubBuffer std::list<std::list<SubBuffer>> availableSubBufferZones; //std::list<SubBuffer> availableSubBuffer; const uint32_t bufferBlocSize; const bool uniformBuffer; }; #endif /* end of include guard: BUFFER_MGR_HPP */
44.219512
231
0.733591
[ "vector" ]
53f5e89d542b2da2c45ba1cf1393e5bf6abdb8d9
8,477
cpp
C++
src/files/files_fat32.cpp
nitz/PowerOverwhelmiing
a2fcd1d1ce22af7022144576d93f24c0da301381
[ "0BSD" ]
24
2020-09-28T17:11:52.000Z
2022-02-11T04:33:33.000Z
src/files/files_fat32.cpp
nitz/PowerOverwhelmiing
a2fcd1d1ce22af7022144576d93f24c0da301381
[ "0BSD" ]
100
2020-10-11T20:55:39.000Z
2021-12-23T15:55:13.000Z
src/files/files_fat32.cpp
nitz/PowerOverwhelmiing
a2fcd1d1ce22af7022144576d93f24c0da301381
[ "0BSD" ]
5
2020-09-28T16:19:02.000Z
2021-09-09T23:18:12.000Z
#include "files_fat32.h" #include "diskio.h" #include "diskio_blkdev.h" #include "cwalk.h" #include "global/global_data.h" #include "files_log_module.ii" namespace files { namespace { constexpr const char* DriveRoot = ""; constexpr uint8_t MountOptionDelayed = 0; constexpr uint8_t MountOptionImmediate = 1; constexpr uint8_t UnmountOptionNone = 0; const nrf_block_dev_sdc_t* sdCardBlockDevice = nullptr; } Fat32::Fat32() { } ////////////////////////////////////////////////////////////////////////// // Disk Operations bool Fat32::Mount() { if (mounted) { // already mounted. return true; } if (!Initialize()) { return false; } NRF_LOG_INFO("Mounting FAT filesystem on SDC..."); FRESULT mountResult = f_mount(&fileSystem, DriveRoot, MountOptionImmediate); if (mountResult != FR_OK) { NRF_LOG_ERROR("Failed to mount filesystem on SDC! (%d)", mountResult); return false; } f_getlabel(DriveRoot, driveLabel, &driveSerial); NRF_LOG_INFO("Mounted `%s` (%08X).", nrf_log_push(driveLabel), driveSerial); mounted = true; return true; } bool Fat32::Unmount() { if (mounted == false) { return true; } NRF_LOG_INFO("Unmounting SDC..."); FRESULT unmountResult = f_mount(nullptr, DriveRoot, UnmountOptionNone); if (unmountResult != FR_OK) { NRF_LOG_ERROR("Failed to unmount SDC! (%d)", unmountResult); return false; } memset(driveLabel, 0, sizeof(driveLabel)); driveSerial = 0; NRF_LOG_INFO("Unmounted."); mounted = false; return true; } ////////////////////////////////////////////////////////////////////////// // Directory Operations bool Fat32::DirectoryOpen(Fat32Directory& dir, const char *directoryPath) { if (mounted == false) { NRF_LOG_WARNING("Cannot DirectoryOpen while SDC is not mounted."); return false; } FRESULT status = f_opendir(&dir, directoryPath); if (status != FR_OK) { NRF_LOG_WARNING("Failed to DirectoryOpen `%s`: %d", nrf_log_push((char*)directoryPath), status); return false; } return true; } bool Fat32::DirectoryRead(Fat32Directory& dir, Fat32FileInfo& info) { if (mounted == false) { NRF_LOG_WARNING("Cannot DirectoryRead while SDC is not mounted."); return false; } FRESULT status = f_readdir(&dir, &info); if (status != FR_OK) { NRF_LOG_WARNING("Failed to DirectoryRead: %d", status); return false; } // if we read something with a null name, we're done. // otherwise, the read was good. return info.fname[0] != '\0'; } bool Fat32::DirectoryClose(Fat32Directory& dir) { if (mounted == false) { NRF_LOG_WARNING("Cannot DirectoryClose while SDC is not mounted."); return false; } FRESULT status = f_closedir(&dir); if (status != FR_OK) { NRF_LOG_WARNING("Failed to DirectoryClose: %d", status); return false; } return true; } ////////////////////////////////////////////////////////////////////////// // File Operations bool Fat32::FileOpen(Fat32File& file, const char *filePath, uint16_t mode) { if (mounted == false) { NRF_LOG_WARNING("Cannot FileOpen while SDC is not mounted."); return false; } FRESULT status = f_open(&file, filePath, mode); if (status != FR_OK) { NRF_LOG_WARNING("Failed to FileOpen `%s`: %d", filePath, status); return false; } return true; } bool Fat32::FileRead(Fat32File& file, void *buffer, size_t amountToRead, size_t *amountRead) { if (mounted == false) { NRF_LOG_WARNING("Cannot FileRead while SDC is not mounted."); return false; } FRESULT status = f_read(&file, buffer, amountToRead, amountRead); if (status != FR_OK) { NRF_LOG_WARNING("Failed to FileRead: %d", status); return false; } return true; } bool Fat32::FileWrite(Fat32File& file, const void *buffer, size_t bufferLength, size_t *amountWritten) { if (mounted == false) { NRF_LOG_WARNING("Cannot FileWrite while SDC is not mounted."); return false; } FRESULT status = f_write(&file, buffer, bufferLength, amountWritten); if (status != FR_OK) { NRF_LOG_WARNING("Failed to FileWrite: %d", status); return false; } return true; } bool Fat32::FileSeek(Fat32File& file, size_t offset) { if (mounted == false) { NRF_LOG_WARNING("Cannot FileSeek while SDC is not mounted."); return false; } FRESULT status = f_lseek(&file, offset); if (status != FR_OK) { NRF_LOG_WARNING("Failed to FileSeek: %d", status); return false; } return true; } bool Fat32::FileClose(Fat32File& file) { if (mounted == false) { NRF_LOG_WARNING("Cannot FileClose while SDC is not mounted."); return false; } FRESULT status = f_close(&file); if (status != FR_OK) { NRF_LOG_WARNING("Failed to FileClose: %d", status); return false; } return true; } bool Fat32::FileStat(Fat32FileInfo& fileInfo, const char *path) { if (mounted == false) { NRF_LOG_WARNING("Cannot FileStat while SDC is not mounted."); return false; } FRESULT status = f_stat(path, &fileInfo); if (status != FR_OK) { NRF_LOG_WARNING("Failed to FileStat: %d", status); return false; } return true; } ////////////////////////////////////////////////////////////////////////// // Internal Operations // USB Handlers void Fat32::UsbDidDisable(app_usbd_event_type_t event) { if (mounted == false && autoRemountAfterUsbDisconnect) { NRF_LOG_INFO("USB stopped, automatically remounting SDC."); Initialize(); Mount(); } else { NRF_LOG_INFO("USB stopped, but we don't care about remounting."); } } void Fat32::UsbWillEnable(app_usbd_event_type_t event) { if (initialized) { NRF_LOG_INFO("USB got power, uninitializing SDC to give it priority."); Uninitialize(); } else { NRF_LOG_INFO("USB got power, but we were not initialized, ignoring."); } } bool Fat32::Initialize() { if (initialized) { return true; } // zero filesystem memset(&fileSystem, 0, sizeof(FATFS)); if (registered == false && RegisterBlockDevice() == false) { // we weren't able to register, can't init. NRF_LOG_ERROR("Cannot initialize SDC, registration failed."); return false; } // we'll stick to unix-style paths for now. cwk_path_set_style(CWK_STYLE_UNIX); // #hardcode -- we only support one disk right now. diskIndex = 0; NRF_LOG_VERBOSE("Initializing disk %d (SDC)...", diskIndex); // trying 3 times, cause that's what they did in the example // and here: https://devzone.nordicsemi.com/f/nordic-q-a/59811/fatfs-example-bug DSTATUS diskStatus = STA_NOINIT; for (uint32_t retries = 3; retries && diskStatus; --retries) { diskStatus = disk_initialize(0); } if (diskStatus) { NRF_LOG_ERROR("Failed to initialize SDC (disk %d) with error: %d.", diskIndex, diskStatus); return false; } uint32_t blocks_per_mb = (1024uL * 1024uL) / sdCardBlockDevice->block_dev.p_ops->geometry(&sdCardBlockDevice->block_dev)->blk_size; uint32_t capacity = sdCardBlockDevice->block_dev.p_ops->geometry(&sdCardBlockDevice->block_dev)->blk_count / blocks_per_mb; NRF_LOG_INFO("Initialized SDC (disk %d) with a capacity of %d MB", diskIndex, capacity); initialized = true; return true; } bool Fat32::Uninitialize() { if (initialized == false) { return true; } if (Unmount() == false) { NRF_LOG_ERROR("Cannot uninitialize SDC, was unable to unmount."); return false; } NRF_LOG_INFO("Uninitializing SDC..."); DSTATUS status = disk_uninitialize(diskIndex); if (status != STA_NOINIT) { NRF_LOG_ERROR("Failed to uninitialize SDC %d with error: %d.", diskIndex, status); return false; } diskIndex = -1; initialized = false; registered = false; memset(&fileSystem, 0, sizeof(FATFS)); NRF_LOG_INFO("Uninitialized."); return true; } bool Fat32::RegisterBlockDevice() { if (registered) { return true; } NRF_LOG_VERBOSE("Registering SDC Block Device..."); sdCardBlockDevice = get_sdc_block_device(); if (sdCardBlockDevice == nullptr) { // uh oh. NRF_LOG_ERROR("Failed to get valid SDC block device. Cannot register drive."); return false; } static diskio_blkdev_t drives[] = { DISKIO_BLOCKDEV_CONFIG(NRF_BLOCKDEV_BASE_ADDR(*sdCardBlockDevice, block_dev), NULL) }; diskio_blockdev_register(drives, ARRAY_SIZE(drives)); NRF_LOG_VERBOSE("Registered."); registered = true; return true; } } // namespace files
21.034739
133
0.651882
[ "geometry" ]
d87ea9f9affc66378d22ed571d67c297aaa10c4f
6,042
cpp
C++
iecp/src/v20210914/model/DescribeEdgeOperationLogsRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
iecp/src/v20210914/model/DescribeEdgeOperationLogsRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
iecp/src/v20210914/model/DescribeEdgeOperationLogsRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/iecp/v20210914/model/DescribeEdgeOperationLogsRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Iecp::V20210914::Model; using namespace std; DescribeEdgeOperationLogsRequest::DescribeEdgeOperationLogsRequest() : m_beginTimeHasBeenSet(false), m_endTimeHasBeenSet(false), m_offsetHasBeenSet(false), m_limitHasBeenSet(false), m_sortHasBeenSet(false), m_moduleHasBeenSet(false), m_conditionHasBeenSet(false) { } string DescribeEdgeOperationLogsRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_beginTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "BeginTime"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_beginTime.c_str(), allocator).Move(), allocator); } if (m_endTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EndTime"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_endTime.c_str(), allocator).Move(), allocator); } if (m_offsetHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Offset"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_offset, allocator); } if (m_limitHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Limit"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_limit, allocator); } if (m_sortHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Sort"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_sort.begin(); itr != m_sort.end(); ++itr, ++i) { d[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(d[key.c_str()][i], allocator); } } if (m_moduleHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Module"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_module.c_str(), allocator).Move(), allocator); } if (m_conditionHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Condition"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_condition.ToJsonObject(d[key.c_str()], allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string DescribeEdgeOperationLogsRequest::GetBeginTime() const { return m_beginTime; } void DescribeEdgeOperationLogsRequest::SetBeginTime(const string& _beginTime) { m_beginTime = _beginTime; m_beginTimeHasBeenSet = true; } bool DescribeEdgeOperationLogsRequest::BeginTimeHasBeenSet() const { return m_beginTimeHasBeenSet; } string DescribeEdgeOperationLogsRequest::GetEndTime() const { return m_endTime; } void DescribeEdgeOperationLogsRequest::SetEndTime(const string& _endTime) { m_endTime = _endTime; m_endTimeHasBeenSet = true; } bool DescribeEdgeOperationLogsRequest::EndTimeHasBeenSet() const { return m_endTimeHasBeenSet; } uint64_t DescribeEdgeOperationLogsRequest::GetOffset() const { return m_offset; } void DescribeEdgeOperationLogsRequest::SetOffset(const uint64_t& _offset) { m_offset = _offset; m_offsetHasBeenSet = true; } bool DescribeEdgeOperationLogsRequest::OffsetHasBeenSet() const { return m_offsetHasBeenSet; } uint64_t DescribeEdgeOperationLogsRequest::GetLimit() const { return m_limit; } void DescribeEdgeOperationLogsRequest::SetLimit(const uint64_t& _limit) { m_limit = _limit; m_limitHasBeenSet = true; } bool DescribeEdgeOperationLogsRequest::LimitHasBeenSet() const { return m_limitHasBeenSet; } vector<FieldSort> DescribeEdgeOperationLogsRequest::GetSort() const { return m_sort; } void DescribeEdgeOperationLogsRequest::SetSort(const vector<FieldSort>& _sort) { m_sort = _sort; m_sortHasBeenSet = true; } bool DescribeEdgeOperationLogsRequest::SortHasBeenSet() const { return m_sortHasBeenSet; } string DescribeEdgeOperationLogsRequest::GetModule() const { return m_module; } void DescribeEdgeOperationLogsRequest::SetModule(const string& _module) { m_module = _module; m_moduleHasBeenSet = true; } bool DescribeEdgeOperationLogsRequest::ModuleHasBeenSet() const { return m_moduleHasBeenSet; } OperationLogsCondition DescribeEdgeOperationLogsRequest::GetCondition() const { return m_condition; } void DescribeEdgeOperationLogsRequest::SetCondition(const OperationLogsCondition& _condition) { m_condition = _condition; m_conditionHasBeenSet = true; } bool DescribeEdgeOperationLogsRequest::ConditionHasBeenSet() const { return m_conditionHasBeenSet; }
26.5
96
0.716816
[ "vector", "model" ]
d88236d71433ebfff3dec3150e87b407840e1468
15,443
cpp
C++
src/String.cpp
gmalysa/gui2d
0675d396b3f1e28073b77903026c3c797cd445b9
[ "BSD-3-Clause" ]
null
null
null
src/String.cpp
gmalysa/gui2d
0675d396b3f1e28073b77903026c3c797cd445b9
[ "BSD-3-Clause" ]
null
null
null
src/String.cpp
gmalysa/gui2d
0675d396b3f1e28073b77903026c3c797cd445b9
[ "BSD-3-Clause" ]
null
null
null
/** * @file 2dgui/String.cpp * @todo License/copyright statement */ // Standard headers // None // Project definitions #include "2dgui/String.h" #include "2dgui/Manager.h" /** * This is the only constructor that should be used, to configure the necessary * rendering information immediately. * @param m Manager to use to track this string * @param font Font to use to render the string (this can be changed later) */ gui2d::String::String(gui2d::Font* font) : _font(font) { init(); } /** * Initialization routine sets all of our default member variable data to avoid repeating it */ void gui2d::String::init(void) { _init = _gInit = _modified = false; _x = _y = 0.0f; _vertexCount = _indexCount = _strLen = _maxCount = 0; _color = glm::vec4(1.0f); _bMinX = _bMinY = SHRT_MIN; _bMaxX = _bMaxY = SHRT_MAX; _vertcoords = NULL; _texcoords = NULL; _index = NULL; } /** * Destructor, cleans up resources based on initialization state at call */ gui2d::String::~String(void) { gui2d::Manager::getSingleton().removeString(this); if (_init) { delete[] _vertcoords; delete[] _texcoords; delete[] _index; } if (_gInit) { glBindVertexArray(0); glDeleteVertexArrays(1, &_vao); glBindBuffer(GL_ARRAY_BUFFER, 0); glDeleteBuffers(2, _vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glDeleteBuffers(1, &_ibo); } } /** * Check for capacity in the currently allocated arrays * @param Capacity requested * @return bool True if the capacity is high enough */ bool gui2d::String::hasCapacity(int count) { return count <= _maxCount; } /** * Double the allocated space and copy the count elements to the new buffer * @param minCapacity The minimum capacity needed * @param copyCount The number of values to copy from the previous buffers */ void gui2d::String::increaseCapacity(int minCapacity, int copyCount) { int newCap = _maxCount*2; glm::i16vec2 *newVert; glm::u16vec2 *newTex; GLushort* newIndex; if (_maxCount*2 < minCapacity) newCap = minCapacity+1; else newCap = _maxCount*2; // Create new arrays newVert = new glm::i16vec2[newCap*4]; newTex = new glm::u16vec2[newCap*4]; newIndex = new GLushort[newCap*6]; // Copy over values if (_init) { memcpy(newVert, _vertcoords, copyCount*4*sizeof(glm::i16vec2)); memcpy(newTex, _texcoords, copyCount*4*sizeof(glm::u16vec2)); memcpy(newIndex, _index, copyCount*6*sizeof(GLushort)); // Clean up memory that we are ditching delete[] _vertcoords; delete[] _texcoords; delete[] _index; } // Save pointers _vertcoords = newVert; _texcoords = newTex; _index = newIndex; // Update our maximum containable count _maxCount = newCap; _init = true; } /** * Translate this string by a fixed amount in normalized coordinates; redraw * @param normX The amount to translate x by, in normalized coordinates * @param normY The amount to translate y by, in normalized coordinates * @return Reference to the string to allow chaining */ gui2d::String& gui2d::String::translate(float normX, float normY) { return setPosition(_x+normX, _y+normY); } /** * Update the opacity methods; we don't use the parent transparent approach because * opacity is stored as part of our color vec4. * @param alpha */ void gui2d::String::setOpacity(float alpha) { _color.w = alpha; } /** * Update the opacity methods; we don't use a glubyte to store alpha but it is part of * the interface */ void gui2d::String::setOpacity(GLubyte alpha) { setOpacity(alpha/255.0f); } /** * Adjust this string's position, redrawing it in order to do so * @param normX The new x position, in normalized coordinates * @param normY The new y position, in normalized coordinates * @return Reference to the string to allow chaining */ gui2d::String& gui2d::String::setPosition(float normX, float normY) { // Initialize our member variables for this string _vertexCount = 0; _indexCount = 0; // Calculate initial location based on normalized coordinates _curX = static_cast<GLshort>(normX * (1 << 15)); _curY = static_cast<GLshort>(normY * (1 << 15)); _x = normX; _y = normY; _startX = _curX; _startY = _curY; // Actually draw the string now findPenDraw(_source); return *this; } /** * Provide a normalized float maximum x coordinate for clipping * @param normMaxX The maximum x value of a displayed string */ void gui2d::String::setMaxX(float normMaxX) { if (normMaxX > 1.0f) _bMaxX = SHRT_MAX; else if (normMaxX < -1.0f) _bMaxX = SHRT_MIN; else _bMaxX = static_cast<GLint>(normMaxX * (1 << 15)); } /** * Provide a normalized float maximum y coordinate for clipping * @param normMaxY The maximum y value of a displayed string */ void gui2d::String::setMaxY(float normMaxY) { if (normMaxY > 1.0f) _bMaxY = SHRT_MAX; else if (normMaxY < -1.0f) _bMaxY = SHRT_MIN; else _bMaxY = static_cast<GLint>(normMaxY * (1 << 15)); } /** * Draw the string from scratch, set init flag, save important rendering parameters, using * the saved x and y position data * @param source The source text to draw */ void gui2d::String::drawText(const std::string& source) { drawText(source, _x, _y); } /** * Draws the string from scratch, saves rendering parameters, etc. using a new position * @param source The source text to draw * @param normX The normalized x coordinate of the new string * @param normY The normalized y coordinate of the new string */ void gui2d::String::drawText(const std::string& source, float normX, float normY) { // Make sure our buffers are big enough to hold the desired string if (!hasCapacity(source.length())) { increaseCapacity(source.length()+1, 0); } // Allocate some space, we need four unique vertices (+textures) per character (at most) // in order to account for different texture mappings at "shared" vertices, and // we need six indices to render the two triangles per character _strLen = source.length(); _maxCount = _strLen; // Initialize our member variables for this string _vertexCount = 0; _indexCount = 0; _source = std::string(source); // Calculate initial location based on normalized coordinates _curX = static_cast<GLshort>(normX * (1 << 15)); _curY = static_cast<GLshort>(normY * (1 << 15)); _x = normX; _y = normY; _startX = _curX; _startY = _curY; // Actually draw the string now findPenDraw(source); } /** * Helper method for rendering a single character into the appropriate arrays. * Note that this does not check for memory! * @param ci Reference to character info struct for the character being drawn * @param curX The current X coordinate to draw the character at * @param curY The current Y coordinate to draw the character at * @param indexOffset The offset of the index buffer to write to for this character's quad * @param vertexOffset The offset of the vertex buffer to write to for this character's quad */ void gui2d::String::drawChar(const gui2d::Font::char_info& ci, GLshort curX, GLshort curY, int indexOffset, int vertexOffset) { GLshort mx, my; mx = curX + ci.bl; my = curY; // Skip empty characters (this means we don't render spaces, for instance) if (ci.sbw == 0) return; // Set up vertex and texture coordinates, going counter clockwise _index[indexOffset] = vertexOffset; _index[indexOffset+3] = vertexOffset; _vertcoords[vertexOffset] = glm::i16vec2(mx, my); _texcoords[vertexOffset] = glm::u16vec2(ci.tx, USHRT_MAX); _index[indexOffset+1] = vertexOffset+1; _vertcoords[vertexOffset+1] = glm::i16vec2(mx + ci.sbw, my); _texcoords[vertexOffset+1] = glm::u16vec2(ci.txEnd, USHRT_MAX); _index[indexOffset+2] = vertexOffset+2; _index[indexOffset+4] = vertexOffset+2; _vertcoords[vertexOffset+2] = glm::i16vec2(mx + ci.sbw, my + _font->getTexHeight()); _texcoords[vertexOffset+2] = glm::u16vec2(ci.txEnd, 0); _index[indexOffset+5] = vertexOffset+3; _vertcoords[vertexOffset+3] = glm::i16vec2(mx, my + _font->getTexHeight()); _texcoords[vertexOffset+3] = glm::u16vec2(ci.tx, 0); } /** * Starting with the current values for all counts and positions, update our counts and pen location * for the current string (used to recalculate pen position when saving part of the string) * @param source The string to find the pen state for. */ void gui2d::String::findPen(const std::string& source) { const char *c; const char *p = 0; const gui2d::Font::char_info *ci; GLint tempX = 0; for (c = source.c_str(); *c != 0; c++) { ci = _font->getCharInfo(*c); // Account for kerning if (p) { tempX = static_cast<GLint>(_curX) + _font->getKerning(*p, *c) + ci->ax; } else { tempX = static_cast<GLint>(_curX) + ci->ax; } // Check if we're going to go out of bounds by advancing our pointer, if so stop drawing if (tempX > _bMaxX) { return; } // Update our "pen" for where to start the next character _curX = static_cast<GLshort>(tempX); if (ci->sbw == 0) { // Disable kerning for next iteration p = 0; continue; } _vertexCount += 4; _indexCount += 6; p = c; } } /** * Same thing as the pen finding method, except this draws the string as well. * @param source The string to find the pen+draw for */ void gui2d::String::findPenDraw(const std::string& source) { const char *c; const char *p = 0; const gui2d::Font::char_info *ci; GLint tempX = 0; _modified = true; for (c = source.c_str(); *c != 0; ++c) { ci = _font->getCharInfo(*c); // Account for kerning if (p) { tempX = static_cast<GLint>(_curX) + _font->getKerning(*p, *c) + ci->ax; } else { tempX = static_cast<GLint>(_curX) + ci->ax; } // Check if we're going to go out of bounds by advancing our pointer, if so stop drawing if (tempX > _bMaxX) { return; } drawChar(*ci, _curX, _curY, _indexCount, _vertexCount); // Update our "pen" for where to start the next character _curX = static_cast<GLshort>(tempX); // Skip empty characters (in either dimension, this means we don't render spaces, for instance) if (ci->sbw == 0) { p = 0; continue; } _vertexCount += 4; _indexCount += 6; p = c; } } /** * Append a string to this one * @param source The string to append */ void gui2d::String::append(const std::string& source) { // First ensure we have capacity if (!hasCapacity(_source.length() + source.length())) { increaseCapacity(_source.length() + source.length(), _strLen); } // Now fill in the characters for our new string findPenDraw(source); // Save the string to our local copy _source.append(source); _strLen = _source.length(); } /** * Remove all of a string after the offset given * @param start The starting character index to remove from (to end) */ void gui2d::String::remove(int start) { remove(start, _strLen); } /** * Remove part of a string, moving the characters after the substring down into * the newly vacated area * @param start The starting character index to remove from * @param length The number of characters to remove */ void gui2d::String::remove(int start, int length) { std::string tail, front; // Reset string info _curX = _startX; _curY = _startY; _vertexCount = 0; _indexCount = 0; // If we're removing from the end, this is a lot faster if (start+length >= _strLen) { // Update the metrics _source = _source.substr(0, start); _strLen = start; findPen(_source); } else { // Get the two string bits that we're keeping tail = _source.substr(start+length, std::string::npos); front = _source.substr(0, start); // Calculate the pen location based on the retained portion findPen(front); // Now, draw in the tail in the right place findPenDraw(tail); // Update our source string and count information _source = front.append(tail); _strLen = _source.length(); } } /** * Insert a string at a given offset * @param source The string to insert * @param offset The character offset to insert after */ void gui2d::String::insert(const std::string& source, int offset) { std::string front, tail; // Ensure we have capacity for both strings if (!hasCapacity(_source.length() + source.length())) { increaseCapacity(_source.length() + source.length(), offset); } // Set up all of our strings front = _source.substr(0, offset); tail = _source.substr(offset, std::string::npos); // Zero counters for new draw _curX = _startX; _curY = _startY; _vertexCount = 0; _indexCount = 0; // Update/draw each string component findPen(front); findPenDraw(source); findPenDraw(tail); // Save new metrics _source = front.append(source).append(tail); _strLen = _source.length(); } /** * Initialize the graphics the first time that this is rendered */ void gui2d::String::graphicsInit(void) { gui2d::Manager& m = gui2d::Manager::getSingleton(); // If already initialized, delete these buffers if (_gInit) { glBindVertexArray(0); glDeleteVertexArrays(1, &_vao); glBindBuffer(GL_ARRAY_BUFFER, 0); glDeleteBuffers(2, _vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glDeleteBuffers(1, &_ibo); } // Generate a vertex array object for our buffers glGenVertexArrays(1, &_vao); glBindVertexArray(_vao); // Generate the vertex buffer that will store our vertices and texture coordinates glGenBuffers(2, _vbo); glBindBuffer(GL_ARRAY_BUFFER, _vbo[0]); glVertexAttribPointer(m.getTSInVertLocation(), 2, GL_SHORT, GL_TRUE, sizeof(glm::i16vec2), 0); glEnableVertexAttribArray(m.getTSInVertLocation()); glBindBuffer(GL_ARRAY_BUFFER, _vbo[1]); glVertexAttribPointer(m.getTSInTexLocation(), 2, GL_UNSIGNED_SHORT, GL_TRUE, sizeof(glm::u16vec2), 0); glEnableVertexAttribArray(m.getTSInTexLocation()); // Generate the index buffer object glGenBuffers(1, &_ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ibo); glBindVertexArray(0); _gInit = true; } /** * Render function. For now this is kind of dumb and will regenerate+rebind VBOs on each render call. */ void gui2d::String::render(void) { // Generate buffers one time if they haven't been if (!_gInit) graphicsInit(); // Don't draw anything if this string isn't visible if (!_visible) return; // Update the buffer data if we've been modified glBindVertexArray(_vao); if (_modified) { glBindBuffer(GL_ARRAY_BUFFER, _vbo[0]); glBufferData(GL_ARRAY_BUFFER, _vertexCount*sizeof(glm::i16vec2), _vertcoords, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, _vbo[1]); glBufferData(GL_ARRAY_BUFFER, _vertexCount*sizeof(glm::u16vec2), _texcoords, GL_DYNAMIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, _indexCount*sizeof(GLushort), _index, GL_DYNAMIC_DRAW); } // Apply the user's chosen color and Z-ordering gui2d::Manager& m = gui2d::Manager::getSingleton(); glUniform4fv(m.getTSUniformColorLocation(), 1, glm::value_ptr(_color)); glUniform1f(m.getTSUniformZLocation(), _z); // Render using the index buffer glDrawElements(GL_TRIANGLES, _indexCount, GL_UNSIGNED_SHORT, 0); glBindVertexArray(0); _modified = false; }
29.028195
128
0.685877
[ "render", "object" ]
d8948e753026e61bdbf2732686d37052949ba6c0
3,515
cxx
C++
examples/force_integration.cxx
LinjianMa/ctf
06a50b6ea4be2eeb7f3d6c43f05a0befae94f08e
[ "BSD-2-Clause" ]
108
2018-01-01T21:29:15.000Z
2022-02-24T17:51:15.000Z
examples/force_integration.cxx
LinjianMa/ctf
06a50b6ea4be2eeb7f3d6c43f05a0befae94f08e
[ "BSD-2-Clause" ]
91
2017-12-27T04:28:09.000Z
2022-03-10T09:14:43.000Z
examples/force_integration.cxx
LinjianMa/ctf
06a50b6ea4be2eeb7f3d6c43f05a0befae94f08e
[ "BSD-2-Clause" ]
45
2017-12-26T21:15:21.000Z
2022-02-10T11:16:40.000Z
/*Copyright (c) 2011, Edgar Solomonik, all rights reserved.*/ /** \addtogroup examples * @{ * \defgroup force_integration force_integration * @{ * \brief tests custom element-wise transform by doing force integration */ #include <ctf.hpp> #include "moldynamics.h" using namespace CTF; int force_integration(int n, World & dw){ Set<particle> sP = Set<particle>(); Group<force> gF = Group<force>(); Vector<particle> P(n, dw, sP); Matrix<force> F (n, n, AS, dw, gF); Matrix<force> F2(n, n, AS, dw, gF); particle * loc_parts; int64_t nloc; int64_t * inds; P.get_local_data(&nloc, &inds, &loc_parts); srand48(dw.rank); for (int64_t i=0; i<nloc; i++){ loc_parts[i].dx = drand48(); loc_parts[i].dy = drand48(); loc_parts[i].coeff = .001*drand48(); loc_parts[i].id = 777; } P.write(nloc, inds, loc_parts); force * loc_frcs; int64_t * finds; int64_t nf; F.get_local_data(&nf, &finds, &loc_frcs); for (int64_t i=0; i<nf; i++){ loc_frcs[i].fx = drand48(); loc_frcs[i].fy = drand48(); } F.write(nf, finds, loc_frcs); delete [] loc_frcs; free(finds); CTF::Transform<force,particle> uacc([](force f, particle & p){ p.dx += f.fx*p.coeff; p.dy += f.fy*p.coeff; }); F2["ij"] += F["ij"]; F2["ij"] += F["ij"]; uacc(F2["ij"],P["i"]); particle * loc_parts_new = new particle[nloc]; P.read(nloc, inds, loc_parts_new); //check that something changed int pass = 1; if (pass){ for (int64_t i=0; i<nloc; i++){ if (fabs(loc_parts[i].dx - loc_parts_new[i].dx)<1.E-6 && fabs(loc_parts[i].dy - loc_parts_new[i].dy)<1.E-6) pass = 0; } } MPI_Allreduce(MPI_IN_PLACE, &pass, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD); if (!pass && dw.rank == 0){ printf("Test incorrect: application of uacc did not modify some value.\n"); } //FIXME = must invert tensors over groups via addinv() rather than - or -=, since these use the inverse of the multiplicative id F.addinv(); uacc(F["ij"],P["i"]); uacc(F["ij"],P["i"]); P.read(nloc, inds, loc_parts_new); free(inds); if (pass){ for (int64_t i=0; i<nloc; i++){ if (fabs(loc_parts[i].dx - loc_parts_new[i].dx)>1.E-6 || fabs(loc_parts[i].dy - loc_parts_new[i].dy)>1.E-6) pass = 0; } } delete [] loc_parts; delete [] loc_parts_new; MPI_Allreduce(MPI_IN_PLACE, &pass, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD); if (dw.rank == 0){ if (pass){ printf("{ P[\"i\"] = uacc(F[\"ij\"]) } passed\n"); } else { printf("{ P[\"i\"] = uacc(F[\"ij\"]) } failed\n"); } } return pass; } #ifndef TEST_SUITE char* getCmdOption(char ** begin, char ** end, const std::string & option){ char ** itr = std::find(begin, end, option); if (itr != end && ++itr != end){ return *itr; } return 0; } int main(int argc, char ** argv){ int rank, np, n; int const in_num = argc; char ** input_str = argv; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &np); if (getCmdOption(input_str, input_str+in_num, "-n")){ n = atoi(getCmdOption(input_str, input_str+in_num, "-n")); if (n < 0) n = 5; } else n = 5; { World dw(MPI_COMM_WORLD, argc, argv); if (rank == 0){ printf("Computing force_integration A_ijkl = f(A_ijkl)\n"); } force_integration(n, dw); } MPI_Finalize(); return 0; } /** * @} * @} */ #endif
22.677419
130
0.580654
[ "vector", "transform" ]
d894b9aabd3f793a23929929c30cde8a44d7eb47
25,678
hpp
C++
fprime-sphinx-drivers/SPWManager/test/ut/GTestBase.hpp
Joshua-Anderson/fprime-sphinx-drivers
28334b667c31a796c69e0f7005e4a9c0545e65fe
[ "Apache-2.0" ]
1
2021-02-22T12:34:25.000Z
2021-02-22T12:34:25.000Z
fprime-sphinx-drivers/SPWManager/test/ut/GTestBase.hpp
Joshua-Anderson/fprime-sphinx-drivers
28334b667c31a796c69e0f7005e4a9c0545e65fe
[ "Apache-2.0" ]
2
2021-08-11T17:14:54.000Z
2021-09-09T22:31:19.000Z
fprime-sphinx-drivers/SPWManager/test/ut/GTestBase.hpp
Joshua-Anderson/fprime-sphinx-drivers
28334b667c31a796c69e0f7005e4a9c0545e65fe
[ "Apache-2.0" ]
1
2021-05-19T02:04:10.000Z
2021-05-19T02:04:10.000Z
// ====================================================================== // \title SPWManager/test/ut/GTestBase.hpp // \author Auto-generated // \brief hpp file for SPWManager component Google Test harness base class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #ifndef SPWManager_GTEST_BASE_HPP #define SPWManager_GTEST_BASE_HPP #include "TesterBase.hpp" #include "gtest/gtest.h" // ---------------------------------------------------------------------- // Macros for command history assertions // ---------------------------------------------------------------------- #define ASSERT_CMD_RESPONSE_SIZE(size) \ this->assertCmdResponse_size(__FILE__, __LINE__, size) #define ASSERT_CMD_RESPONSE(index, opCode, cmdSeq, response) \ this->assertCmdResponse(__FILE__, __LINE__, index, opCode, cmdSeq, response) // ---------------------------------------------------------------------- // Macros for event history assertions // ---------------------------------------------------------------------- #define ASSERT_EVENTS_SIZE(size) \ this->assertEvents_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_SPWManager_SpaceWireInitializationError_SIZE(size) \ this->assertEvents_SPWManager_SpaceWireInitializationError_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_SPWManager_SpaceWireInitializationError(index, _status) \ this->assertEvents_SPWManager_SpaceWireInitializationError(__FILE__, __LINE__, index, _status) #define ASSERT_EVENTS_SPWManager_SpaceWireLinkDisconnected_SIZE(size) \ this->assertEvents_SPWManager_SpaceWireLinkDisconnected_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_SPWManager_SpaceWireError_SIZE(size) \ this->assertEvents_SPWManager_SpaceWireError_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_SPWManager_SpaceWireError(index, _status, _statusCode) \ this->assertEvents_SPWManager_SpaceWireError(__FILE__, __LINE__, index, _status, _statusCode) #define ASSERT_EVENTS_SPWManager_SpaceWireTransactionTimeout_SIZE(size) \ this->assertEvents_SPWManager_SpaceWireTransactionTimeout_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_SPWManager_SpaceWireTransactionTimeout(index, _timeout, _command, _address, _status) \ this->assertEvents_SPWManager_SpaceWireTransactionTimeout(__FILE__, __LINE__, index, _timeout, _command, _address, _status) #define ASSERT_EVENTS_SPWManager_RMAPWriteResult_SIZE(size) \ this->assertEvents_SPWManager_RMAPWriteResult_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_SPWManager_RMAPWriteResult(index, _address) \ this->assertEvents_SPWManager_RMAPWriteResult(__FILE__, __LINE__, index, _address) #define ASSERT_EVENTS_SPWManager_RMAPReadResult_SIZE(size) \ this->assertEvents_SPWManager_RMAPReadResult_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_SPWManager_RMAPReadResult(index, _address, _value) \ this->assertEvents_SPWManager_RMAPReadResult(__FILE__, __LINE__, index, _address, _value) #define ASSERT_EVENTS_SPWManager_Busy_SIZE(size) \ this->assertEvents_SPWManager_Busy_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_SPWManager_ResetLink_SIZE(size) \ this->assertEvents_SPWManager_ResetLink_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_SPWManager_ResetLink(index, _numAborted) \ this->assertEvents_SPWManager_ResetLink(__FILE__, __LINE__, index, _numAborted) // ---------------------------------------------------------------------- // Macros for typed user from port history assertions // ---------------------------------------------------------------------- #define ASSERT_FROM_PORT_HISTORY_SIZE(size) \ this->assertFromPortHistory_size(__FILE__, __LINE__, size) #define ASSERT_from_driverWriteRMAP_SIZE(size) \ this->assert_from_driverWriteRMAP_size(__FILE__, __LINE__, size) #define ASSERT_from_driverWriteRMAP(index, _dest_addr, _dest_key, _write_addr, _buf_ptr, _num_bytes, _increment, _verify, _acknowledge) \ { \ ASSERT_GT(this->fromPortHistory_driverWriteRMAP->size(), static_cast<U32>(index)) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Index into history of from_driverWriteRMAP\n" \ << " Expected: Less than size of history (" \ << this->fromPortHistory_driverWriteRMAP->size() << ")\n" \ << " Actual: " << index << "\n"; \ const FromPortEntry_driverWriteRMAP& _e = \ this->fromPortHistory_driverWriteRMAP->at(index); \ ASSERT_EQ(_dest_addr, _e.dest_addr) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument dest_addr at index " \ << index \ << " in history of from_driverWriteRMAP\n" \ << " Expected: " << _dest_addr << "\n" \ << " Actual: " << _e.dest_addr << "\n"; \ ASSERT_EQ(_dest_key, _e.dest_key) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument dest_key at index " \ << index \ << " in history of from_driverWriteRMAP\n" \ << " Expected: " << _dest_key << "\n" \ << " Actual: " << _e.dest_key << "\n"; \ ASSERT_EQ(_write_addr, _e.write_addr) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument write_addr at index " \ << index \ << " in history of from_driverWriteRMAP\n" \ << " Expected: " << _write_addr << "\n" \ << " Actual: " << _e.write_addr << "\n"; \ ASSERT_EQ(_buf_ptr, _e.buf_ptr) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument buf_ptr at index " \ << index \ << " in history of from_driverWriteRMAP\n" \ << " Expected: " << _buf_ptr << "\n" \ << " Actual: " << _e.buf_ptr << "\n"; \ ASSERT_EQ(_num_bytes, _e.num_bytes) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument num_bytes at index " \ << index \ << " in history of from_driverWriteRMAP\n" \ << " Expected: " << _num_bytes << "\n" \ << " Actual: " << _e.num_bytes << "\n"; \ ASSERT_EQ(_increment, _e.increment) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument increment at index " \ << index \ << " in history of from_driverWriteRMAP\n" \ << " Expected: " << _increment << "\n" \ << " Actual: " << _e.increment << "\n"; \ ASSERT_EQ(_verify, _e.verify) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument verify at index " \ << index \ << " in history of from_driverWriteRMAP\n" \ << " Expected: " << _verify << "\n" \ << " Actual: " << _e.verify << "\n"; \ ASSERT_EQ(_acknowledge, _e.acknowledge) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument acknowledge at index " \ << index \ << " in history of from_driverWriteRMAP\n" \ << " Expected: " << _acknowledge << "\n" \ << " Actual: " << _e.acknowledge << "\n"; \ } #define ASSERT_from_statusOut_SIZE(size) \ this->assert_from_statusOut_size(__FILE__, __LINE__, size) #define ASSERT_from_statusOut(index, _spwStatus) \ { \ ASSERT_GT(this->fromPortHistory_statusOut->size(), static_cast<U32>(index)) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Index into history of from_statusOut\n" \ << " Expected: Less than size of history (" \ << this->fromPortHistory_statusOut->size() << ")\n" \ << " Actual: " << index << "\n"; \ const FromPortEntry_statusOut& _e = \ this->fromPortHistory_statusOut->at(index); \ ASSERT_EQ(_spwStatus, _e.spwStatus) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument spwStatus at index " \ << index \ << " in history of from_statusOut\n" \ << " Expected: " << _spwStatus << "\n" \ << " Actual: " << _e.spwStatus << "\n"; \ } #define ASSERT_from_PingResponse_SIZE(size) \ this->assert_from_PingResponse_size(__FILE__, __LINE__, size) #define ASSERT_from_PingResponse(index, _key) \ { \ ASSERT_GT(this->fromPortHistory_PingResponse->size(), static_cast<U32>(index)) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Index into history of from_PingResponse\n" \ << " Expected: Less than size of history (" \ << this->fromPortHistory_PingResponse->size() << ")\n" \ << " Actual: " << index << "\n"; \ const FromPortEntry_PingResponse& _e = \ this->fromPortHistory_PingResponse->at(index); \ ASSERT_EQ(_key, _e.key) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument key at index " \ << index \ << " in history of from_PingResponse\n" \ << " Expected: " << _key << "\n" \ << " Actual: " << _e.key << "\n"; \ } #define ASSERT_from_driverReset_SIZE(size) \ this->assert_from_driverReset_size(__FILE__, __LINE__, size) #define ASSERT_from_driverReadRMAP_SIZE(size) \ this->assert_from_driverReadRMAP_size(__FILE__, __LINE__, size) #define ASSERT_from_driverReadRMAP(index, _dest_addr, _dest_key, _read_addr, _buf_ptr, _num_bytes, _increment) \ { \ ASSERT_GT(this->fromPortHistory_driverReadRMAP->size(), static_cast<U32>(index)) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Index into history of from_driverReadRMAP\n" \ << " Expected: Less than size of history (" \ << this->fromPortHistory_driverReadRMAP->size() << ")\n" \ << " Actual: " << index << "\n"; \ const FromPortEntry_driverReadRMAP& _e = \ this->fromPortHistory_driverReadRMAP->at(index); \ ASSERT_EQ(_dest_addr, _e.dest_addr) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument dest_addr at index " \ << index \ << " in history of from_driverReadRMAP\n" \ << " Expected: " << _dest_addr << "\n" \ << " Actual: " << _e.dest_addr << "\n"; \ ASSERT_EQ(_dest_key, _e.dest_key) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument dest_key at index " \ << index \ << " in history of from_driverReadRMAP\n" \ << " Expected: " << _dest_key << "\n" \ << " Actual: " << _e.dest_key << "\n"; \ ASSERT_EQ(_read_addr, _e.read_addr) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument read_addr at index " \ << index \ << " in history of from_driverReadRMAP\n" \ << " Expected: " << _read_addr << "\n" \ << " Actual: " << _e.read_addr << "\n"; \ ASSERT_EQ(_buf_ptr, _e.buf_ptr) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument buf_ptr at index " \ << index \ << " in history of from_driverReadRMAP\n" \ << " Expected: " << _buf_ptr << "\n" \ << " Actual: " << _e.buf_ptr << "\n"; \ ASSERT_EQ(_num_bytes, _e.num_bytes) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument num_bytes at index " \ << index \ << " in history of from_driverReadRMAP\n" \ << " Expected: " << _num_bytes << "\n" \ << " Actual: " << _e.num_bytes << "\n"; \ ASSERT_EQ(_increment, _e.increment) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument increment at index " \ << index \ << " in history of from_driverReadRMAP\n" \ << " Expected: " << _increment << "\n" \ << " Actual: " << _e.increment << "\n"; \ } #define ASSERT_from_driverGetStatus_SIZE(size) \ this->assert_from_driverGetStatus_size(__FILE__, __LINE__, size) namespace Drv { //! \class SPWManagerGTestBase //! \brief Auto-generated base class for SPWManager component Google Test harness //! class SPWManagerGTestBase : public SPWManagerTesterBase { protected: // ---------------------------------------------------------------------- // Construction and destruction // ---------------------------------------------------------------------- //! Construct object SPWManagerGTestBase //! SPWManagerGTestBase( #if FW_OBJECT_NAMES == 1 const char *const compName, /*!< The component name*/ const U32 maxHistorySize /*!< The maximum size of each history*/ #else const U32 maxHistorySize /*!< The maximum size of each history*/ #endif ); //! Destroy object SPWManagerGTestBase //! virtual ~SPWManagerGTestBase(void); protected: // ---------------------------------------------------------------------- // Commands // ---------------------------------------------------------------------- //! Assert size of command response history //! void assertCmdResponse_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; //! Assert command response in history at index //! void assertCmdResponse( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 index, /*!< The index*/ const FwOpcodeType opCode, /*!< The opcode*/ const U32 cmdSeq, /*!< The command sequence number*/ const Fw::CommandResponse response /*!< The command response*/ ) const; protected: // ---------------------------------------------------------------------- // Events // ---------------------------------------------------------------------- void assertEvents_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // Event: SPWManager_SpaceWireInitializationError // ---------------------------------------------------------------------- void assertEvents_SPWManager_SpaceWireInitializationError_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; void assertEvents_SPWManager_SpaceWireInitializationError( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 index, /*!< The index*/ const I32 status /*!< Error status from SPWDriver*/ ) const; protected: // ---------------------------------------------------------------------- // Event: SPWManager_SpaceWireLinkDisconnected // ---------------------------------------------------------------------- void assertEvents_SPWManager_SpaceWireLinkDisconnected_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // Event: SPWManager_SpaceWireError // ---------------------------------------------------------------------- void assertEvents_SPWManager_SpaceWireError_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; void assertEvents_SPWManager_SpaceWireError( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 index, /*!< The index*/ SPWManagerComponentBase::SpaceWireError_status status, /*!< Status enum*/ const I32 statusCode /*!< Error status code from SPWDriver*/ ) const; protected: // ---------------------------------------------------------------------- // Event: SPWManager_SpaceWireTransactionTimeout // ---------------------------------------------------------------------- void assertEvents_SPWManager_SpaceWireTransactionTimeout_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; void assertEvents_SPWManager_SpaceWireTransactionTimeout( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 index, /*!< The index*/ const U32 timeout, /*!< Timeout value*/ SPWManagerComponentBase::SpaceWireTransactionTimeout_command command, /*!< Type of command*/ const U32 address, /*!< Target address to perform command on*/ SPWManagerComponentBase::SpaceWireTransactionTimeout_status status /*!< State of transaction at timeout*/ ) const; protected: // ---------------------------------------------------------------------- // Event: SPWManager_RMAPWriteResult // ---------------------------------------------------------------------- void assertEvents_SPWManager_RMAPWriteResult_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; void assertEvents_SPWManager_RMAPWriteResult( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 index, /*!< The index*/ const U32 address /*!< Target address to perform command on*/ ) const; protected: // ---------------------------------------------------------------------- // Event: SPWManager_RMAPReadResult // ---------------------------------------------------------------------- void assertEvents_SPWManager_RMAPReadResult_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; void assertEvents_SPWManager_RMAPReadResult( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 index, /*!< The index*/ const U32 address, /*!< Target address to perform command on*/ const U32 value /*!< Value returned from read*/ ) const; protected: // ---------------------------------------------------------------------- // Event: SPWManager_Busy // ---------------------------------------------------------------------- void assertEvents_SPWManager_Busy_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // Event: SPWManager_ResetLink // ---------------------------------------------------------------------- void assertEvents_SPWManager_ResetLink_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; void assertEvents_SPWManager_ResetLink( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 index, /*!< The index*/ const U32 numAborted /*!< Number of async requests aborted*/ ) const; protected: // ---------------------------------------------------------------------- // From ports // ---------------------------------------------------------------------- void assertFromPortHistory_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From port: driverWriteRMAP // ---------------------------------------------------------------------- void assert_from_driverWriteRMAP_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From port: statusOut // ---------------------------------------------------------------------- void assert_from_statusOut_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From port: PingResponse // ---------------------------------------------------------------------- void assert_from_PingResponse_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From port: driverReset // ---------------------------------------------------------------------- void assert_from_driverReset_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From port: driverReadRMAP // ---------------------------------------------------------------------- void assert_from_driverReadRMAP_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From port: driverGetStatus // ---------------------------------------------------------------------- void assert_from_driverGetStatus_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; }; } // end namespace Drv #endif
42.725458
137
0.542721
[ "object" ]
d8990453c5ddb24c89edc3161f627d8bfe48d957
787
cpp
C++
Algorithms/Strings/Gemstones/main.cpp
ugurcan-sonmez-95/HackerRank_Problems
187d83422128228c241f279096386df5493d539d
[ "MIT" ]
null
null
null
Algorithms/Strings/Gemstones/main.cpp
ugurcan-sonmez-95/HackerRank_Problems
187d83422128228c241f279096386df5493d539d
[ "MIT" ]
null
null
null
Algorithms/Strings/Gemstones/main.cpp
ugurcan-sonmez-95/HackerRank_Problems
187d83422128228c241f279096386df5493d539d
[ "MIT" ]
null
null
null
// Gemstones - Solution #include <iostream> #include <vector> #include <map> #include <algorithm> void gemstones(std::vector<std::string> &str_vec) { std::map<char, int> char_dict; for (auto &str: str_vec) { std::sort(str.begin(), str.end()); for (int i{}; i < str.size(); i++) if (str[i] != str[i+1]) char_dict[str[i]]++; } auto find = char_dict.begin(); int count{}; while (find != char_dict.end()) { if (find->second == str_vec.size()) count++; find++; } std::cout << count; } int main() { int n; std::cin >> n; std::vector<std::string> str_vec(n); for (int i{}; i < str_vec.size(); i++) std::cin >> str_vec[i]; gemstones(str_vec); return 0; }
22.485714
51
0.514612
[ "vector" ]
d89dbd08e63438520055a947f93859c3c53ca7c6
42,362
cc
C++
orly/indy/disk/merge_data_file.test.cc
orlyatomics/orly
d413f999f51a8e553832dab4e3baa7ca68928840
[ "Apache-2.0" ]
69
2015-01-06T05:12:57.000Z
2021-11-06T20:34:10.000Z
orly/indy/disk/merge_data_file.test.cc
waderly/orly
9d7660ea9d07591f8cc6b1b92d8e6c3b8b78eeee
[ "Apache-2.0" ]
5
2015-07-09T02:21:50.000Z
2021-08-13T11:10:26.000Z
orly/indy/disk/merge_data_file.test.cc
waderly/orly
9d7660ea9d07591f8cc6b1b92d8e6c3b8b78eeee
[ "Apache-2.0" ]
15
2015-01-23T13:34:05.000Z
2020-06-15T16:46:50.000Z
/* <orly/indy/disk/merge_data_file.test.cc> Unit test for <orly/indy/disk/merge_data_file.h>. Copyright 2010-2014 OrlyAtomics, Inc. 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 <orly/indy/disk/merge_data_file.h> #include <valgrind/callgrind.h> #include <base/scheduler.h> #include <orly/indy/disk/data_file.h> #include <orly/indy/disk/disk_test.h> #include <orly/indy/disk/read_file.h> #include <orly/indy/disk/sim/mem_engine.h> #include <orly/indy/fiber/fiber_test_runner.h> #include <test/kit.h> using namespace std; using namespace chrono; using namespace Base; using namespace Orly; using namespace Orly::Atom; using namespace Orly::Indy; using namespace Orly::Indy::Disk; using namespace Orly::Indy::Disk::Util; using namespace Orly::Indy::Fiber; static const size_t BlockSize = Disk::Util::PhysicalBlockSize; Orly::Indy::Util::TPool L0::TManager::TRepo::TMapping::Pool(sizeof(TRepo::TMapping), "Repo Mapping"); Orly::Indy::Util::TPool L0::TManager::TRepo::TMapping::TEntry::Pool(sizeof(TRepo::TMapping::TEntry), "Repo Mapping Entry"); Orly::Indy::Util::TPool L0::TManager::TRepo::TDataLayer::Pool(sizeof(TMemoryLayer), "Data Layer"); Orly::Indy::Util::TPool TUpdate::Pool(sizeof(TUpdate), "Update", 1048578UL); Orly::Indy::Util::TPool TUpdate::TEntry::Pool(sizeof(TUpdate::TEntry), "Entry", 1048578UL); Disk::TBufBlock::TPool Disk::TBufBlock::Pool(BlockSize, 2000UL); FIXTURE(BasicTailing) { TFiberTestRunner runner([](std::mutex &mut, std::condition_variable &cond, bool &fin, Fiber::TRunner::TRunnerCons &) { void *state_alloc = alloca(Sabot::State::GetMaxStateSize()); TScheduler scheduler(TScheduler::TPolicy(4, 10, milliseconds(10))); Sim::TMemEngine mem_engine(&scheduler, 256 /* disk space: 256MB */, 256 /* slow disk space: 256MB */, 16384 /* page cache slots: 64MB */, 1 /* num page lru */, 1024 /* block cache slots: 64MB */, 1 /* num block lru */); Base::TUuid file_id(TUuid::Best); TSequenceNumber seq_num = 0U; TUuid index_id(TUuid::Twister); /* Make data file 1 */ { TSuprena arena; TMockMem mem_layer; /* insert data */ { TSuprena suprena; void *state_alloc = alloca(Sabot::State::GetMaxStateSize()); /* insert <[int64_t, string, desc<int64_t>, desc<string>]> */ Insert(mem_layer, ++seq_num, index_id, TKey(46L, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("short")); Insert(mem_layer, ++seq_num, index_id, TKey(49L, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")); Insert(mem_layer, ++seq_num, index_id, TKey(57L, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")); } size_t data_gen_id = 1; TDataFile data_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, &mem_layer, file_id, data_gen_id, 20UL, 0U, Medium); } /* Make data file 2 (more of the same) */ { TSuprena arena; TMockMem mem_layer; /* insert data */ { TSuprena suprena; void *state_alloc = alloca(Sabot::State::GetMaxStateSize()); /* insert <[int64_t, string, desc<int64_t>, desc<string>]> */ Insert(mem_layer, ++seq_num, index_id, TKey(7L, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("short")); Insert(mem_layer, ++seq_num, index_id, TKey(409L, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("Here's a new one")); Insert(mem_layer, ++seq_num, index_id, TKey(Native::TTombstone::Tombstone, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")); } size_t data_gen_id = 2; TDataFile data_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, &mem_layer, file_id, data_gen_id, 20UL, 0U, Medium); } /* merge them. Here seq (4,5,6) should be visible */ { TSuprena arena; TMergeDataFile merge_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, file_id, vector<size_t>{1, 2}, file_id, 4UL, 0U, Low, 16384, 20UL, true, false); TReader reader(HERE, mem_engine.GetEngine(), file_id, 4UL); TReader::TArena main_arena(&reader, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), RealTime); TReader::TIndexFile idx_file(&reader, index_id, RealTime); TReader::TArena index_arena(&idx_file, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), RealTime); TStream<Orly::Indy::Disk::Util::LogicalBlockSize, Orly::Indy::Disk::Util::LogicalBlockSize, Orly::Indy::Disk::Util::PhysicalBlockSize, Orly::Indy::Disk::Util::PageCheckedBlock, 0UL> in_stream(HERE, Source::PresentWalk, RealTime, &reader, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), 0); size_t out_offset; /* what came from file 1 but got overriden in 2 */ EXPECT_TRUE(idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("short")), &arena, state_alloc), out_offset, in_stream, &index_arena)); /* this has been tombstoned in file 2, but because it had history it's still visible as a tombstone */ EXPECT_TRUE(idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), out_offset, in_stream, &index_arena)); /* this got added in file 2 */ EXPECT_TRUE(idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("Here's a new one")), &arena, state_alloc), out_offset, in_stream, &index_arena)); vector<pair<TKey, TKey>> expected_vec; expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("short")), &arena, state_alloc), TKey(7L, &arena, state_alloc)); expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), TKey(Native::TTombstone::Tombstone, &arena, state_alloc)); expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("Here's a new one")), &arena, state_alloc), TKey(409L, &arena, state_alloc)); size_t seen = 0UL; for (TReader::TIndexFile::TKeyCursor cur_key_csr(&idx_file); cur_key_csr; ++cur_key_csr, ++seen) { const TReader::TIndexFile::TKeyItem &item = *cur_key_csr; EXPECT_TRUE(cur_key_csr); if (EXPECT_GE(expected_vec.size(), seen + 1)) { EXPECT_EQ(TKey(item.Key, &index_arena), expected_vec[seen].first); EXPECT_EQ(TKey(item.Value, &main_arena), expected_vec[seen].second); } } EXPECT_EQ(expected_vec.size(), seen); } /* merge it again to get rid of the remaining history behind the tombstone. Here seq (4,5,6) should be visible */ { TSuprena arena; TMergeDataFile merge_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, file_id, vector<size_t>{4}, file_id, 5UL, 0U, Low, 16384, 20UL, true, true); TReader reader(HERE, mem_engine.GetEngine(), file_id, 5UL); TReader::TArena main_arena(&reader, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), RealTime); TReader::TIndexFile idx_file(&reader, index_id, RealTime); TReader::TArena index_arena(&idx_file, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), RealTime); TStream<Orly::Indy::Disk::Util::LogicalBlockSize, Orly::Indy::Disk::Util::LogicalBlockSize, Orly::Indy::Disk::Util::PhysicalBlockSize, Orly::Indy::Disk::Util::PageCheckedBlock, 0UL> in_stream(HERE, Source::PresentWalk, RealTime, &reader, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), 0); size_t out_offset; /* what came from file 1 but got overriden in 2 */ EXPECT_TRUE(idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("short")), &arena, state_alloc), out_offset, in_stream, &index_arena)); /* this has been tombstoned in file 2, but because it had history it's still visible as a tombstone */ EXPECT_TRUE(idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), out_offset, in_stream, &index_arena)); /* this got added in file 2 */ EXPECT_TRUE(idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("Here's a new one")), &arena, state_alloc), out_offset, in_stream, &index_arena)); vector<pair<TKey, TKey>> expected_vec; expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("short")), &arena, state_alloc), TKey(7L, &arena, state_alloc)); expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), TKey(Native::TTombstone::Tombstone, &arena, state_alloc)); expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("Here's a new one")), &arena, state_alloc), TKey(409L, &arena, state_alloc)); size_t seen = 0UL; for (TReader::TIndexFile::TKeyCursor cur_key_csr(&idx_file); cur_key_csr; ++cur_key_csr, ++seen) { const TReader::TIndexFile::TKeyItem &item = *cur_key_csr; EXPECT_TRUE(cur_key_csr); if (EXPECT_GE(expected_vec.size(), seen + 1)) { EXPECT_EQ(TKey(item.Key, &index_arena), expected_vec[seen].first); EXPECT_EQ(TKey(item.Value, &main_arena), expected_vec[seen].second); } } EXPECT_EQ(expected_vec.size(), seen); } /* merge it again to get rid of the tombstone. Here seq (4,5) should be visible */ { TSuprena arena; TMergeDataFile merge_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, file_id, vector<size_t>{5}, file_id, 6UL, 0U, Low, 16384, 20UL, true, true); TReader reader(HERE, mem_engine.GetEngine(), file_id, 6UL); TReader::TArena main_arena(&reader, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), RealTime); TReader::TIndexFile idx_file(&reader, index_id, RealTime); TReader::TArena index_arena(&idx_file, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), RealTime); TStream<Orly::Indy::Disk::Util::LogicalBlockSize, Orly::Indy::Disk::Util::LogicalBlockSize, Orly::Indy::Disk::Util::PhysicalBlockSize, Orly::Indy::Disk::Util::PageCheckedBlock, 0UL> in_stream(HERE, Source::PresentWalk, RealTime, &reader, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), 0); size_t out_offset; /* what came from file 1 but got overriden in 2 */ EXPECT_TRUE(idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("short")), &arena, state_alloc), out_offset, in_stream, &index_arena)); /* this has been tombstoned in file 2. */ EXPECT_FALSE(idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), out_offset, in_stream, &index_arena)); /* this got added in file 2 */ EXPECT_TRUE(idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("Here's a new one")), &arena, state_alloc), out_offset, in_stream, &index_arena)); vector<pair<TKey, TKey>> expected_vec; expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("short")), &arena, state_alloc), TKey(7L, &arena, state_alloc)); expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("Here's a new one")), &arena, state_alloc), TKey(409L, &arena, state_alloc)); size_t seen = 0UL; for (TReader::TIndexFile::TKeyCursor cur_key_csr(&idx_file); cur_key_csr; ++cur_key_csr, ++seen) { const TReader::TIndexFile::TKeyItem &item = *cur_key_csr; EXPECT_TRUE(cur_key_csr); if (EXPECT_GE(expected_vec.size(), seen + 1)) { EXPECT_EQ(TKey(item.Key, &index_arena), expected_vec[seen].first); EXPECT_EQ(TKey(item.Value, &main_arena), expected_vec[seen].second); } } EXPECT_EQ(expected_vec.size(), seen); } GracefullShutdown(); std::lock_guard<std::mutex> lock(mut); fin = true; cond.notify_one(); }); } FIXTURE(BasicTailingDisabled) { TFiberTestRunner runner([](std::mutex &mut, std::condition_variable &cond, bool &fin, Fiber::TRunner::TRunnerCons &) { void *state_alloc = alloca(Sabot::State::GetMaxStateSize()); TScheduler scheduler(TScheduler::TPolicy(4, 10, milliseconds(10))); Sim::TMemEngine mem_engine(&scheduler, 256 /* disk space: 256MB */, 256 /* slow disk space: 256MB */, 16384 /* page cache slots: 64MB */, 1 /* num page lru */, 1024 /* block cache slots: 64MB */, 1 /* num block lru */); Base::TUuid file_id(TUuid::Best); TSequenceNumber seq_num = 0U; TUuid index_id(TUuid::Twister); /* Make data file 1 */ { TSuprena arena; TMockMem mem_layer; /* insert data */ { TSuprena suprena; void *state_alloc = alloca(Sabot::State::GetMaxStateSize()); /* insert <[int64_t, string, desc<int64_t>, desc<string>]> */ Insert(mem_layer, ++seq_num, index_id, TKey(46L, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("short")); Insert(mem_layer, ++seq_num, index_id, TKey(49L, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")); Insert(mem_layer, ++seq_num, index_id, TKey(57L, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")); } size_t data_gen_id = 1; TDataFile data_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, &mem_layer, file_id, data_gen_id, 20UL, 0U, Medium); } /* Make data file 2 (more of the same) */ { TSuprena arena; TMockMem mem_layer; /* insert data */ { TSuprena suprena; void *state_alloc = alloca(Sabot::State::GetMaxStateSize()); /* insert <[int64_t, string, desc<int64_t>, desc<string>]> */ Insert(mem_layer, ++seq_num, index_id, TKey(7L, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("short")); Insert(mem_layer, ++seq_num, index_id, TKey(409L, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("Here's a new one")); Insert(mem_layer, ++seq_num, index_id, TKey(Native::TTombstone::Tombstone, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")); } size_t data_gen_id = 2; TDataFile data_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, &mem_layer, file_id, data_gen_id, 20UL, 0U, Medium); } /* merge them. Here seq (4,5,6) should be visible */ { TSuprena arena; TMergeDataFile merge_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, file_id, vector<size_t>{1, 2}, file_id, 4UL, 0U, Low, 16384, 20UL, false, false); TReader reader(HERE, mem_engine.GetEngine(), file_id, 4UL); TReader::TArena main_arena(&reader, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), RealTime); TReader::TIndexFile idx_file(&reader, index_id, RealTime); TReader::TArena index_arena(&idx_file, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), RealTime); TStream<Orly::Indy::Disk::Util::LogicalBlockSize, Orly::Indy::Disk::Util::LogicalBlockSize, Orly::Indy::Disk::Util::PhysicalBlockSize, Orly::Indy::Disk::Util::PageCheckedBlock, 0UL> in_stream(HERE, Source::PresentWalk, RealTime, &reader, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), 0); size_t out_offset; /* what came from file 1 but got overriden in 2 */ EXPECT_TRUE(idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("short")), &arena, state_alloc), out_offset, in_stream, &index_arena)); /* this has been tombstoned in file 2, but because it had history it's still visible as a tombstone */ EXPECT_TRUE(idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), out_offset, in_stream, &index_arena)); /* this got added in file 2 */ EXPECT_TRUE(idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("Here's a new one")), &arena, state_alloc), out_offset, in_stream, &index_arena)); vector<pair<TKey, TKey>> expected_vec; expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("short")), &arena, state_alloc), TKey(7L, &arena, state_alloc)); expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), TKey(Native::TTombstone::Tombstone, &arena, state_alloc)); expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("Here's a new one")), &arena, state_alloc), TKey(409L, &arena, state_alloc)); size_t seen = 0UL; for (TReader::TIndexFile::TKeyCursor cur_key_csr(&idx_file); cur_key_csr; ++cur_key_csr, ++seen) { const TReader::TIndexFile::TKeyItem &item = *cur_key_csr; EXPECT_TRUE(cur_key_csr); if (EXPECT_GE(expected_vec.size(), seen + 1)) { EXPECT_EQ(TKey(item.Key, &index_arena), expected_vec[seen].first); EXPECT_EQ(TKey(item.Value, &main_arena), expected_vec[seen].second); } } EXPECT_EQ(expected_vec.size(), seen); } for (size_t i = 0; i < 3; ++i) { /* merge it again to get make sure nothing changed. Here seq (4,5,6) should be visible */ { TSuprena arena; TMergeDataFile merge_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, file_id, vector<size_t>{(4 + i)}, file_id, 5UL + i, 0U, Low, 16384, 20UL, false, false); TReader reader(HERE, mem_engine.GetEngine(), file_id, 5UL); TReader::TArena main_arena(&reader, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), RealTime); TReader::TIndexFile idx_file(&reader, index_id, RealTime); TReader::TArena index_arena(&idx_file, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), RealTime); TStream<Orly::Indy::Disk::Util::LogicalBlockSize, Orly::Indy::Disk::Util::LogicalBlockSize, Orly::Indy::Disk::Util::PhysicalBlockSize, Orly::Indy::Disk::Util::PageCheckedBlock, 0UL> in_stream(HERE, Source::PresentWalk, RealTime, &reader, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), 0); size_t out_offset; /* what came from file 1 but got overriden in 2 */ EXPECT_TRUE(idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("short")), &arena, state_alloc), out_offset, in_stream, &index_arena)); /* this has been tombstoned in file 2, but because it had history it's still visible as a tombstone */ EXPECT_TRUE(idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), out_offset, in_stream, &index_arena)); /* this got added in file 2 */ EXPECT_TRUE(idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("Here's a new one")), &arena, state_alloc), out_offset, in_stream, &index_arena)); vector<pair<TKey, TKey>> expected_vec; expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("short")), &arena, state_alloc), TKey(7L, &arena, state_alloc)); expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), TKey(Native::TTombstone::Tombstone, &arena, state_alloc)); expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("Here's a new one")), &arena, state_alloc), TKey(409L, &arena, state_alloc)); size_t seen = 0UL; for (TReader::TIndexFile::TKeyCursor cur_key_csr(&idx_file); cur_key_csr; ++cur_key_csr, ++seen) { const TReader::TIndexFile::TKeyItem &item = *cur_key_csr; EXPECT_TRUE(cur_key_csr); if (EXPECT_GE(expected_vec.size(), seen + 1)) { EXPECT_EQ(TKey(item.Key, &index_arena), expected_vec[seen].first); EXPECT_EQ(TKey(item.Value, &main_arena), expected_vec[seen].second); } } EXPECT_EQ(expected_vec.size(), seen); } } GracefullShutdown(); std::lock_guard<std::mutex> lock(mut); fin = true; cond.notify_one(); }); } FIXTURE(Deep) { TFiberTestRunner runner([](std::mutex &mut, std::condition_variable &cond, bool &fin, Fiber::TRunner::TRunnerCons &) { void *state_alloc = alloca(Sabot::State::GetMaxStateSize()); TScheduler scheduler(TScheduler::TPolicy(4, 10, milliseconds(10))); Sim::TMemEngine mem_engine(&scheduler, 256 /* disk space: 256MB */, 256 /* slow disk space: 256MB */, 16384 /* page cache slots: 64MB */, 1 /* num page lru */, 1024 /* block cache slots: 64MB */, 1 /* num block lru */); Base::TUuid file_id(TUuid::Best); TSequenceNumber seq_num = 0U; TUuid int_str_decint_decstr_idx(TUuid::Twister); TUuid int_str_int_str_idx(TUuid::Twister); TUuid int_str_decint_str_idx(TUuid::Twister); /* Make data file 1 */ { TSuprena arena; TMockMem mem_layer; /* insert data */ { TSuprena suprena; void *state_alloc = alloca(Sabot::State::GetMaxStateSize()); /* insert <[int64_t, string, desc<int64_t>, desc<string>]> */ Insert(mem_layer, ++seq_num, int_str_decint_decstr_idx, TKey(map<TDesc<int64_t>, string>{{TDesc<int64_t>(30L), string("Hello")}, {TDesc<int64_t>(9L), string("This is also a longer string")}}, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("short")); Insert(mem_layer, ++seq_num, int_str_decint_decstr_idx, TKey(map<TDesc<int64_t>, string>{{TDesc<int64_t>(30L), string("Hey yo")}, {TDesc<int64_t>(20L), string("Some form of a longer string")}}, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")); Insert(mem_layer, ++seq_num, int_str_decint_decstr_idx, TKey(map<TDesc<int64_t>, string>{{TDesc<int64_t>(30L), string("Hey yo")}, {TDesc<int64_t>(27L), string("This is also a longer string")}}, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")); /* insert <[int64_t, string, int64_t, string]> */ Insert(mem_layer, ++seq_num, int_str_int_str_idx, TKey(set<int64_t>{1, 3, 9}, &suprena, state_alloc), 1L, string("Orly"), 1L, string("short")); } size_t data_gen_id = 1; TDataFile data_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, &mem_layer, file_id, data_gen_id, 20UL, 0U, Medium); } /* Make data file 2 (more of the same) */ { TSuprena arena; TMockMem mem_layer; /* insert data */ { TSuprena suprena; void *state_alloc = alloca(Sabot::State::GetMaxStateSize()); /* insert <[int64_t, string, desc<int64_t>, desc<string>]> */ Insert(mem_layer, ++seq_num, int_str_decint_decstr_idx, TKey(map<TDesc<int64_t>, string>{{TDesc<int64_t>(30L), string("Hello")}, {TDesc<int64_t>(9L), string("This is also a longer string")}}, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(2L), TDesc<string>("short")); Insert(mem_layer, ++seq_num, int_str_decint_decstr_idx, TKey(map<TDesc<int64_t>, string>{{TDesc<int64_t>(30L), string("Hey yo")}, {TDesc<int64_t>(20L), string("Some form of a longer string")}}, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(2L), TDesc<string>("This string should be too long to fit in a core")); Insert(mem_layer, ++seq_num, int_str_decint_decstr_idx, TKey(map<TDesc<int64_t>, string>{{TDesc<int64_t>(30L), string("Hey yo")}, {TDesc<int64_t>(27L), string("This is also a longer string")}}, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(4L), TDesc<string>("This string should be too long to fit in a core")); /* insert <[int64_t, string, int64_t, string]> */ Insert(mem_layer, ++seq_num, int_str_int_str_idx, TKey(set<int64_t>{1, 3, 9}, &suprena, state_alloc), 1L, string("Orly"), 2L, string("short")); } size_t data_gen_id = 2; TDataFile data_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, &mem_layer, file_id, data_gen_id, 20UL, 0U, Medium); } /* Make data file 3 (something different) */ { TSuprena arena; TMockMem mem_layer; /* insert data */ { TSuprena suprena; void *state_alloc = alloca(Sabot::State::GetMaxStateSize()); /* insert <[int64_t, string, desc<int64_t>, desc<string>]> */ Insert(mem_layer, ++seq_num, int_str_decint_decstr_idx, TKey(map<TDesc<int64_t>, string>{{TDesc<int64_t>(30L), string("Hello")}, {TDesc<int64_t>(9L), string("This is also a longer string")}}, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(5L), TDesc<string>("short")); Insert(mem_layer, ++seq_num, int_str_decint_decstr_idx, TKey(map<TDesc<int64_t>, string>{{TDesc<int64_t>(30L), string("Hey yo")}, {TDesc<int64_t>(20L), string("Some form of a longer string")}}, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(5L), TDesc<string>("This string should be too long to fit in a core")); Insert(mem_layer, ++seq_num, int_str_decint_decstr_idx, TKey(map<TDesc<int64_t>, string>{{TDesc<int64_t>(30L), string("Hey yo")}, {TDesc<int64_t>(27L), string("This is also a longer string")}}, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(6L), TDesc<string>("This string should be too long to fit in a core")); /* insert <[int64_t, string, desc<int64_t>, string]> */ Insert(mem_layer, ++seq_num, int_str_decint_str_idx, TKey(set<TDesc<int64_t>>{TDesc<int64_t>(1), TDesc<int64_t>(7), TDesc<int64_t>(20)}, &suprena, state_alloc), 1L, string("Orly"), TDesc<int64_t>(2L), string("short")); } size_t data_gen_id = 3; TDataFile data_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, &mem_layer, file_id, data_gen_id, 20UL, 0U, Medium); } /* merge them */ { TSuprena arena; TMergeDataFile merge_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, file_id, vector<size_t>{1, 2, 3}, file_id, 4UL, 0U, Low, 16384, 20UL, true, false); TReader reader(HERE, mem_engine.GetEngine(), file_id, 4UL); TReader::TArena main_arena(&reader, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), RealTime); TReader::TIndexFile int_str_decint_decstr_idx_file(&reader, int_str_decint_decstr_idx, RealTime); TReader::TArena int_str_decint_decstr_idx_arena(&int_str_decint_decstr_idx_file, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), RealTime); TReader::TIndexFile int_str_int_str_idx_file(&reader, int_str_int_str_idx, RealTime); TReader::TArena int_str_int_str_idx_arena(&int_str_int_str_idx_file, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), RealTime); TReader::TIndexFile int_str_decint_str_idx_file(&reader, int_str_decint_str_idx, RealTime); TReader::TArena int_str_decint_str_idx_arena(&int_str_decint_str_idx_file, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), RealTime); TStream<Orly::Indy::Disk::Util::LogicalBlockSize, Orly::Indy::Disk::Util::LogicalBlockSize, Orly::Indy::Disk::Util::PhysicalBlockSize, Orly::Indy::Disk::Util::PageCheckedBlock, 0UL> in_stream(HERE, Source::PresentWalk, RealTime, &reader, mem_engine.GetEngine()->GetCache<TReader::PhysicalCachePageSize>(), 0); size_t out_offset; /* what came from file 1 */ EXPECT_TRUE(int_str_decint_decstr_idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("short")), &arena, state_alloc), out_offset, in_stream, &int_str_decint_decstr_idx_arena)); EXPECT_TRUE(int_str_decint_decstr_idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), out_offset, in_stream, &int_str_decint_decstr_idx_arena)); EXPECT_TRUE(int_str_int_str_idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), 1L, string("short")), &arena, state_alloc), out_offset, in_stream, &int_str_int_str_idx_arena)); /* what came from file 2 */ EXPECT_TRUE(int_str_decint_decstr_idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(2L), TDesc<string>("short")), &arena, state_alloc), out_offset, in_stream, &int_str_decint_decstr_idx_arena)); EXPECT_TRUE(int_str_decint_decstr_idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(2L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), out_offset, in_stream, &int_str_decint_decstr_idx_arena)); EXPECT_TRUE(int_str_decint_decstr_idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(4L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), out_offset, in_stream, &int_str_decint_decstr_idx_arena)); EXPECT_TRUE(int_str_int_str_idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), 2L, string("short")), &arena, state_alloc), out_offset, in_stream, &int_str_int_str_idx_arena)); /* what came from file 3 */ EXPECT_TRUE(int_str_decint_decstr_idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(5L), TDesc<string>("short")), &arena, state_alloc), out_offset, in_stream, &int_str_decint_decstr_idx_arena)); EXPECT_TRUE(int_str_decint_decstr_idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(5L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), out_offset, in_stream, &int_str_decint_decstr_idx_arena)); EXPECT_TRUE(int_str_decint_decstr_idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(6L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), out_offset, in_stream, &int_str_decint_decstr_idx_arena)); EXPECT_TRUE(int_str_decint_str_idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(2L), string("short")), &arena, state_alloc), out_offset, in_stream, &int_str_decint_str_idx_arena)); /* what doesn't exist */ EXPECT_FALSE(int_str_decint_decstr_idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(6L), TDesc<string>("short")), &arena, state_alloc), out_offset, in_stream, &int_str_decint_decstr_idx_arena)); EXPECT_FALSE(int_str_decint_decstr_idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(7L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), out_offset, in_stream, &int_str_decint_decstr_idx_arena)); EXPECT_FALSE(int_str_decint_decstr_idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(8L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), out_offset, in_stream, &int_str_decint_decstr_idx_arena)); EXPECT_FALSE(int_str_decint_str_idx_file.FindInHash(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(3L), string("short")), &arena, state_alloc), out_offset, in_stream, &int_str_decint_str_idx_arena)); vector<pair<TKey, TKey>> expected_vec; expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(6L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), TKey(map<TDesc<int64_t>, string>{{TDesc<int64_t>(30L), string("Hey yo")}, {TDesc<int64_t>(27L), string("This is also a longer string")}}, &arena, state_alloc)); expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(5L), TDesc<string>("short")), &arena, state_alloc), TKey(map<TDesc<int64_t>, string>{{TDesc<int64_t>(30L), string("Hello")}, {TDesc<int64_t>(9L), string("This is also a longer string")}}, &arena, state_alloc)); expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(5L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), TKey(map<TDesc<int64_t>, string>{{TDesc<int64_t>(30L), string("Hey yo")}, {TDesc<int64_t>(20L), string("Some form of a longer string")}}, &arena, state_alloc)); expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(4L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), TKey(map<TDesc<int64_t>, string>{{TDesc<int64_t>(30L), string("Hey yo")}, {TDesc<int64_t>(27L), string("This is also a longer string")}}, &arena, state_alloc)); expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(2L), TDesc<string>("short")), &arena, state_alloc), TKey(map<TDesc<int64_t>, string>{{TDesc<int64_t>(30L), string("Hello")}, {TDesc<int64_t>(9L), string("This is also a longer string")}}, &arena, state_alloc)); expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(2L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), TKey(map<TDesc<int64_t>, string>{{TDesc<int64_t>(30L), string("Hey yo")}, {TDesc<int64_t>(20L), string("Some form of a longer string")}}, &arena, state_alloc)); expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("short")), &arena, state_alloc), TKey(map<TDesc<int64_t>, string>{{TDesc<int64_t>(30L), string("Hello")}, {TDesc<int64_t>(9L), string("This is also a longer string")}}, &arena, state_alloc)); expected_vec.emplace_back(TKey(make_tuple(1L, string("Orly"), TDesc<int64_t>(1L), TDesc<string>("This string should be too long to fit in a core")), &arena, state_alloc), TKey(map<TDesc<int64_t>, string>{{TDesc<int64_t>(30L), string("Hey yo")}, {TDesc<int64_t>(27L), string("This is also a longer string")}}, &arena, state_alloc)); size_t seen = 0UL; for (TReader::TIndexFile::TKeyCursor cur_key_csr(&int_str_decint_decstr_idx_file); cur_key_csr; ++cur_key_csr, ++seen) { const TReader::TIndexFile::TKeyItem &item = *cur_key_csr; EXPECT_TRUE(cur_key_csr); if (EXPECT_GE(expected_vec.size(), seen + 1)) { EXPECT_EQ(TKey(item.Key, &int_str_decint_decstr_idx_arena), expected_vec[seen].first); EXPECT_EQ(TKey(item.Value, &main_arena), expected_vec[seen].second); } } EXPECT_EQ(expected_vec.size(), seen); } GracefullShutdown(); std::lock_guard<std::mutex> lock(mut); fin = true; cond.notify_one(); }); } FIXTURE(SomeHistory) { TFiberTestRunner runner([](std::mutex &mut, std::condition_variable &cond, bool &fin, Fiber::TRunner::TRunnerCons &) { void *state_alloc = alloca(Sabot::State::GetMaxStateSize()); TScheduler scheduler(TScheduler::TPolicy(10, 10, milliseconds(10))); Sim::TMemEngine mem_engine(&scheduler, 256 /* disk space: 256MB */, 256 /* slow disk space: 256MB */, 16384 /* page cache slots: 64MB */, 1 /* num page lru */, 1024 /* block cache slots: 64MB */, 1 /* num block lru */); Base::TUuid file_id(TUuid::TimeAndMAC); TSuprena arena; TSequenceNumber seq_num = 0U; Base::TUuid int_idx(Base::TUuid::Twister); /* data file 1 */ { TMockMem mem_layer; for (int64_t i = 0; i < 11; i += 2) { mem_layer.Insert(TMockUpdate::NewMockUpdate(TUpdate::TOpByKey{ { TIndexKey(int_idx, TKey(make_tuple(i), &arena, state_alloc)), TKey(i * 10, &arena, state_alloc)}, { TIndexKey(int_idx, TKey(make_tuple(i + 1L), &arena, state_alloc)), TKey((i + 1L) * 10, &arena, state_alloc)} }, TKey(&arena), TKey(Base::TUuid(TUuid::Best), &arena, state_alloc), ++seq_num)); mem_layer.Insert(TMockUpdate::NewMockUpdate(TUpdate::TOpByKey{ { TIndexKey(int_idx, TKey(make_tuple(i), &arena, state_alloc)), TKey(i * 10, &arena, state_alloc)}, { TIndexKey(int_idx, TKey(make_tuple(i + 1L), &arena, state_alloc)), TKey((i + 1L) * 10, &arena, state_alloc)} }, TKey(&arena), TKey(Base::TUuid(TUuid::Best), &arena, state_alloc), ++seq_num)); } TDataFile data_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, &mem_layer, file_id, 1UL, 20UL, 0U, RealTime); } /* data file 2 */ { TMockMem mem_layer; for (int64_t i = 0; i < 11; i += 2) { mem_layer.Insert(TMockUpdate::NewMockUpdate(TUpdate::TOpByKey{ { TIndexKey(int_idx, TKey(make_tuple(i), &arena, state_alloc)), TKey(i * 10, &arena, state_alloc)}, { TIndexKey(int_idx, TKey(make_tuple(i + 1L), &arena, state_alloc)), TKey((i + 1L) * 10, &arena, state_alloc)} }, TKey(&arena), TKey(Base::TUuid(TUuid::Best), &arena, state_alloc), ++seq_num)); mem_layer.Insert(TMockUpdate::NewMockUpdate(TUpdate::TOpByKey{ { TIndexKey(int_idx, TKey(make_tuple(i), &arena, state_alloc)), TKey(i * 10, &arena, state_alloc)}, { TIndexKey(int_idx, TKey(make_tuple(i + 1L), &arena, state_alloc)), TKey((i + 1L) * 10, &arena, state_alloc)} }, TKey(&arena), TKey(Base::TUuid(TUuid::Best), &arena, state_alloc), ++seq_num)); } TDataFile data_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, &mem_layer, file_id, 2UL, 20UL, 0U, RealTime); } /* merge them */ { TMergeDataFile merge_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, file_id, vector<size_t>{1UL, 2UL}, file_id, 3UL, 0U, Low, 16384, 20UL, false, false); } std::lock_guard<std::mutex> lock(mut); fin = true; cond.notify_one(); }); } FIXTURE(JumpGrowingMainArena) { TFiberTestRunner runner([](std::mutex &mut, std::condition_variable &cond, bool &fin, Fiber::TRunner::TRunnerCons &) { stringstream my_str; const string zello_str("zello World"); void *state_alloc = alloca(Sabot::State::GetMaxStateSize()); Base::TUuid file_id(TUuid::TimeAndMAC); Base::TUuid int_idx(Base::TUuid::Twister); const size_t start_amt = 4096 * 16; while (my_str.str().size() < start_amt) { my_str << (rand() % 10); } const std::string add_str = my_str.str(); for (size_t i = start_amt; i < 4096 * 16 * 32; i += start_amt) { my_str << add_str; cout << "Trying i = [" << i << "]" << endl; TScheduler scheduler(TScheduler::TPolicy(10, 10, milliseconds(10))); Sim::TMemEngine mem_engine(&scheduler, 1024 /* disk space: 1GB */, 512 /* slow disk space: 512MB */, 65536 /* page cache slots: 256MB */, 1 /* num page lru */, 2048 /* block cache slots: 128MB */, 1 /* num block lru */); TSuprena arena; TSequenceNumber seq_num = 0U; /* data file 1 */ { TMockMem mem_layer; Insert(mem_layer, ++seq_num, int_idx, TKey(my_str.str(), &arena, state_alloc), 1L); Insert(mem_layer, ++seq_num, int_idx, TKey(zello_str, &arena, state_alloc), 2L); TDataFile data_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, &mem_layer, file_id, 1UL, 20UL, 0U, RealTime); } /* push it through the merger */ { TMergeDataFile merge_file(mem_engine.GetEngine(), TVolume::TDesc::Fast, file_id, vector<size_t>{1UL}, file_id, 3UL, 0U, Low, 16384, 20UL, false, false); } } std::lock_guard<std::mutex> lock(mut); fin = true; cond.notify_one(); }); }
75.511586
364
0.659837
[ "vector" ]
d89f4076469e5b30c25605ed656efa33fee91a37
2,288
cc
C++
tests/test_json.cc
cisco/goFish
cc890b96e341d15b72fd6c95d9ce2ff22011c15e
[ "BSD-2-Clause" ]
10
2019-05-20T23:41:57.000Z
2021-11-08T11:18:07.000Z
tests/test_json.cc
cisco/goFish
cc890b96e341d15b72fd6c95d9ce2ff22011c15e
[ "BSD-2-Clause" ]
null
null
null
tests/test_json.cc
cisco/goFish
cc890b96e341d15b72fd6c95d9ce2ff22011c15e
[ "BSD-2-Clause" ]
3
2020-10-02T14:07:37.000Z
2021-03-16T12:11:59.000Z
#include "test_json.h" void JSONTest::setUp() { _json = std::make_unique<JSON>(""); } void JSONTest::TestConstructors() { { std::string name = ""; auto j = new JSON(name); _json.reset(j); CPPUNIT_ASSERT_EQUAL(_json->GetName(), name); CPPUNIT_ASSERT_EQUAL(_json->GetJSON(), std::string("{}")); } { std::string name = "json"; auto j = new JSON(name); _json.reset(j); CPPUNIT_ASSERT_EQUAL(_json->GetName(), name); CPPUNIT_ASSERT_EQUAL(_json->GetJSON(), "{\"" + name + "\":{}}"); } { std::string name = "json"; std::map<std::string, std::string> val; val.insert(std::make_pair("sub1", "val1")); val.insert(std::make_pair("sub2", "val2")); val.insert(std::make_pair("sub3", "val3")); auto j = new JSON(name, val); _json.reset(j); CPPUNIT_ASSERT_EQUAL(_json->GetName(), name); CPPUNIT_ASSERT_EQUAL(_json->GetJSON(), "{\"" + name + "\":{\"sub1\":\"val1\",\"sub2\":\"val2\",\"sub3\":\"val3\"}}"); } } void JSONTest::TestAddKeyValue() { std::string name = "json"; auto j = new JSON(name); _json.reset(j); _json->AddKeyValue("sub1", "val1"); _json->BuildJSONObject(); CPPUNIT_ASSERT_EQUAL(_json->GetJSON(), "{\"" + name + "\":{\"sub1\":\"val1\"}}"); _json->BuildJSONObjectArray(); CPPUNIT_ASSERT_EQUAL(_json->GetJSON(), "{\"" + name + "\":[{\"sub1\":\"val1\"}]}"); } void JSONTest::TestAddObject() { std::string name = "json"; auto j = new JSON(name); _json.reset(j); std::map<std::string, std::string> val; val.insert(std::make_pair("sub1", "val1")); auto j2 = new JSON("json2", val); _json->AddObject(*j2); // Test build normal object. _json->BuildJSONObject(); CPPUNIT_ASSERT_EQUAL(_json->GetJSON(), "{\"" + name + "\":{\"json2\":{\"sub1\":\"val1\"}}}"); // Test build array of objects. _json->BuildJSONObjectArray(); CPPUNIT_ASSERT_EQUAL(_json->GetJSON(), "{\"" + name + "\":[{\"json2\":{\"sub1\":\"val1\"}}]}"); // Test build array of key value pairs. _json.reset(j2); _json->BuildJSONObjectArray(); CPPUNIT_ASSERT_EQUAL(_json->GetJSON(), std::string("{\"json2\":[{\"sub1\":\"val1\"}]}")); }
27.902439
125
0.555944
[ "object" ]
d8a56112b4fc23a2e94d533d20b6c07939560d7c
1,452
cpp
C++
tests/test_linalg_transposed.cpp
stigrs/scilib
c49f1f882bf2031a4de537e0f5701b2648af181f
[ "MIT" ]
null
null
null
tests/test_linalg_transposed.cpp
stigrs/scilib
c49f1f882bf2031a4de537e0f5701b2648af181f
[ "MIT" ]
null
null
null
tests/test_linalg_transposed.cpp
stigrs/scilib
c49f1f882bf2031a4de537e0f5701b2648af181f
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Stig Rune Sellevag // // This file is distributed under the MIT License. See the accompanying file // LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms // and conditions. #include <scilib/mdarray.h> #include <scilib/linalg.h> #include <gtest/gtest.h> TEST(TestMatrix, TestTransposed) { // clang-format off std::vector<int> data = { 1, 2, 3, 4, 5, 6, 7, 8 }; std::vector<int> t_data = { 1, 5, 2, 6, 3, 7, 4, 8 }; // clang-format on Sci::Matrix<int> a(data, 2, 4); Sci::Matrix<int> ans(t_data, 4, 2); auto at = Sci::Linalg::transposed(a); for (std::size_t i = 0; i < at.extent(0); ++i) { for (std::size_t j = 0; j < at.extent(1); ++j) { EXPECT_EQ(at(i, j), ans(i, j)); } } } TEST(TestMatrix, TestTransposedColMajor) { // clang-format off std::vector<int> data = { 1, 2, 3, 4, 5, 6, 7, 8 }; std::vector<int> t_data = { 1, 5, 2, 6, 3, 7, 4, 8 }; // clang-format on Sci::Matrix<int, stdex::layout_left> a(data, 4, 2); Sci::Matrix<int, stdex::layout_left> ans(t_data, 2, 4); auto at = Sci::Linalg::transposed(a); for (std::size_t j = 0; j < at.extent(1); ++j) { for (std::size_t i = 0; i < at.extent(0); ++i) { EXPECT_EQ(at(i, j), ans(i, j)); } } }
24.2
78
0.513774
[ "vector" ]
d8a9852b6cca6a8e6cee7a10070b9e849d3d4613
4,089
cc
C++
src/main.cc
DanShaders/cpp-protoc-initializers
b262c68df15cce43ba9ddf0726311f3d17548de7
[ "MIT" ]
null
null
null
src/main.cc
DanShaders/cpp-protoc-initializers
b262c68df15cce43ba9ddf0726311f3d17548de7
[ "MIT" ]
null
null
null
src/main.cc
DanShaders/cpp-protoc-initializers
b262c68df15cce43ba9ddf0726311f3d17548de7
[ "MIT" ]
null
null
null
#include <google/protobuf/compiler/code_generator.h> #include <google/protobuf/compiler/cpp/cpp_generator.h> #include <google/protobuf/compiler/plugin.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/io/printer.h> #include <vector> using namespace google::protobuf; class Generator : public compiler::CodeGenerator { private: template <typename T> string convert_scoped(const T *message) const { if (message->containing_type()) { return convert_scoped(message->containing_type()) + "_" + message->name(); } else { string s = ""; for (char c : message->full_name()) { if (c == '.') { s += "::"; } else { s += c; } } return s; } } template <typename T> string convert_unscoped(const T *message) const { std::vector<string> names; while (message) { names.push_back(message->name()); message = message->containing_type(); } reverse(names.begin(), names.end()); string s; for (auto c : names) { s += c + "_"; } s.pop_back(); return s; } bool GenerateFor(const Descriptor *message, const FileDescriptor *file, compiler::GeneratorContext *context) const { auto class_scope_inserter = context->OpenForInsert( compiler::StripProto(file->name()) + ".pb.h", "class_scope:" + message->full_name()); auto printer = io::Printer(class_scope_inserter, '$'); printer.Print("const static std::string TYPE_NAME;\n"); printer.Print("struct initializable_type {\n"); printer.Indent(); for (int i = 0; i < message->field_count(); ++i) { auto field = message->field(i); auto etype = field->cpp_type(); string type = "::PROTOBUF_NAMESPACE_ID::" + std::string(field->cpp_type_name()); if (etype == FieldDescriptor::CPPTYPE_ENUM) { type = convert_scoped(field->enum_type()); } else if (etype == FieldDescriptor::CPPTYPE_MESSAGE) { type = convert_scoped(field->message_type()); } else if (etype == FieldDescriptor::CPPTYPE_BOOL) { type = "bool"; } if (field->is_repeated()) { type = "std::vector<" + type + ">"; } printer.Print("$type$ $name$;\n", "type", type.c_str(), "name", field->name().c_str()); } printer.Outdent(); printer.Print("};\n\n$constructor$(const initializable_type &t) : $constructor$() {\n", "constructor", convert_unscoped(message)); printer.Indent(); for (int i = 0; i < message->field_count(); ++i) { auto field = message->field(i); auto lname = field->lowercase_name().c_str(), name = field->name().c_str(); if (field->is_repeated()) { printer.Print("for (std::size_t i = 0; i < t.$name$.size(); ++i) {\n", "name", name); printer.Indent(); printer.Print("*add_$lname$() = t.$name$[i];", "lname", lname, "name", name); printer.Outdent(); printer.Print("}\n"); } else { printer.Print("set_$lname$(t.$name$);\n", "lname", lname, "name", name); } } printer.Outdent(); printer.Print("}\n"); for (int i = 0; i < message->nested_type_count(); ++i) { GenerateFor(message->nested_type(i), file, context); } { auto namespace_scope_inserter = context->OpenForInsert( compiler::StripProto(file->name()) + ".pb.h", "namespace_scope"); auto p = io::Printer(namespace_scope_inserter, '$'); p.Print("inline const std::string $1$::TYPE_NAME = \"$2$\";\n", "1", convert_scoped(message), "2", message->full_name()); } { auto includes_inserter = context->OpenForInsert(compiler::StripProto(file->name()) + ".pb.h", "includes"); io::Printer(includes_inserter, '$').Print("#include <vector>\n"); } return true; } compiler::cpp::CppGenerator cppGenerator; public: bool Generate(const FileDescriptor *file, const string &parameter, compiler::GeneratorContext *context, string *error) const { if (!cppGenerator.Generate(file, parameter, context, error)) { return false; } for (int i = 0; i < file->message_type_count(); ++i) { GenerateFor(file->message_type(i), file, context); } return true; } }; int main(int argc, char **argv) { Generator generator; return compiler::PluginMain(argc, argv, &generator); }
31.697674
90
0.642944
[ "vector" ]
d8b850433842ea64cdf7d7a1dda025a04bd91005
4,914
cpp
C++
src/geometry/sphere.cpp
Twinklebear/tray
eeb6dc930a3f81bb2abd74a41a4fb409a0e0865b
[ "MIT" ]
61
2015-01-01T10:58:21.000Z
2022-01-05T14:22:15.000Z
src/geometry/sphere.cpp
Twinklebear/tray
eeb6dc930a3f81bb2abd74a41a4fb409a0e0865b
[ "MIT" ]
null
null
null
src/geometry/sphere.cpp
Twinklebear/tray
eeb6dc930a3f81bb2abd74a41a4fb409a0e0865b
[ "MIT" ]
3
2016-04-11T19:07:47.000Z
2018-05-31T12:40:50.000Z
#include "monte_carlo/util.h" #include "linalg/util.h" #include "linalg/ray.h" #include "linalg/vector.h" #include "geometry/sphere.h" Sphere::Sphere(float radius) : radius(radius){} bool Sphere::intersect(Ray &ray, DifferentialGeometry &diff_geom) const { //Compute quadratic sphere coefficients Vector ray_orig{ray.o}; float a = ray.d.length_sqr(); float b = 2 * ray.d.dot(ray_orig); float c = ray_orig.length_sqr() - radius * radius; //Solve quadratic equation for t values //If no solutions exist the ray doesn't intersect the sphere float t[2]; if (!solve_quadratic(a, b, c, t[0], t[1])){ return false; } //Early out, if t[0] (min) is > max or t[1] (max) is < min then both //our hits are outside of the region we're testing if (t[0] > ray.max_t || t[1] < ray.min_t){ return false; } //Find the t value that is within the region we care about, or return if neither is float t_hit = t[0]; if (t_hit < ray.min_t){ t_hit = t[1]; if (t_hit > ray.max_t){ return false; } } ray.max_t = t_hit; diff_geom.point = ray(t_hit); //For a unit sphere the normal is the same as the point hit diff_geom.normal = Normal{diff_geom.point}; diff_geom.geom_normal = diff_geom.normal; if (ray.d.dot(diff_geom.normal) < 0){ diff_geom.hit_side = HITSIDE::FRONT; } else { diff_geom.hit_side = HITSIDE::BACK; } //Compute parameterization of surface and various derivatives for texturing //Sphere is parameterized by phi and theta coords float phi = std::atan2(diff_geom.point.x, diff_geom.point.y); if (phi < 0){ phi += TAU; } float theta = std::acos(clamp(diff_geom.point.z / radius, -1.f, 1.f)); diff_geom.u = phi / TAU; diff_geom.v = theta / PI; //Compute derivatives for point vs. parameterization, using trig shortcuts to //skip cos/sin calls float inv_z = 1 / std::sqrt(diff_geom.point.x * diff_geom.point.x + diff_geom.point.y * diff_geom.point.y); float cos_phi = diff_geom.point.x * inv_z; float sin_phi = diff_geom.point.y * inv_z; diff_geom.dp_du = Vector{-TAU * diff_geom.point.y, TAU * diff_geom.point.x, 0}; diff_geom.dp_dv = PI * Vector{diff_geom.point.z * cos_phi, diff_geom.point.z * sin_phi, -radius * std::sin(theta)}; //Compute derivatives of normals using Weingarten eqns Vector ddp_duu = -TAU * TAU * Vector{diff_geom.point.x, diff_geom.point.y, 0}; Vector ddp_duv = PI * TAU * diff_geom.point.z * Vector{-sin_phi, cos_phi, 0}; Vector ddp_dvv = -PI * PI * Vector{diff_geom.point.x, diff_geom.point.y, diff_geom.point.z}; float E = diff_geom.dp_du.dot(diff_geom.dp_du); float F = diff_geom.dp_du.dot(diff_geom.dp_dv); float G = diff_geom.dp_dv.dot(diff_geom.dp_dv); float e = diff_geom.normal.dot(ddp_duu); float f = diff_geom.normal.dot(ddp_duv); float g = diff_geom.normal.dot(ddp_dvv); float divisor = 1 / (E * G - F * F); diff_geom.dn_du = Normal{(f * F - e * G) * divisor * diff_geom.dp_du + (e * F - f * E) * divisor * diff_geom.dp_dv}; diff_geom.dn_dv = Normal{(g * F - f * G) * divisor * diff_geom.dp_du + (f * F - g * E) * divisor * diff_geom.dp_dv}; diff_geom.geom = this; return true; } BBox Sphere::bound() const { return BBox{Point{-radius, -radius, -radius}, Point{radius, radius, radius}}; } void Sphere::refine(std::vector<Geometry*> &prims){ prims.push_back(this); } float Sphere::surface_area() const { return 2 * TAU * radius; } Point Sphere::sample(const GeomSample &gs, Normal &normal) const { Point p = Point{0, 0, 0} + radius * uniform_sample_sphere(gs.u); normal = Normal{p.x, p.y, p.z}.normalized(); return p; } Point Sphere::sample(const Point &p, const GeomSample &gs, Normal &normal) const { //Compute coordinate system for sampling the sphere where z is the vector from the center to the point Vector w_z = Vector{-p}.normalized(); Vector w_x, w_y; coordinate_system(w_z, w_x, w_y); //If we're inside the sphere we can just sample it uniformly if (p.distance_sqr(Point{0, 0, 0}) - radius * radius < 1e-4){ return sample(gs, normal); } //Compute angle of cone that we see of the sphere float cos_theta = std::sqrt(std::max(0.f, 1 - radius * radius / p.distance_sqr(Point{0, 0, 0}))); DifferentialGeometry dg; Ray ray{p, uniform_sample_cone(gs.u, cos_theta, w_x, w_y, w_z), 0.001}; //We might not hit the sphere due to some numerical errors, so make sure it does hit if (!intersect(ray, dg)){ ray.max_t = ray.d.normalized().dot(Point{0, 0, 0} - p); } Point ps = ray(ray.max_t); normal = Normal{ps}.normalized(); return ps; } float Sphere::pdf(const Point &p, const Vector &w_i) const { //If we're in the sphere compute the weight inside but defined over the solid angle if (p.distance_sqr(Point{0, 0, 0}) - radius * radius < 1e-4){ return Geometry::pdf(p, w_i); } float cos_theta = std::sqrt(std::max(0.f, 1 - radius * radius / p.distance_sqr(Point{0, 0, 0}))); return uniform_cone_pdf(cos_theta); } bool Sphere::attach_light(const Transform&){ return true; }
37.227273
103
0.692308
[ "geometry", "vector", "transform", "solid" ]
d8c5d980e262c3b278cf84be4273628a27cbbb03
1,596
cpp
C++
OverlordEngine/Components/ColliderComponent.cpp
Zakatos/Rift-Traveller
cbce326e4c508f9342a4fa9904bfad2a9fcabb92
[ "MIT" ]
null
null
null
OverlordEngine/Components/ColliderComponent.cpp
Zakatos/Rift-Traveller
cbce326e4c508f9342a4fa9904bfad2a9fcabb92
[ "MIT" ]
null
null
null
OverlordEngine/Components/ColliderComponent.cpp
Zakatos/Rift-Traveller
cbce326e4c508f9342a4fa9904bfad2a9fcabb92
[ "MIT" ]
null
null
null
//Precompiled Header [ALWAYS ON TOP IN CPP] #include "stdafx.h" #include "ColliderComponent.h" #include "RigidBodyComponent.h" #include "../Base/GeneralStructs.h" #include "../Diagnostics/Logger.h" #include "../Scenegraph/GameObject.h" ColliderComponent::ColliderComponent(std::shared_ptr<PxGeometry> & geometry, const PxMaterial& material, const PxTransform& localPose) : m_Geometry(geometry), m_Material(material), m_LocalPose(localPose), m_pShape(nullptr), m_isTrigger(false) { } ColliderComponent::~ColliderComponent(void) { } void ColliderComponent::Initialize(const GameContext& gameContext) { UNREFERENCED_PARAMETER(gameContext); auto rigidBody = GetGameObject()->GetComponent<RigidBodyComponent>(); if (rigidBody == nullptr) { Logger::LogError(L"[ColliderComponent] Cannot add a Collider to an object that does not have a rigid body"); return; } rigidBody->AddCollider(this); } void ColliderComponent::Update(const GameContext& gameContext) { UNREFERENCED_PARAMETER(gameContext); } void ColliderComponent::Draw(const GameContext& gameContext) { UNREFERENCED_PARAMETER(gameContext); } void ColliderComponent::EnableTrigger(bool isTrigger) { m_isTrigger = isTrigger; if(m_pShape != nullptr) { m_pShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, !isTrigger); m_pShape->setFlag(PxShapeFlag::eTRIGGER_SHAPE, isTrigger); } } void ColliderComponent::SetShape(PxShape* shape) { m_pShape = shape; if(m_isTrigger) { m_pShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, !m_isTrigger); m_pShape->setFlag(PxShapeFlag::eTRIGGER_SHAPE, m_isTrigger); } }
23.130435
134
0.766917
[ "geometry", "object", "shape" ]
d8ccb19da5d9fbd8cc64728ce98c5d6f6b635fe1
3,618
cpp
C++
aws-cpp-sdk-monitoring/source/model/GetInsightRuleReportResult.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-monitoring/source/model/GetInsightRuleReportResult.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-monitoring/source/model/GetInsightRuleReportResult.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/monitoring/model/GetInsightRuleReportResult.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/logging/LogMacros.h> #include <utility> using namespace Aws::CloudWatch::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils::Logging; using namespace Aws::Utils; using namespace Aws; GetInsightRuleReportResult::GetInsightRuleReportResult() : m_aggregateValue(0.0), m_approximateUniqueCount(0) { } GetInsightRuleReportResult::GetInsightRuleReportResult(const Aws::AmazonWebServiceResult<XmlDocument>& result) : m_aggregateValue(0.0), m_approximateUniqueCount(0) { *this = result; } GetInsightRuleReportResult& GetInsightRuleReportResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result) { const XmlDocument& xmlDocument = result.GetPayload(); XmlNode rootNode = xmlDocument.GetRootElement(); XmlNode resultNode = rootNode; if (!rootNode.IsNull() && (rootNode.GetName() != "GetInsightRuleReportResult")) { resultNode = rootNode.FirstChild("GetInsightRuleReportResult"); } if(!resultNode.IsNull()) { XmlNode keyLabelsNode = resultNode.FirstChild("KeyLabels"); if(!keyLabelsNode.IsNull()) { XmlNode keyLabelsMember = keyLabelsNode.FirstChild("member"); while(!keyLabelsMember.IsNull()) { m_keyLabels.push_back(keyLabelsMember.GetText()); keyLabelsMember = keyLabelsMember.NextNode("member"); } } XmlNode aggregationStatisticNode = resultNode.FirstChild("AggregationStatistic"); if(!aggregationStatisticNode.IsNull()) { m_aggregationStatistic = Aws::Utils::Xml::DecodeEscapedXmlText(aggregationStatisticNode.GetText()); } XmlNode aggregateValueNode = resultNode.FirstChild("AggregateValue"); if(!aggregateValueNode.IsNull()) { m_aggregateValue = StringUtils::ConvertToDouble(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(aggregateValueNode.GetText()).c_str()).c_str()); } XmlNode approximateUniqueCountNode = resultNode.FirstChild("ApproximateUniqueCount"); if(!approximateUniqueCountNode.IsNull()) { m_approximateUniqueCount = StringUtils::ConvertToInt64(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(approximateUniqueCountNode.GetText()).c_str()).c_str()); } XmlNode contributorsNode = resultNode.FirstChild("Contributors"); if(!contributorsNode.IsNull()) { XmlNode contributorsMember = contributorsNode.FirstChild("member"); while(!contributorsMember.IsNull()) { m_contributors.push_back(contributorsMember); contributorsMember = contributorsMember.NextNode("member"); } } XmlNode metricDatapointsNode = resultNode.FirstChild("MetricDatapoints"); if(!metricDatapointsNode.IsNull()) { XmlNode metricDatapointsMember = metricDatapointsNode.FirstChild("member"); while(!metricDatapointsMember.IsNull()) { m_metricDatapoints.push_back(metricDatapointsMember); metricDatapointsMember = metricDatapointsMember.NextNode("member"); } } } if (!rootNode.IsNull()) { XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); m_responseMetadata = responseMetadataNode; AWS_LOGSTREAM_DEBUG("Aws::CloudWatch::Model::GetInsightRuleReportResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() ); } return *this; }
35.470588
173
0.736042
[ "model" ]
d8d2b0a90488da973e27625fcca72ef001e987b7
4,632
hh
C++
component/oai-ausf/src/common/unicode/normalizer.hh
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-ausf/src/common/unicode/normalizer.hh
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-ausf/src/common/unicode/normalizer.hh
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
#ifndef UNF_NORMALIZER_HH #define UNF_NORMALIZER_HH #include <vector> #include <string> #include <algorithm> #include <cstring> #include "searcher.hh" #include "char_stream.hh" #include "table.hh" #include "util.hh" namespace UNF { class Normalizer { public: enum Form { FORM_NFD, FORM_NFC, FORM_NFKD, FORM_NFKC }; public: Normalizer() : nf_d( TABLE::NODES, TABLE::CANONICAL_DECOM_ROOT, (const char*) TABLE::STRINGS), nf_kd( TABLE::NODES, TABLE::COMPATIBILITY_DECOM_ROOT, (const char*) TABLE::STRINGS), nf_c( TABLE::NODES, TABLE::CANONICAL_COM_ROOT, (const char*) TABLE::STRINGS), nf_c_qc(TABLE::NODES, TABLE::NFC_ILLEGAL_ROOT), nf_kc_qc(TABLE::NODES, TABLE::NFKC_ILLEGAL_ROOT), ccc(TABLE::NODES, TABLE::CANONICAL_CLASS_ROOT) {} const char* normalize(const char* src, Form form) { switch (form) { case FORM_NFD: return nfd(src); case FORM_NFC: return nfc(src); case FORM_NFKD: return nfkd(src); case FORM_NFKC: return nfkc(src); default: return src; } } const char* nfd(const char* src) { return decompose(src, nf_d); } const char* nfkd(const char* src) { return decompose(src, nf_kd); } const char* nfc(const char* src) { return compose(src, nf_c_qc, nf_d); } const char* nfkc(const char* src) { return compose(src, nf_kc_qc, nf_kd); } private: const char* decompose(const char* src, const Trie::NormalizationForm& nf) { const char* beg = next_invalid_char(src, nf); if (*beg == '\0') return src; buffer.assign(src, beg); do { const char* end = next_valid_starter(beg, nf); decompose_one(beg, end, nf, buffer); beg = next_invalid_char(end, nf); buffer.append(end, beg); } while (*beg != '\0'); return buffer.c_str(); } void decompose_one( const char* beg, const char* end, const Trie::NormalizationForm& nf, std::string& buf) { unsigned last = buf.size(); nf.decompose(Trie::RangeCharStream(beg, end), buf); char* bufbeg = const_cast<char*>(buf.data()); canonical_combining_class_ordering(bufbeg + last, bufbeg + buf.size()); } const char* compose( const char* src, const Trie::NormalizationForm& nf, const Trie::NormalizationForm& nf_decomp) { const char* beg = next_invalid_char(src, nf); if (*beg == '\0') return src; buffer.assign(src, beg); while (*beg != '\0') { const char* end = next_valid_starter(beg, nf); buffer2.clear(); decompose_one(beg, end, nf_decomp, buffer2); end = compose_one(buffer2.c_str(), end, buffer); beg = next_invalid_char(end, nf); buffer.append(end, beg); } return buffer.c_str(); } const char* compose_one( const char* starter, const char* rest_starter, std::string& buf) { Trie::CharStreamForComposition in( starter, rest_starter, canonical_classes, buffer3); while (in.within_first()) nf_c.compose(in, buf); return in.cur(); } void canonical_combining_class_ordering(char* beg, const char* end) { canonical_classes.assign(end - beg + 1, 0); // +1 is for sentinel value ccc.sort(beg, canonical_classes); } const char* next_invalid_char( const char* src, const Trie::NormalizationForm& nf) const { int last_canonical_class = 0; const char* cur = Util::nearest_utf8_char_start_point(src); const char* starter = cur; for (; *cur != '\0'; cur = Util::nearest_utf8_char_start_point(cur + 1)) { int canonical_class = ccc.get_class(cur); if (last_canonical_class > canonical_class && canonical_class != 0) return starter; if (nf.quick_check(cur) == false) return starter; if (canonical_class == 0) starter = cur; last_canonical_class = canonical_class; } return cur; } const char* next_valid_starter( const char* src, const Trie::NormalizationForm& nf) const { const char* cur = Util::nearest_utf8_char_start_point(src + 1); while (ccc.get_class(cur) != 0 || nf.quick_check(cur) == false) cur = Util::nearest_utf8_char_start_point(cur + 1); return cur; } private: const Trie::NormalizationForm nf_d; const Trie::NormalizationForm nf_kd; const Trie::NormalizationForm nf_c; const Trie::NormalizationForm nf_c_qc; const Trie::NormalizationForm nf_kc_qc; const Trie::CanonicalCombiningClass ccc; std::string buffer; std::string buffer2; std::string buffer3; std::vector<unsigned char> canonical_classes; }; } // namespace UNF #endif
30.27451
78
0.64918
[ "vector" ]
d8d3cfdac364cb7dc6c923f6393ae3b50104476b
2,551
cpp
C++
peer/listener_thread.cpp
jhengyilin/chatNT
7287a90bf2270d12584157285dd160b2e55dd0b3
[ "MIT" ]
6
2020-12-17T09:11:30.000Z
2021-04-16T08:29:33.000Z
peer/listener_thread.cpp
jhengyilin/chatNT
7287a90bf2270d12584157285dd160b2e55dd0b3
[ "MIT" ]
null
null
null
peer/listener_thread.cpp
jhengyilin/chatNT
7287a90bf2270d12584157285dd160b2e55dd0b3
[ "MIT" ]
2
2020-12-29T07:44:45.000Z
2020-12-29T09:37:01.000Z
#include "listener_thread.h" #include "logger.h" #include <cstring> #include <thread> #include <unistd.h> #define LISTENER_NUM 10 #ifdef __linux__ #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #elif _WIN32 #include <WinSock2.h> typedef int socklen_t; #endif using namespace std; //constructor ListenerThread::ListenerThread(int port, SocketControl *_mainsocketControl, SslHandler *_sslHandler, std::vector<User> *_userList, std::vector<Message> *_messages) { //socket initialization mainSocketControl = _mainsocketControl; sslHandler = _sslHandler; userList = _userList; messages = _messages; listenerSocketDescriptor = socket(AF_INET, SOCK_STREAM, 0); if (listenerSocketDescriptor == -1) { error("Listener Socket Creation Failed\n"); exit(-1); } else { info("Listener Established\n"); } //connection initialization struct sockaddr_in listenerInfo; memset(&listenerInfo, 0, sizeof(listenerInfo)); listenerInfo.sin_family = PF_INET; listenerInfo.sin_addr.s_addr = INADDR_ANY; listenerInfo.sin_port = htons(port); int err = bind(listenerSocketDescriptor, (struct sockaddr *)&listenerInfo, sizeof(listenerInfo)); if (err == -1) { error("Bind port failed, please try again\n"); exit(-1); } else { info("Binded on port " + to_string(port) + "\n"); } } //starts listening for incoming connections void ListenerThread::startListen() { listen(listenerSocketDescriptor, LISTENER_NUM); while (true) { //accepts incoming connection struct sockaddr_in incomingClientInfo; socklen_t infoSize = sizeof(incomingClientInfo); int incomingClientSocketDescriptor = accept(listenerSocketDescriptor, (struct sockaddr *)&incomingClientInfo, &infoSize); if (incomingClientSocketDescriptor <= 0) { break; } info("Incoming request assigned with descriptor " + to_string(incomingClientSocketDescriptor) + "\n"); info("(originated from ip: " + string(inet_ntoa(incomingClientInfo.sin_addr)) + ", port: " + to_string(ntohs(incomingClientInfo.sin_port)) + ")\n"); //creates and assigns a new thread to handle the incoming connection HandlerThread *newThread = new HandlerThread(incomingClientSocketDescriptor, mainSocketControl, sslHandler, userList, messages); thread sth(&HandlerThread::handler, newThread); sth.detach(); } delete this; } //destructor ListenerThread::~ListenerThread() { #ifdef __linux__ close(listenerSocketDescriptor); #elif _WIN32 closesocket(listenerSocketDescriptor); #endif }
27.728261
163
0.732262
[ "vector" ]
d8e26b538ed11fca2600dbd03dae48912160165e
5,498
cpp
C++
auxiliary/renderer/OpenGL/GLSimpleMeshRenderer.cpp
billhj/Etoile2015
c9311fc2a901cd60b2aeead5462ca8d6f7c5aa3a
[ "Apache-2.0" ]
null
null
null
auxiliary/renderer/OpenGL/GLSimpleMeshRenderer.cpp
billhj/Etoile2015
c9311fc2a901cd60b2aeead5462ca8d6f7c5aa3a
[ "Apache-2.0" ]
null
null
null
auxiliary/renderer/OpenGL/GLSimpleMeshRenderer.cpp
billhj/Etoile2015
c9311fc2a901cd60b2aeead5462ca8d6f7c5aa3a
[ "Apache-2.0" ]
null
null
null
/** * Copyright(C) 2009-2012 * @author Jing HUANG * @file GLSimpleMeshRenderer.cpp * @brief * @date 1/2/2011 */ #include "GLSimpleMeshRenderer.h" #include "glhead.h" #include "geometry/TextureManager.h" #include "geometry/Texture.h" #include "geometry/ModelTransform.h" #include "geometry/Entity.h" namespace Etoile { void useTransform(ModelTransform* t) { if(t) { Matrix4f modelM = t->getGLModelMatrix(); glPushMatrix(); glMultMatrixf(&modelM[0][0]); } } void unUseTransform(ModelTransform* t) { if(t) { glPopMatrix(); } } GLSimpleMeshRenderer::GLSimpleMeshRenderer(const std::string& name) : ObjectRenderer(name), p_mesh(NULL) { #ifdef USING_GLEW p_vertexVBO = NULL; p_normalVBO = NULL; p_texcoordVBO = NULL; p_indexVBO = NULL; #endif } GLSimpleMeshRenderer::~GLSimpleMeshRenderer() { #ifdef USING_GLEW if(NULL != p_vertexVBO) { delete p_vertexVBO; } if(NULL != p_normalVBO) { delete p_normalVBO; } if(NULL != p_texcoordVBO) { delete p_texcoordVBO; } if(NULL != p_indexVBO) { delete p_indexVBO; } #endif } void GLSimpleMeshRenderer::draw() { if(p_mesh == NULL) return; //Matrix4f modelM; ModelTransform* t = this->getEntity()->getTransformation(); useTransform(t); drawSimpleMesh(p_mesh); unUseTransform(t); } void useMaterial(SimpleMesh::Material& mat) { glMaterialfv(GL_FRONT, GL_AMBIENT, &mat.m_ambient[0]); glMaterialfv(GL_FRONT, GL_DIFFUSE, &mat.m_diffuse[0]); glMaterialfv(GL_FRONT, GL_SPECULAR, &mat.m_specular[0]); glMateriali(GL_FRONT, GL_SHININESS, mat.m_shininess); //make sure need to use applying glEnable(GL_POLYGON_STIPPLE); glEnable(GL_POLYGON_STIPPLE); glPolygonStipple(__stippleMask[int(mat.m_transparency * __screenDoorMaskRange)]); } void GLSimpleMeshRenderer::setSimpleMesh(SimpleMesh* mesh) { p_mesh = mesh; #ifdef USING_GLEW GLenum usage = GL_STATIC_DRAW_ARB; p_normalVBO = new VBO(mesh->m_normals.size() * 3, &(mesh->m_normals[0][0]), usage); p_texcoordVBO = new VBO(mesh->m_texcoords.size() * 3, &(mesh->m_texcoords[0][0]), usage); p_vertexVBO = new VBO(mesh->m_positions.size() * 3, &(mesh->m_positions[0][0]), usage); p_indexVBO = new IndexVBO(mesh->m_vertexIndices.size(), &(mesh->m_vertexIndices[0]), usage); #endif } #ifdef USING_GLEW void GLSimpleMeshRenderer::setSimpleMesh(SimpleMesh* mesh, GLenum usage) { p_mesh = mesh; p_normalVBO = new VBO(mesh->m_normals.size() * 3, &(mesh->m_normals[0][0]), usage); p_texcoordVBO = new VBO(mesh->m_texcoords.size() * 3, &(mesh->m_texcoords[0][0]), usage); p_vertexVBO = new VBO(mesh->m_positions.size() * 3, &(mesh->m_positions[0][0]), usage); p_indexVBO = new IndexVBO(mesh->m_vertexIndices.size(), &(mesh->m_vertexIndices[0]), usage); } void GLSimpleMeshRenderer::drawSimpleMesh(SimpleMesh* mesh) { for(unsigned int i = 0; i < mesh->m_groups.size(); ++i) { SimpleMesh::Group& group = mesh->m_groups[i]; SimpleMesh::Material& mat = mesh->m_materials[group.m_materialIndex]; useMaterial(mat); int index = mat.m_indicesInRessouce[TextureMaterial::DIFFUSE_MAP]; if(index >= 0) { TextureManager::getInstance()->get(index)->use(); } glBegin(GL_TRIANGLES); for(unsigned int j = 0; j < group.m_faceIndices.size(); ++j) { SimpleMesh::Face& face = mesh->m_faces[j]; for(unsigned int k = 0; k < face.m_verticesInfo.size(); ++k) { SimpleMesh::Vertex& v = face.m_verticesInfo[k]; glTexCoord3fv(&mesh->m_texcoords[v.m_texcoordIndex][0]); glNormal3fv(&mesh->m_normals[v.m_normalIndex][0]); glVertex3fv(&mesh->m_positions[v.m_posIndex][0]); } } glEnd(); if(index >= 0) { TextureManager::getInstance()->get(index)->unUse(); } } /*for(unsigned int i = 0; i < mesh->m_groups.size(); ++i) { SimpleMesh::Group& group = mesh->m_groups[i]; SimpleMesh::Material& mat = mesh->m_materials[group.m_materialIndex]; useMaterial(mat); p_texcoordVBO->use(); glTexCoordPointer(3, GL_FLOAT, 0, 0); p_normalVBO->use(); glNormalPointer(GL_FLOAT, 0, 0); p_vertexVBO->use(); glVertexPointer(3, GL_FLOAT, 0, 0); printOpenGLError(); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); printOpenGLError(); p_indexVBO->use(); glDrawElements( GL_TRIANGLES, group.m_count_vertexIndices, GL_UNSIGNED_INT, (GLvoid*)(group.m_offset_vertexIndices)); p_indexVBO->unUse(); printOpenGLError(); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); p_texcoordVBO->unUse(); p_normalVBO->unUse(); p_vertexVBO->unUse(); printOpenGLError(); }*/ } #else void GLSimpleMeshRenderer::drawSimpleMesh(SimpleMesh* mesh) { for(unsigned int i = 0; i < mesh->m_groups.size(); ++i) { SimpleMesh::Group& group = mesh->m_groups[i]; SimpleMesh::Material& mat = mesh->m_materials[group.m_materialIndex]; useMaterial(mat); glBegin(GL_TRIANGLES); for(unsigned int j = 0; j < group.m_faceIndices.size(); ++j) { SimpleMesh::Face& face = mesh->m_faces[j]; for(unsigned int k = 0; k < face.m_verticesInfo.size(); ++k) { SimpleMesh::Vertex& v = face.m_verticesInfo[k]; glTexCoord3fv(&mesh->m_texcoords[v.m_texcoordIndex][0]); glNormal3fv(&mesh->m_normals[v.m_normalIndex][0]); glVertex3fv(&mesh->m_positions[v.m_posIndex][0]); } } glEnd(); } } #endif }
26.180952
119
0.68825
[ "mesh", "geometry" ]
d8f04d0d9d3ab00e590aefff7051d94c5e182f94
4,284
cpp
C++
Feature_construction/2_resi_pattern_detection/deadloc_detect/loc_arr.cpp
HPCCS/PARIS
a245b3c9ea201a098329b1d2c52c825286a4199a
[ "MIT" ]
null
null
null
Feature_construction/2_resi_pattern_detection/deadloc_detect/loc_arr.cpp
HPCCS/PARIS
a245b3c9ea201a098329b1d2c52c825286a4199a
[ "MIT" ]
null
null
null
Feature_construction/2_resi_pattern_detection/deadloc_detect/loc_arr.cpp
HPCCS/PARIS
a245b3c9ea201a098329b1d2c52c825286a4199a
[ "MIT" ]
null
null
null
/* split dynamic trace into batches. * For each batch, there is a location * array, in which there is no copied * locations */ #include "loc_arr.h" #include "omp.h" /*/ if elem in vec template <class T> bool isInOrNot(vector<T> &vec, T elem){ int sz = vec.size(); for(int i=0;i<sz;i++){ if(vec[i]==elem){ return true; break; }else{ continue; } } return false; } */ // if elem in vec template <class T> bool isInOrNot(vector<T> &vec, T elem){ int sz = vec.size(); bool bl[sz]; int i; bool rt=false; #pragma omp parallel { #pragma omp parallel for shared(vec,bl) private(i) for(i=0;i<sz;i++){ if(vec[i]==elem){ bl[i]=true; }else{ bl[i]=false; } } #pragma omp parallel for shared(bl) private(i) for(i=0;i<sz;i++){ rt=rt||bl[i]; } } return rt; } // only handle a single batch here (loc_arr_size) loc_arr::loc_arr(vector<instr_info> &instr_batch){ // for the single batch // collect all its reg and addr arrays int bsz = instr_batch.size(); for(int i=0;i<bsz;i++){ int oprd_sz = instr_batch[i].oprd_line_set.size(); for(int j=0;j<oprd_sz;j++){ string str_tmp = instr_batch[i].oprd_line_set[j].regName; //bool signal = false; // if there is repeat in reg_arr if(this->reg_arr.empty()){ this->reg_arr.push_back(str_tmp); }else{ //int reg_sz = reg_arr.size(); //for(int k=0;k<reg_sz;k++){ //if(reg_arr[k]==str_tmp){ //signal = true; //break; //}else{ //continue; //} //} if(isInOrNot(reg_arr,str_tmp) == false){ reg_arr.push_back(str_tmp); }else{ continue; } } // handling these operations that have mem addr inside // alloca, load, store, getelementptr // fence, cmpxchg, atomicrmw int tmp_opc = instr_batch[i].opcodeId; if(tmp_opc>=26&&tmp_opc<=32&&instr_batch[i].lineId>0){ switch(tmp_opc){ case 26:{ // get the mem addr of the alloca from the only oprand // assert(oprd_sz==1 && "\nBUG: alloc has more than 1 operand!\n"); string addr = to_string((int)instr_batch[i].oprd_line_set[0].dynValue); if(addr_arr.empty()){ addr_arr.push_back(addr); }else{ if(isInOrNot(addr_arr,addr)==false){ addr_arr.push_back(addr); } } break; } case 27:{ // get the mem addr in load // the oprand id is 1 for(int k=0;k<oprd_sz;k++){ if(instr_batch[i].oprd_line_set[k].arguId == "1"){ string addr = to_string((int)instr_batch[i].oprd_line_set[k].dynValue); if(addr_arr.empty()){ addr_arr.push_back(addr); break; }else{ if(isInOrNot(addr_arr,addr)==false){ addr_arr.push_back(addr); }else{ break; } } } } break; } case 28:{ // get the mem addr in store // the oprand id is 2 for(int k=0;k<oprd_sz;k++){ if(instr_batch[i].oprd_line_set[k].arguId == "2"){ string addr = to_string((int)instr_batch[i].oprd_line_set[k].dynValue); if(addr_arr.empty()){ addr_arr.push_back(addr); break; }else{ if(isInOrNot(addr_arr,addr)==false){ addr_arr.push_back(addr); }else{ break; } } } } break; } case 29:{ // get the mem addr in getelementptr // the oprand id is r // becase the base mem id is added // by load operation already for(int k=0;k<oprd_sz;k++){ if(instr_batch[i].oprd_line_set[k].arguId == "r"){ string addr = to_string((int)instr_batch[i].oprd_line_set[k].dynValue); if(addr_arr.empty()){ addr_arr.push_back(addr); break; }else{ if(isInOrNot(addr_arr,addr)==false){ addr_arr.push_back(addr); }else{ break; } } } } break; } case 30: printf("******************************\n \ the Fence operation is found!!\n \ ******************************\n"); break; case 31: printf("********************************\n \ the CmpXchg operation is found!!\n \ ********************************\n"); break; case 32: printf("*********************************\n \ the atomicrmw operation is found!!\n \ *********************************\n"); break; } } } } } loc_arr::~loc_arr(){ }
22.909091
76
0.552754
[ "vector" ]
d8f7234543efcbc6d874438c0240f9ab89cc753e
147,439
cc
C++
vasptest.cc
idaholab/hpcswtest
1f976b913231a7d3259a8a10a7af58af3929c5b2
[ "Apache-2.0" ]
6
2017-08-15T19:46:32.000Z
2022-02-16T01:32:49.000Z
vasptest.cc
idaholab/hpcswtest
1f976b913231a7d3259a8a10a7af58af3929c5b2
[ "Apache-2.0" ]
5
2017-08-15T19:45:28.000Z
2021-12-10T21:29:38.000Z
vasptest.cc
idaholab/hpcswtest
1f976b913231a7d3259a8a10a7af58af3929c5b2
[ "Apache-2.0" ]
3
2017-08-15T15:36:22.000Z
2021-12-04T16:22:37.000Z
/* Copyright 2017 Battelle Energy Alliance, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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. Description ----------- HPC Software testing suite. VaspTest subclass source code. Date Created: Wed Dec 16 14:32:52 MST 2015 Author: Cormac Garvey */ #include "vasptest.h" #include <iostream> // for debugging only #include <cstdlib> // for exit() namespace hpcswtest { const std::vector<std::string> VaspTest::vasp_incar_inputs_ = { R"(SYSTEM=O_free_atom ISMEAR=0 SIGMA=0.01 #no broadening for atomic levels)" }; // vector vasp_incar_inputs_ const std::vector<std::string> VaspTest::vasp_kpoints_inputs_ = { R"(mma-point only 1 ! one k-point rec ! in units of the reciprocal lattice vector 0 0 0 1 ! 3 coordinates and weigh)" }; // vector vasp_kpoints_inputs_ const std::vector<std::string> VaspTest::vasp_poscar_inputs_ = { R"(O atom in a box 1.0 7.0 0.0 0.0 0.0 7.0 0.0 0.0 0.0 7.0 1 cartesian 0 0 0)" }; // vector vasp_poscar_inputs_ const std::vector<std::string> VaspTest::vasp_potcar_inputs_ = { R"( PAW_PBE O 08Apr2002 6.00000000000000000 parameters from PSCTR are: VRHFIN =O: s2p4 LEXCH = PE EATOM = 432.3788 eV, 31.7789 Ry TITEL = PAW_PBE O 08Apr2002 LULTRA = F use ultrasoft PP ? IUNSCR = 0 unscreen: 0-lin 1-nonlin 2-no RPACOR = .000 partial core radius POMASS = 16.000; ZVAL = 6.000 mass and valenz RCORE = 1.520 outmost cutoff radius RWIGS = 1.550; RWIGS = .820 wigner-seitz radius (au A) ENMAX = 400.000; ENMIN = 300.000 eV ICORE = 2 local potential LCOR = T correct aug charges LPAW = T paw PP EAUG = 605.392 DEXC = .000 RMAX = 2.264 core radius for proj-oper RAUG = 1.300 factor for augmentation sphere RDEP = 1.550 radius for radial grids QCUT = -5.520; QGAM = 11.041 optimization parameters Description l E TYP RCUT TYP RCUT 0 .000 23 1.200 0 -.700 23 1.200 1 .000 23 1.520 1 .600 23 1.520 2 .000 7 1.500 Error from kinetic energy argument (eV) NDATA = 100 STEP = 20.000 1.050 163. 160. 159. 156. 154. 151. 148. 146. 142. 139. 137. 134. 130. 126. 123. 119. 115. 111. 108. 102. 98.8 95.2 90.0 86.6 83.2 78.3 73.5 70.4 65.9 61.6 57.4 53.4 49.6 46.0 42.6 39.3 35.3 32.4 28.9 26.4 23.4 20.6 18.1 15.8 13.7 11.9 10.3 8.47 7.22 5.87 4.73 3.95 3.13 2.45 1.80 1.37 1.03 .721 .493 .329 .215 .138 .882E-01 .534E-01 .367E-01 .267E-01 .223E-01 .205E-01 .193E-01 .181E-01 .162E-01 .138E-01 .112E-01 .878E-02 .646E-02 .490E-02 .370E-02 .300E-02 .259E-02 .238E-02 .219E-02 .196E-02 .167E-02 .132E-02 .100E-02 .764E-03 .617E-03 .544E-03 .522E-03 .507E-03 .467E-03 .403E-03 .312E-03 .236E-03 .181E-03 .157E-03 .152E-03 .150E-03 .139E-03 .118E-03 END of PSCTR-controll parameters local part 122.832189257630020 .23155445E+02 .23152693E+02 .23149261E+02 .23143544E+02 .23135541E+02 .23125253E+02 .23112681E+02 .23097823E+02 .23080677E+02 .23061237E+02 .23039495E+02 .23015440E+02 .22989059E+02 .22960335E+02 .22929249E+02 .22895777E+02 .22859896E+02 .22821578E+02 .22780793E+02 .22737509E+02 .22691690E+02 .22643299E+02 .22592293E+02 .22538630E+02 .22482260E+02 .22423132E+02 .22361190E+02 .22296376E+02 .22228625E+02 .22157873E+02 .22084048E+02 .22007079E+02 .21926890E+02 .21843403E+02 .21756538E+02 .21666211E+02 .21572340E+02 .21474838E+02 .21373619E+02 .21268597E+02 .21159684E+02 .21046794E+02 .20929842E+02 .20808743E+02 .20683417E+02 .20553785E+02 .20419772E+02 .20281308E+02 .20138327E+02 .19990769E+02 .19838580E+02 .19681713E+02 .19520129E+02 .19353797E+02 .19182693E+02 .19006804E+02 .18826128E+02 .18640671E+02 .18450451E+02 .18255500E+02 .18055858E+02 .17851580E+02 .17642733E+02 .17429396E+02 .17211664E+02 .16989641E+02 .16763448E+02 .16533218E+02 .16299098E+02 .16061247E+02 .15819840E+02 .15575061E+02 .15327109E+02 .15076196E+02 .14822544E+02 .14566388E+02 .14307973E+02 .14047552E+02 .13785392E+02 .13521763E+02 .13256948E+02 .12991234E+02 .12724915E+02 .12458289E+02 .12191659E+02 .11925331E+02 .11659614E+02 .11394816E+02 .11131245E+02 .10869211E+02 .10609017E+02 .10350966E+02 .10095354E+02 .98424727E+01 .95926072E+01 .93460340E+01 .91030212E+01 .88638270E+01 .86286987E+01 .83978722E+01 .81715707E+01 .79500043E+01 .77333688E+01 .75218455E+01 .73156002E+01 .71147829E+01 .69195273E+01 .67299503E+01 .65461519E+01 .63682145E+01 .61962037E+01 .60301671E+01 .58701350E+01 .57161205E+01 .55681193E+01 .54261103E+01 .52900556E+01 .51599012E+01 .50355773E+01 .49169989E+01 .48040663E+01 .46966659E+01 .45946711E+01 .44979426E+01 .44063297E+01 .43196709E+01 .42377948E+01 .41605214E+01 .40876627E+01 .40190236E+01 .39544034E+01 .38935965E+01 .38363932E+01 .37825814E+01 .37319469E+01 .36842749E+01 .36393508E+01 .35969612E+01 .35568949E+01 .35189437E+01 .34829034E+01 .34485744E+01 .34157630E+01 .33842813E+01 .33539488E+01 .33245924E+01 .32960472E+01 .32681572E+01 .32407752E+01 .32137639E+01 .31869956E+01 .31603530E+01 .31337289E+01 .31070267E+01 .30801603E+01 .30530540E+01 .30256429E+01 .29978721E+01 .29696971E+01 .29410832E+01 .29120056E+01 .28824486E+01 .28524057E+01 .28218788E+01 .27908779E+01 .27594206E+01 .27275318E+01 .26952425E+01 .26625901E+01 .26296170E+01 .25963704E+01 .25629018E+01 .25292661E+01 .24955211E+01 .24617268E+01 .24279449E+01 .23942383E+01 .23606701E+01 .23273035E+01 .22942010E+01 .22614239E+01 .22290318E+01 .21970823E+01 .21656302E+01 .21347276E+01 .21044231E+01 .20747616E+01 .20457843E+01 .20175281E+01 .19900255E+01 .19633044E+01 .19373883E+01 .19122957E+01 .18880405E+01 .18646316E+01 .18420733E+01 .18203652E+01 .17995024E+01 .17794755E+01 .17602707E+01 .17418705E+01 .17242532E+01 .17073938E+01 .16912639E+01 .16758320E+01 .16610641E+01 .16469237E+01 .16333722E+01 .16203693E+01 .16078735E+01 .15958421E+01 .15842318E+01 .15729988E+01 .15620996E+01 .15514907E+01 .15411295E+01 .15309742E+01 .15209843E+01 .15111206E+01 .15013460E+01 .14916249E+01 .14819243E+01 .14722133E+01 .14624637E+01 .14526498E+01 .14427487E+01 .14327405E+01 .14226081E+01 .14123373E+01 .14019171E+01 .13913392E+01 .13805984E+01 .13696923E+01 .13586213E+01 .13473883E+01 .13359990E+01 .13244615E+01 .13127860E+01 .13009850E+01 .12890728E+01 .12770654E+01 .12649804E+01 .12528367E+01 .12406544E+01 .12284542E+01 .12162578E+01 .12040872E+01 .11919646E+01 .11799123E+01 .11679522E+01 .11561062E+01 .11443952E+01 .11328397E+01 .11214589E+01 .11102712E+01 .10992936E+01 .10885419E+01 .10780303E+01 .10677713E+01 .10577759E+01 .10480534E+01 .10386110E+01 .10294545E+01 .10205875E+01 .10120120E+01 .10037281E+01 .99573405E+00 .98802637E+00 .98059993E+00 .97344797E+00 .96656217E+00 .95993281E+00 .95354881E+00 .94739790E+00 .94146671E+00 .93574091E+00 .93020536E+00 .92484425E+00 .91964123E+00 .91457956E+00 .90964227E+00 .90481229E+00 .90007260E+00 .89540637E+00 .89079709E+00 .88622870E+00 .88168571E+00 .87715333E+00 .87261756E+00 .86806530E+00 .86348444E+00 .85886393E+00 .85419386E+00 .84946550E+00 .84467136E+00 .83980521E+00 .83486211E+00 .82983841E+00 .82473177E+00 .81954111E+00 .81426662E+00 .80890973E+00 .80347303E+00 .79796024E+00 .79237615E+00 .78672657E+00 .78101820E+00 .77525858E+00 .76945600E+00 .76361942E+00 .75775831E+00 .75188262E+00 .74600265E+00 .74012893E+00 .73427215E+00 .72844301E+00 .72265218E+00 .71691014E+00 .71122715E+00 .70561310E+00 .70007743E+00 .69462911E+00 .68927647E+00 .68402723E+00 .67888835E+00 .67386605E+00 .66896570E+00 .66419185E+00 .65954814E+00 .65503733E+00 .65066125E+00 .64642082E+00 .64231605E+00 .63834605E+00 .63450904E+00 .63080240E+00 .62722268E+00 .62376568E+00 .62042644E+00 .61719934E+00 .61407817E+00 .61105614E+00 .60812599E+00 .60528004E+00 .60251030E+00 .59980849E+00 .59716614E+00 .59457468E+00 .59202550E+00 .58951003E+00 .58701980E+00 .58454654E+00 .58208221E+00 .57961910E+00 .57714987E+00 .57466763E+00 .57216594E+00 .56963895E+00 .56708132E+00 .56448837E+00 .56185603E+00 .55918091E+00 .55646027E+00 .55369208E+00 .55087499E+00 .54800835E+00 .54509219E+00 .54212720E+00 .53911474E+00 .53605675E+00 .53295582E+00 .52981506E+00 .52663812E+00 .52342909E+00 .52019253E+00 .51693334E+00 .51365677E+00 .51036832E+00 .50707371E+00 .50377881E+00 .50048961E+00 .49721211E+00 .49395232E+00 .49071615E+00 .48750942E+00 .48433774E+00 .48120651E+00 .47812083E+00 .47508551E+00 .47210497E+00 .46918326E+00 .46632398E+00 .46353029E+00 .46080485E+00 .45814984E+00 .45556693E+00 .45305727E+00 .45062147E+00 .44825964E+00 .44597137E+00 .44375571E+00 .44161126E+00 .43953613E+00 .43752797E+00 .43558402E+00 .43370110E+00 .43187571E+00 .43010401E+00 .42838185E+00 .42670486E+00 .42506848E+00 .42346796E+00 .42189845E+00 .42035503E+00 .41883273E+00 .41732664E+00 .41583186E+00 .41434364E+00 .41285733E+00 .41136849E+00 .40987289E+00 .40836657E+00 .40684582E+00 .40530728E+00 .40374789E+00 .40216498E+00 .40055624E+00 .39891975E+00 .39725399E+00 .39555786E+00 .39383066E+00 .39207210E+00 .39028230E+00 .38846177E+00 .38661143E+00 .38473254E+00 .38282674E+00 .38089598E+00 .37894254E+00 .37696897E+00 .37497807E+00 .37297287E+00 .37095659E+00 .36893261E+00 .36690442E+00 .36487563E+00 .36284989E+00 .36083085E+00 .35882219E+00 .35682749E+00 .35485030E+00 .35289401E+00 .35096191E+00 .34905706E+00 .34718238E+00 .34534052E+00 .34353392E+00 .34176471E+00 .34003479E+00 .33834572E+00 .33669879E+00 .33509493E+00 .33353480E+00 .33201871E+00 .33054663E+00 .32911826E+00 .32773295E+00 .32638975E+00 .32508743E+00 .32382450E+00 .32259918E+00 .32140947E+00 .32025315E+00 .31912781E+00 .31803085E+00 .31695955E+00 .31591105E+00 .31488241E+00 .31387062E+00 .31287264E+00 .31188540E+00 .31090587E+00 .30993106E+00 .30895805E+00 .30798401E+00 .30700625E+00 .30602221E+00 .30502951E+00 .30402592E+00 .30300946E+00 .30197832E+00 .30093095E+00 .29986602E+00 .29878246E+00 .29767946E+00 .29655644E+00 .29541311E+00 .29424942E+00 .29306559E+00 .29186206E+00 .29063955E+00 .28939897E+00 .28814149E+00 .28686844E+00 .28558136E+00 .28428197E+00 .28297213E+00 .28165382E+00 .28032916E+00 .27900034E+00 .27766963E+00 .27633933E+00 .27501179E+00 .27368934E+00 .27237430E+00 .27106894E+00 .26977549E+00 .26849606E+00 .26723268E+00 .26598726E+00 .26476157E+00 .26355722E+00 .26237566E+00 .26121818E+00 .26008586E+00 .25897959E+00 .25790008E+00 .25684781E+00 .25582306E+00 .25482591E+00 .25385623E+00 .25291367E+00 .25199772E+00 .25110764E+00 .25024254E+00 .24940133E+00 .24858278E+00 .24778552E+00 .24700803E+00 .24624869E+00 .24550578E+00 .24477747E+00 .24406190E+00 .24335715E+00 .24266125E+00 .24197226E+00 .24128820E+00 .24060715E+00 .23992721E+00 .23924657E+00 .23856345E+00 .23787620E+00 .23718326E+00 .23648318E+00 .23577464E+00 .23505648E+00 .23432765E+00 .23358730E+00 .23283470E+00 .23206930E+00 .23129074E+00 .23049880E+00 .22969344E+00 .22887479E+00 .22804315E+00 .22719895E+00 .22634282E+00 .22547549E+00 .22459785E+00 .22371090E+00 .22281576E+00 .22191365E+00 .22100589E+00 .22009385E+00 .21917899E+00 .21826279E+00 .21734679E+00 .21643251E+00 .21552151E+00 .21461531E+00 .21371541E+00 .21282327E+00 .21194030E+00 .21106783E+00 .21020712E+00 .20935932E+00 .20852550E+00 .20770662E+00 .20690351E+00 .20611688E+00 .20534731E+00 .20459524E+00 .20386099E+00 .20314472E+00 .20244647E+00 .20176612E+00 .20110343E+00 .20045804E+00 .19982942E+00 .19921696E+00 .19861993E+00 .19803748E+00 .19746867E+00 .19691247E+00 .19636779E+00 .19583345E+00 .19530823E+00 .19479088E+00 .19428008E+00 .19377454E+00 .19327293E+00 .19277395E+00 .19227630E+00 .19177873E+00 .19128003E+00 .19077902E+00 .19027463E+00 .18976581E+00 .18925164E+00 .18873125E+00 .18820390E+00 .18766893E+00 .18712580E+00 .18657407E+00 .18601343E+00 .18544366E+00 .18486468E+00 .18427653E+00 .18367934E+00 .18307336E+00 .18245897E+00 .18183663E+00 .18120690E+00 .18057043E+00 .17992795E+00 .17928028E+00 .17862829E+00 .17797292E+00 .17731514E+00 .17665599E+00 .17599649E+00 .17533773E+00 .17468077E+00 .17402668E+00 .17337651E+00 .17273128E+00 .17209201E+00 .17145962E+00 .17083504E+00 .17021908E+00 .16961253E+00 .16901607E+00 .16843034E+00 .16785584E+00 .16729304E+00 .16674226E+00 .16620377E+00 .16567772E+00 .16516416E+00 .16466305E+00 .16417424E+00 .16369750E+00 .16323250E+00 .16277882E+00 .16233597E+00 .16190338E+00 .16148038E+00 .16106628E+00 .16066029E+00 .16026161E+00 .15986936E+00 .15948266E+00 .15910059E+00 .15872220E+00 .15834656E+00 .15797274E+00 .15759979E+00 .15722681E+00 .15685292E+00 .15647729E+00 .15609910E+00 .15571761E+00 .15533214E+00 .15494205E+00 .15454679E+00 .15414587E+00 .15373889E+00 .15332551E+00 .15290550E+00 .15247869E+00 .15204501E+00 .15160447E+00 .15115717E+00 .15070328E+00 .15024306E+00 .14977685E+00 .14930505E+00 .14882814E+00 .14834665E+00 .14786118E+00 .14737238E+00 .14688092E+00 .14638754E+00 .14589300E+00 .14539806E+00 .14490354E+00 .14441021E+00 .14391889E+00 .14343036E+00 .14294540E+00 .14246476E+00 .14198915E+00 .14151925E+00 .14105571E+00 .14059910E+00 .14014996E+00 .13970877E+00 .13927593E+00 .13885178E+00 .13843659E+00 .13803056E+00 .13763383E+00 .13724643E+00 .13686835E+00 .13649948E+00 .13613966E+00 .13578864E+00 .13544611E+00 .13511171E+00 .13478500E+00 .13446548E+00 .13415263E+00 .13384585E+00 .13354452E+00 .13324799E+00 .13295557E+00 .13266656E+00 .13238023E+00 .13209586E+00 .13181273E+00 .13153012E+00 .13124732E+00 .13096365E+00 .13067845E+00 .13039111E+00 .13010103E+00 .12980768E+00 .12951055E+00 .12920922E+00 .12890329E+00 .12859244E+00 .12827640E+00 .12795499E+00 .12762805E+00 .12729554E+00 .12695744E+00 .12661382E+00 .12626482E+00 .12591063E+00 .12555151E+00 .12518776E+00 .12481975E+00 .12444790E+00 .12407269E+00 .12369460E+00 .12331418E+00 .12293200E+00 .12254866E+00 .12216478E+00 .12178098E+00 .12139790E+00 .12101618E+00 .12063646E+00 .12025935E+00 .11988545E+00 .11951535E+00 .11914960E+00 .11878872E+00 .11843318E+00 .11808343E+00 .11773986E+00 .11740281E+00 .11707256E+00 .11674936E+00 .11643337E+00 .11612472E+00 .11582347E+00 .11552960E+00 .11524306E+00 .11496374E+00 .11469144E+00 .11442595E+00 .11416697E+00 .11391417E+00 .11366717E+00 .11342554E+00 .11318884E+00 .11295655E+00 .11272816E+00 .11250313E+00 .11228088E+00 .11206084E+00 .11184242E+00 .11162503E+00 .11140810E+00 .11119104E+00 .11097329E+00 .11075431E+00 .11053359E+00 .11031063E+00 .11008499E+00 .10985625E+00 .10962403E+00 .10938800E+00 .10914789E+00 .10890345E+00 .10865450E+00 .10840093E+00 .10814264E+00 .10787962E+00 .10761191E+00 .10733958E+00 .10706278E+00 .10678170E+00 .10649658E+00 .10620769E+00 .10591537E+00 .10561998E+00 .10532192E+00 .10502162E+00 .10471954E+00 .10441617E+00 .10411201E+00 .10380756E+00 .10350335E+00 .10319991E+00 .10289777E+00 .10259743E+00 .10229940E+00 .10200418E+00 .10171222E+00 .10142397E+00 .10113985E+00 .10086023E+00 .10058546E+00 .10031584E+00 .10005162E+00 .99793034E-01 .99540245E-01 .99293377E-01 .99052504E-01 .98817651E-01 .98588793E-01 .98365858E-01 .98148724E-01 .97937225E-01 .97731147E-01 .97530237E-01 .97334202E-01 .97142709E-01 .96955397E-01 .96771871E-01 .96591713E-01 .96414480E-01 .96239713E-01 .96066940E-01 .95895679E-01 .95725442E-01 .95555746E-01 .95386107E-01 .95216055E-01 .95045131E-01 .94872896E-01 .94698932E-01 .94522846E-01 .94344276E-01 .94162891E-01 .93978395E-01 .93790532E-01 .93599082E-01 .93403871E-01 .93204764E-01 .93001674E-01 .92794556E-01 .92583411E-01 .92368286E-01 .92149271E-01 .91926498E-01 .91700141E-01 .91470413E-01 .91237566E-01 .91001884E-01 .90763683E-01 .90523308E-01 .90281128E-01 .90037534E-01 .89792935E-01 .89547752E-01 .89302418E-01 .89057370E-01 .88813047E-01 .88569884E-01 .88328311E-01 .88088743E-01 .87851584E-01 .87617217E-01 .87386003E-01 .87158276E-01 .86934344E-01 .86714482E-01 .86498932E-01 .86287900E-01 .86081555E-01 .85880026E-01 .85683402E-01 .85491732E-01 .85305023E-01 .85123242E-01 .84946313E-01 .84774125E-01 .84606523E-01 .84443320E-01 .84284292E-01 .84129183E-01 .83977708E-01 .83829555E-01 .83684387E-01 .83541847E-01 .83401561E-01 .83263141E-01 .83126188E-01 .82990297E-01 .82855060E-01 .82720073E-01 .82584933E-01 .82449250E-01 .82312643E-01 .82174750E-01 .82035227E-01 .81893753E-01 .81750031E-01 .81603794E-01 .81454803E-01 .81302851E-01 .81147768E-01 .80989416E-01 .80827694E-01 .80662540E-01 .80493929E-01 .80321872E-01 .80146420E-01 .79967660E-01 .79785713E-01 .79600737E-01 .79412920E-01 .79222482E-01 .79029671E-01 .78834760E-01 .78638045E-01 .78439844E-01 .78240491E-01 .78040334E-01 .77839732E-01 .77639049E-01 .77438658E-01 .77238926E-01 .77040221E-01 .76842902E-01 .76647319E-01 .76453807E-01 .76262685E-01 .76074254E-01 .75888790E-01 .75706547E-01 .75527750E-01 .75352598E-01 .75181256E-01 .75013859E-01 .74850509E-01 .74691274E-01 .74536187E-01 .74385246E-01 .74238414E-01 .74095622E-01 .73956766E-01 .73821710E-01 .73690288E-01 .73562306E-01 .73437542E-01 .73315749E-01 .73196658E-01 .73079982E-01 .72965415E-01 .72852638E-01 .72741320E-01 .72631122E-01 .72521701E-01 .72412713E-01 .72303815E-01 .72194667E-01 gradient corrections used for XC 5 atomic pseudo charge-density .60000000E+01 .59917682E+01 .59671789E+01 .59265479E+01 .58703891E+01 .57993990E+01 .57144341E+01 .56164855E+01 .55066511E+01 .53861066E+01 .52560766E+01 .51178084E+01 .49725469E+01 .48215134E+01 .46658876E+01 .45067929E+01 .43452859E+01 .41823479E+01 .40188803E+01 .38557025E+01 .36935506E+01 .35330797E+01 .33748662E+01 .32194109E+01 .30671444E+01 .29184307E+01 .27735730E+01 .26328185E+01 .24963632E+01 .23643571E+01 .22369087E+01 .21140897E+01 .19959388E+01 .18824658E+01 .17736551E+01 .16694691E+01 .15698510E+01 .14747279E+01 .13840130E+01 .12976078E+01 .12154045E+01 .11372872E+01 .10631344E+01 .99281940E+00 .92621249E+00 .86318152E+00 .80359313E+00 .74731357E+00 .69420942E+00 .64414831E+00 .59699943E+00 .55263402E+00 .51092580E+00 .47175127E+00 .43498998E+00 .40052480E+00 .36824205E+00 .33803164E+00 .30978717E+00 .28340598E+00 .25878921E+00 .23584178E+00 .21447237E+00 .19459343E+00 .17612108E+00 .15897509E+00 .14307879E+00 .12835897E+00 .11474584E+00 .10217290E+00 .90576828E-01 .79897428E-01 .70077479E-01 .61062654E-01 .52801404E-01 .45244856E-01 .38346707E-01 .32063120E-01 .26352622E-01 .21176003E-01 .16496215E-01 .12278281E-01 .84891979E-02 .50978486E-02 .20749112E-02 -.60722392E-03 -.29745366E-02 -.50514558E-02 -.68609362E-02 -.84245308E-02 -.97624615E-02 -.10893686E-01 -.11835965E-01 -.12605919E-01 -.13219093E-01 -.13690009E-01 -.14032225E-01 -.14258381E-01 -.14380251E-01 -.14408793E-01 -.14354189E-01 -.14225891E-01 -.14032660E-01 -.13782607E-01 -.13483228E-01 -.13141441E-01 -.12763619E-01 -.12355619E-01 -.11922818E-01 -.11470137E-01 -.11002072E-01 -.10522716E-01 -.10035788E-01 -.95446538E-02 -.90523500E-02 -.85616040E-02 -.80748545E-02 -.75942711E-02 -.71217719E-02 -.66590412E-02 -.62075454E-02 -.57685488E-02 -.53431281E-02 -.49321863E-02 -.45364660E-02 -.41565619E-02 -.37929322E-02 -.34459103E-02 -.31157151E-02 -.28024608E-02 -.25061667E-02 -.22267656E-02 -.19641127E-02 -.17179931E-02 -.14881294E-02 -.12741886E-02 -.10757886E-02 -.89250485E-03 -.72387531E-03 -.56940653E-03 -.42857839E-03 -.30084889E-03 -.18565853E-03 -.82434402E-04 .94060408E-05 .90451458E-04 .16129340E-03 .22252332E-03 .27472986E-03 .31849633E-03 .35439845E-03 .38300228E-03 .40486239E-03 .42052015E-03 .43050232E-03 .43531967E-03 .43546591E-03 .43141669E-03 .42362876E-03 .41253930E-03 .39856538E-03 .38210349E-03 .36352929E-03 .34319737E-03 .32144120E-03 .29857309E-03 .27488433E-03 .25064534E-03 .22610596E-03 .20149575E-03 .17702443E-03 .15288230E-03 .12924076E-03 .10625290E-03 .84054063E-04 .62762536E-04 .42480190E-04 .23293206E-04 .52728069E-05 -.11523997E-04 -.27053634E-04 -.41285196E-04 -.54199648E-04 -.65789036E-04 -.76055698E-04 -.85011472E-04 -.92676912E-04 -.99080513E-04 -.10425795E-03 -.10825132E-03 -.11110843E-03 -.11288204E-03 -.11362924E-03 -.11341070E-03 -.11229009E-03 -.11033340E-03 -.10760841E-03 -.10418409E-03 -.10013005E-03 -.95516074E-04 -.90411625E-04 -.84885403E-04 -.79004941E-04 -.72836222E-04 -.66443339E-04 -.59888174E-04 -.53230123E-04 -.46525844E-04 -.39829037E-04 -.33190254E-04 -.26656746E-04 -.20272330E-04 -.14077288E-04 -.81082945E-05 -.23983708E-05 .30231404E-05 .81305709E-05 .12901903E-04 .17318722E-04 .21366154E-04 .25032774E-04 .28310510E-04 .31194523E-04 .33683071E-04 .35777367E-04 .37481423E-04 .38801876E-04 .39747820E-04 .40330618E-04 .40563715E-04 .40462443E-04 .40043828E-04 .39326388E-04 .38329937E-04 .37075387E-04 .35584548E-04 .33879943E-04 .31984612E-04 .29921930E-04 .27715431E-04 .25388634E-04 .22964881E-04 .20467181E-04 .17918061E-04 .15339435E-04 .12752470E-04 .10177472E-04 .76337790E-05 .51396670E-05 .27122626E-05 .36747166E-06 -.18800836E-05 -.40171154E-05 -.60317107E-05 -.79133600E-05 -.96529757E-05 -.11242900E-04 -.12676905E-04 -.13950176E-04 -.15059296E-04 -.16002213E-04 -.16778201E-04 -.17387818E-04 -.17832850E-04 -.18116252E-04 -.18242083E-04 -.18215435E-04 -.18042359E-04 -.17729783E-04 -.17285432E-04 -.16717741E-04 -.16035770E-04 -.15249111E-04 -.14367805E-04 -.13402245E-04 -.12363095E-04 -.11261198E-04 -.10107488E-04 -.89129121E-05 -.76883443E-05 -.64445099E-05 -.51919113E-05 -.39407569E-05 -.27008960E-05 -.14817571E-05 -.29229229E-06 .85907414E-06 .19644910E-05 .30167200E-05 .40091707E-05 .49359281E-05 .57917760E-05 .65722140E-05 .72734684E-05 .78924981E-05 .84269947E-05 .88753771E-05 .92367814E-05 .95110452E-05 .96986879E-05 .98008862E-05 .98194454E-05 .97567671E-05 .96158136E-05 .94000686E-05 .91134958E-05 .87604949E-05 .83458553E-05 .78747087E-05 .73524802E-05 .67848387E-05 .61776463E-05 .55369089E-05 .48687256E-05 .41792398E-05 .34745909E-05 .27608672E-05 .20440608E-05 .13300240E-05 .62442817E-06 -.67274844E-07 -.73988911E-06 -.13885077E-05 -.20085430E-05 -.25957536E-05 -.31462683E-05 -.36566061E-05 -.41236935E-05 -.45448774E-05 -.49179355E-05 -.52410820E-05 -.55129711E-05 -.57326961E-05 -.58997856E-05 -.60141966E-05 -.60763041E-05 -.60868881E-05 -.60471176E-05 -.59585325E-05 -.58230221E-05 -.56428027E-05 -.54203921E-05 -.51585832E-05 -.48604156E-05 -.45291462E-05 -.41682184E-05 -.37812318E-05 -.33719094E-05 -.29440665E-05 -.25015785E-05 -.20483491E-05 -.15882795E-05 -.11252375E-05 -.66302845E-06 -.20536640E-06 .24415270E-06 .68207665E-06 .11051209E-05 .15101907E-05 .18944013E-05 .22550957E-05 .25898612E-05 .28965426E-05 .31732540E-05 .34183878E-05 .36306212E-05 .38089213E-05 .39525463E-05 .40610461E-05 .41342594E-05 .41723089E-05 .41755949E-05 .41447863E-05 .40808098E-05 .39848377E-05 .38582733E-05 .37027357E-05 .35200423E-05 .33121910E-05 .30813405E-05 .28297905E-05 .25599605E-05 .22743685E-05 .19756094E-05 .16663331E-05 .13492220E-05 .10269701E-05 .70226093E-06 .37774670E-06 .56028197E-07 -.26036489E-06 -.56899253E-06 -.86752192E-06 -.11537438E-05 -.14255877E-05 -.16811355E-05 -.19186339E-05 -.21365050E-05 -.23333557E-05 -.25079852E-05 -.26593909E-05 -.27867730E-05 -.28895365E-05 -.29672929E-05 -.30198589E-05 -.30472548E-05 -.30496999E-05 -.30276079E-05 -.29815799E-05 -.29123962E-05 -.28210073E-05 -.27085230E-05 -.25762012E-05 -.24254351E-05 -.22577400E-05 -.20747392E-05 -.18781493E-05 -.16697650E-05 -.14514439E-05 -.12250901E-05 -.99263919E-06 -.75604189E-06 -.51724870E-06 -.27819440E-06 -.40783164E-07 .19312596E-06 .42173291E-06 .64330979E-06 .85621327E-06 .10588960E-05 .12499175E-05 .14279530E-05 .15918027E-05 .17403988E-05 .18728116E-05 .19882544E-05 .20860878E-05 .21658217E-05 .22271172E-05 .22697861E-05 .22937907E-05 .22992407E-05 .22863909E-05 .22556358E-05 .22075048E-05 .21426558E-05 .20618676E-05 .19660321E-05 .18561454E-05 .17332978E-05 .15986645E-05 .14534943E-05 .12990990E-05 .11368416E-05 .96812543E-06 .79438183E-06 .61705882E-06 .43760937E-06 .25747988E-06 .78098960E-07 -.99133517E-07 -.27285691E-06 -.44175989E-06 -.60458990E-06 -.76016206E-06 -.90736736E-06 -.10451802E-05 -.11726648E-05 -.12889818E-05 -.13933923E-05 -.14852629E-05 -.15640686E-05 -.16293950E-05 -.16809403E-05 -.17185153E-05 -.17420434E-05 -.17515594E-05 -.17472073E-05 -.17292375E-05 -.16980032E-05 -.16539558E-05 -.15976400E-05 -.15296880E-05 -.14508129E-05 -.13618024E-05 -.12635108E-05 -.11568517E-05 -.10427895E-05 -.92233154E-06 -.79651917E-06 -.66641916E-06 -.53311498E-06 -.39769801E-06 -.26125892E-06 -.12487913E-06 .10377485E-07 .14347264E-06 .27340134E-06 .39919922E-06 .51994941E-06 .63478896E-06 .74291471E-06 .84358862E-06 .93614249E-06 .10199820E-05 .10945904E-05 .11595310E-05 .12144494E-05 .12590751E-05 .12932221E-05 .13167890E-05 .13297585E-05 .13321964E-05 .13242491E-05 .13061420E-05 .12781757E-05 .12407232E-05 .11942252E-05 .11391859E-05 .10761679E-05 .10057870E-05 .92870654E-06 .84563134E-06 .75730164E-06 .66448672E-06 .56797846E-06 .46858480E-06 .36712315E-06 .26441394E-06 .16127411E-06 .58510840E-07 -.43084584E-07 -.14274268E-06 -.23972139E-06 -.33331146E-06 -.42284137E-06 -.50768199E-06 -.58725077E-06 -.66101551E-06 -.72849772E-06 -.78927542E-06 -.84298553E-06 -.88932573E-06 -.92805581E-06 -.95899854E-06 -.98204001E-06 -.99712946E-06 -.10042787E-05 -.10035609E-05 -.99510908E-06 -.97911412E-06 -.95582224E-06 -.92553223E-06 -.88859224E-06 -.84539628E-06 -.79638041E-06 -.74201862E-06 -.68281852E-06 -.61931691E-06 -.55207504E-06 -.48167388E-06 -.40870931E-06 -.33378719E-06 -.25751852E-06 -.18051463E-06 -.10338237E-06 -.26719534E-07 .48889673E-07 .12287892E-06 .19470384E-06 .26384591E-06 .32981604E-06 .39215784E-06 .45045066E-06 .50431220E-06 .55340089E-06 .59741779E-06 .63610824E-06 .66926307E-06 .69671942E-06 .71836129E-06 .73411956E-06 .74397180E-06 .74794162E-06 .74609770E-06 .73855250E-06 .72546064E-06 .70701697E-06 .68345439E-06 .65504139E-06 .62207935E-06 .58489965E-06 .54386058E-06 .49934410E-06 .45175249E-06 .40150487E-06 .34903364E-06 .29478097E-06 .23919513E-06 .18272695E-06 .12582629E-06 .68938549E-07 .12501322E-07 -.43058875E-07 -.97329706E-07 -.14991596E-06 -.20044230E-06 -.24855584E-06 -.29392849E-06 -.33625901E-06 -.37527494E-06 -.41073416E-06 -.44242622E-06 -.47017345E-06 -.49383173E-06 -.51329101E-06 -.52847558E-06 -.53934403E-06 -.54588897E-06 -.54813649E-06 -.54614532E-06 -.54000588E-06 -.52983894E-06 -.51579416E-06 -.49804846E-06 -.47680410E-06 -.45228674E-06 -.42474318E-06 -.39443917E-06 -.36165694E-06 -.32669276E-06 -.28985441E-06 -.25145854E-06 -.21182812E-06 -.17128979E-06 -.13017128E-06 -.88798891E-07 -.47494935E-07 -.65753680E-08 .33652554E-07 .72892492E-07 .11086111E-06 .14729002E-06 .18192762E-06 .21454067E-06 .24491580E-06 .27286079E-06 .29820565E-06 .32080356E-06 .34053152E-06 .35729090E-06 .37100778E-06 .38163299E-06 .38914209E-06 .39353509E-06 .39483599E-06 .39309215E-06 .38837349E-06 .38077154E-06 .37039831E-06 .35738509E-06 .34188101E-06 .32405161E-06 .30407723E-06 .28215135E-06 .25847886E-06 .23327422E-06 .20675970E-06 .17916344E-06 .15071762E-06 .12165660E-06 .92215039E-07 .62626105E-07 .33119689E-07 .39206951E-08 -.24752597E-07 -.52690095E-07 -.79691358E-07 -.10556696E-06 -.13013974E-06 -.15324595E-06 -.17473624E-06 -.19447656E-06 -.21234887E-06 -.22825180E-06 -.24210104E-06 -.25382974E-06 -.26338863E-06 -.27074611E-06 -.27588811E-06 -.27881792E-06 -.27955575E-06 -.27813834E-06 -.27461828E-06 -.26906337E-06 -.26155573E-06 -.25219095E-06 -.24107705E-06 -.22833345E-06 -.21408978E-06 -.19848472E-06 -.18166473E-06 -.16378279E-06 -.14499707E-06 -.12546963E-06 -.10536508E-06 -.84849265E-07 -.64087970E-07 -.43245621E-07 -.22484060E-07 -.19613409E-08 .18169418E-07 .37761115E-07 .56673688E-07 .74775054E-07 .91941974E-07 .10806083E-06 .12302832E-06 .13675204E-06 .14915099E-06 .16015600E-06 .16970998E-06 .17776817E-06 .18429822E-06 .18928021E-06 .19270655E-06 .19458179E-06 .19492237E-06 .19375623E-06 .19112240E-06 .18707045E-06 .18165991E-06 .17495962E-06 .16704703E-06 .15800738E-06 .14793295E-06 .13692218E-06 .12507877E-06 .11251081E-06 .99329838E-07 .85649915E-07 .71586695E-07 .57256498E-07 .42775398E-07 .28258334E-07 .13818240E-07 -.43478729E-09 -.14394282E-07 -.27958162E-07 -.41029432E-07 -.53516833E-07 -.65335434E-07 -.76407165E-07 -.86661288E-07 -.96034794E-07 -.10447275E-06 -.11192854E-06 -.11836410E-06 -.12375001E-06 -.12806557E-06 -.13129879E-06 -.13344629E-06 -.13451320E-06 -.13451290E-06 -.13346681E-06 -.13140400E-06 -.12836090E-06 -.12438080E-06 -.11951341E-06 -.11381435E-06 -.10734461E-06 -.10016996E-06 -.92360356E-07 -.83989297E-07 -.75133217E-07 -.65870815E-07 -.56282407E-07 -.46449269E-07 -.36452990E-07 -.26374834E-07 -.16295114E-07 -.62925859E-08 .35561287E-08 .13177100E-07 .22499609E-07 .31456639E-07 .39985322E-07 .48027346E-07 .55529326E-07 .62443121E-07 .68726111E-07 .74341419E-07 .79258092E-07 .83451231E-07 .86902064E-07 .89597984E-07 .91532524E-07 .92705296E-07 .93121878E-07 .92793663E-07 .91737653E-07 .89976232E-07 .87536883E-07 .84451885E-07 .80757970E-07 .76495956E-07 .71710350E-07 .66448940E-07 .60762354E-07 .54703620E-07 .48327702E-07 .41691044E-07 .34851096E-07 .27865848E-07 .20793373E-07 .13691366E-07 .66167019E-08 -.37499308E-09 -.72297542E-08 -.13895671E-07 -.20323255E-07 -.26465788E-07 -.32279633E-07 -.37724526E-07 -.42763829E-07 -.47364755E-07 -.51498560E-07 -.55140694E-07 -.58270921E-07 -.60873410E-07 -.62936773E-07 -.64454090E-07 -.65422877E-07 -.65845040E-07 -.65726779E-07 -.65078469E-07 -.63914512E-07 -.62253155E-07 -.60116282E-07 -.57529183E-07 -.54520303E-07 -.51120960E-07 -.47365060E-07 -.43288783E-07 -.38930265E-07 -.34329266E-07 -.29526833E-07 -.24564953E-07 -.19486211E-07 -.14333446E-07 -.91494082E-08 -.39764231E-08 .11439326E-08 .61711490E-08 .11066085E-07 .15791256E-07 .20311104E-07 .24592250E-07 .28603725E-07 .32317176E-07 .35707053E-07 .38750770E-07 .41428839E-07 .43724980E-07 .45626202E-07 .47122860E-07 .48208684E-07 .48880781E-07 .49139608E-07 .48988926E-07 .48435724E-07 .47490115E-07 .46165220E-07 .44477022E-07 .42444198E-07 .40087938E-07 .37431747E-07 .34501224E-07 .31323833E-07 .27928668E-07 .24346193E-07 .20607989E-07 .16746490E-07 .12794713E-07 .87859919E-08 .47537088E-08 .73102898E-09 -.32493587E-08 -.71554951E-08 -.10956395E-07 -.14622282E-07 -.18124808E-07 -.21437265E-07 -.24534773E-07 -.27394460E-07 -.29995620E-07 -.32319853E-07 -.34351183E-07 -.36076162E-07 -.37483945E-07 -.38566352E-07 -.39317902E-07 -.39735828E-07 -.39820072E-07 -.39573258E-07 -.39000641E-07 -.38110042E-07 -.36911758E-07 -.35418458E-07 -.33645056E-07 -.31608577E-07 -.29327996E-07 -.26824071E-07 -.24119164E-07 -.21237046E-07 -.18202698E-07 -.15042101E-07 -.11782020E-07 -.84497905E-08 -.50730892E-08 -.16797180E-08 .17026196E-08 .50465364E-08 .83251756E-08 .11512419E-07 .14583088E-07 .17513133E-07 .20279819E-07 .22861888E-07 .25239723E-07 .27395485E-07 .29313242E-07 .30979082E-07 .32381206E-07 .33510003E-07 .34358115E-07 .34920476E-07 .35194336E-07 .35179264E-07 .34877139E-07 .34292118E-07 .33430584E-07 .32301084E-07 .30914248E-07 .29282688E-07 .27420888E-07 .25345076E-07 .23073086E-07 .20624207E-07 .18019022E-07 .15279237E-07 .12427505E-07 .94872409E-08 .64824308E-08 .34374431E-08 .37683268E-09 -.26748531E-08 -.56932672E-08 -.86544532E-08 -.11535032E-07 -.14312380E-07 -.16964808E-07 -.19471719E-07 -.21813770E-07 -.23973015E-07 -.25933039E-07 -.27679077E-07 -.29198125E-07 -.30479028E-07 -.31512564E-07 -.32291502E-07 -.32810648E-07 -.33066883E-07 -.33059167E-07 -.32788546E-07 -.32258130E-07 -.31473058E-07 -.30440450E-07 -.29169342E-07 -.27670607E-07 -.25956858E-07 -.24042349E-07 -.21942849E-07 -.19675514E-07 -.17258751E-07 -.14712064E-07 -.12055899E-07 -.93114809E-08 -.65006434E-08 -.36456576E-08 -.76905595E-09 .21065446E-08 .49586189E-08 .77649082E-08 .10503593E-07 .13153461E-07 .15694069E-07 .18105899E-07 .20370507E-07 .22470662E-07 24.7554104503838985 T Non local Part 0 2 1.19823013906127396 1.10994077959183524 1.53342233373160219 1.53342233373160219 -0.291376959654070899 Reciprocal Space Part .41916247E+01 .41825847E+01 .41555387E+01 .41107084E+01 .40484610E+01 .39693053E+01 .38738873E+01 .37629841E+01 .36374959E+01 .34984375E+01 .33469290E+01 .31841841E+01 .30114991E+01 .28302395E+01 .26418272E+01 .24477262E+01 .22494282E+01 .20484379E+01 .18462583E+01 .16443755E+01 .14442443E+01 .12472735E+01 .10548126E+01 .86813848E+00 .68844301E+00 .51682202E+00 .35426518E+00 .20164722E+00 .59720666E-01 -.70890044E-01 -.18969273E+00 -.29633001E+00 -.39058015E+00 -.47235620E+00 -.54170338E+00 -.59879486E+00 -.64392596E+00 -.67750676E+00 -.70005339E+00 -.71217809E+00 -.71457813E+00 -.70802382E+00 -.69334585E+00 -.67142204E+00 -.64316388E+00 -.60950289E+00 -.57137716E+00 -.52971824E+00 -.48543852E+00 -.43941937E+00 -.39250026E+00 -.34546882E+00 -.29905223E+00 -.25390984E+00 -.21062725E+00 -.16971183E+00 -.13158971E+00 -.96604303E-01 -.65016283E-01 -.37004945E-01 -.12670925E-01 .79598551E-02 .24931149E-01 .38350371E-01 .48381788E-01 .55239058E-01 .59177307E-01 .60484919E-01 .59475206E-01 .56478136E-01 .51832277E-01 .45877121E-01 .38945906E-01 .31359071E-01 .23418444E-01 .15402235E-01 .75609010E-02 .11392130E-03 -.67525066E-02 -.12886855E-01 -.18172761E-01 -.22528680E-01 -.25906755E-01 -.28290977E-01 -.29694738E-01 -.30157854E-01 -.29743190E-01 -.28532968E-01 -.26624897E-01 -.24128204E-01 -.21159697E-01 -.17839940E-01 -.14289626E-01 -.10626249E-01 -.69611057E-02 -.33967125E-02 -.24653651E-04 .30761027E-02 .58404133E-02 .82176957E-02 Real Space Part -.12209911E+02 -.12156465E+02 -.11996746E+02 -.11732600E+02 -.11367080E+02 -.10904404E+02 -.10349903E+02 -.97099514E+01 -.89918873E+01 -.82039151E+01 -.73550000E+01 -.64547502E+01 -.55132907E+01 -.45411287E+01 -.35490140E+01 -.25477947E+01 -.15482719E+01 -.56105360E+00 .40358764E+00 .13358530E+01 .22265484E+01 .30672055E+01 .38501921E+01 .45688082E+01 .52173671E+01 .57912593E+01 .62869985E+01 .67022486E+01 .70358309E+01 .72877116E+01 .74589701E+01 .75517488E+01 .75691844E+01 .75153242E+01 .73950278E+01 .72138561E+01 .69779520E+01 .66939128E+01 .63686597E+01 .60093047E+01 .56230197E+01 .52169103E+01 .47978951E+01 .43725954E+01 .39472355E+01 .35275565E+01 .31187441E+01 .27253720E+01 .23513613E+01 .19999558E+01 .16737134E+01 .13745126E+01 .11035728E+01 .86148821E+00 .64827189E+00 .46341029E+00 .30592455E+00 .17443747E+00 .67243739E-01 -.17618413E-01 -.82296239E-01 -.12905384E+00 -.16020751E+00 -.17806636E+00 -.18487943E+00 -.18279001E+00 -.17379778E+00 -.15972907E+00 -.14221522E+00 -.12267879E+00 -.10232730E+00 -.82153699E-01 -.62942943E-01 -.45283648E-01 -.29583985E-01 -.16090730E-01 -.49105123E-02 .39677126E-02 .10649843E-01 .15314281E-01 .18190739E-01 .19540772E-01 .19640479E-01 .18765672E-01 .17179704E-01 .15123994E-01 .12811214E-01 .10420974E-01 .80977811E-02 .59509921E-02 .40564286E-02 .24593019E-02 .11780974E-02 .20907384E-03 -.46894317E-03 -.88975727E-03 -.10952287E-02 -.11311262E-02 -.10435471E-02 -.87599685E-03 Reciprocal Space Part .74573153E+01 .74205324E+01 .73105035E+01 .71281866E+01 .68751723E+01 .65536755E+01 .61665220E+01 .57171327E+01 .52095018E+01 .46481714E+01 .40382008E+01 .33851306E+01 .26949407E+01 .19740037E+01 .12290314E+01 .46701580E+00 -.30483477E+00 -.10791659E+01 -.18485513E+01 -.26055719E+01 -.33428971E+01 -.40533700E+01 -.47300925E+01 -.53665105E+01 -.59564989E+01 -.64944419E+01 -.69753105E+01 -.73947331E+01 -.77490593E+01 -.80354149E+01 -.82517461E+01 -.83968535E+01 -.84704128E+01 -.84729835E+01 -.84060025E+01 -.82717655E+01 -.80733934E+01 -.78147852E+01 -.75005585E+01 -.71359771E+01 -.67268679E+01 -.62795286E+01 -.58006267E+01 -.52970927E+01 -.47760092E+01 -.42444981E+01 -.37096071E+01 -.31781994E+01 -.26568473E+01 -.21517323E+01 -.16685537E+01 -.12124471E+01 -.78791534E+00 -.39877098E+00 -.48094094E-01 .26179610E+00 .52935445E+00 .75380808E+00 .93513994E+00 .10740583E+01 .11719530E+01 .12308401E+01 .12532955E+01 .12423801E+01 .12015583E+01 .11346105E+01 .10455433E+01 .93849855E+00 .81766341E+00 .68718315E+00 .55107898E+00 .41317216E+00 .27701602E+00 .14583714E+00 .22486520E-01 -.90598413E-01 -.19142056E+00 -.27843862E+00 -.35057128E+00 -.40719064E+00 -.44810548E+00 -.47353521E+00 -.48407567E+00 -.48065789E+00 -.46450122E+00 -.43706235E+00 -.39998148E+00 -.35502741E+00 -.30404270E+00 -.24889052E+00 -.19140434E+00 -.13334157E+00 -.76342240E-01 -.21893397E-01 .28700093E-01 .74337975E-01 .11414004E+00 .14745461E+00 .17386013E+00 .19316046E+00 Real Space Part -.14450582E+03 -.14434158E+03 -.14384692E+03 -.14301613E+03 -.14184006E+03 -.14030674E+03 -.13840209E+03 -.13611089E+03 -.13341784E+03 -.13030866E+03 -.12677136E+03 -.12279734E+03 -.11838257E+03 -.11352859E+03 -.10824339E+03 -.10254210E+03 -.96447492E+02 -.89990226E+02 -.83208815E+02 -.76149381E+02 -.68865127E+02 -.61415564E+02 -.53865525E+02 -.46283974E+02 -.38742660E+02 -.31314650E+02 -.24072789E+02 -.17088132E+02 -.10428398E+02 -.41564905E+01 .16708644E+01 .70043321E+01 .11802990E+02 .16035133E+02 .19678836E+02 .22722270E+02 .25163755E+02 .27011560E+02 .28283456E+02 .29006050E+02 .29213914E+02 .28948539E+02 .28257163E+02 .27191494E+02 .25806374E+02 .24158431E+02 .22304747E+02 .20301581E+02 .18203183E+02 .16060736E+02 .13921425E+02 .11827682E+02 .98165975E+01 .79195094E+01 .61617801E+01 .45627407E+01 .31358031E+01 .18887196E+01 .82397384E+00 -.60720401E-01 -.77183450E+00 -.13193800E+01 -.17162274E+01 -.19774128E+01 -.21194552E+01 -.21597028E+01 -.21157294E+01 -.20047908E+01 -.18433559E+01 -.16467180E+01 -.14286910E+01 -.12013912E+01 -.97510211E+00 -.75821818E+00 -.55725868E+00 -.37694436E+00 -.22032548E+00 -.88950652E-01 .16934939E-01 .98173080E-01 .15646828E+00 .19416536E+00 .21403714E+00 .21908924E+00 .21238723E+00 .19691002E+00 .17543163E+00 .15043210E+00 .12403694E+00 .97983416E-01 .73610913E-01 .51872133E-01 .33361169E-01 .18354475E-01 .68606192E-02 -.13250790E-02 -.65645922E-02 -.93230150E-02 -.10118734E-01 -.94798863E-02 Non local Part 1 2 1.19823013906127396 6.12884028017874360 -3.81892483499089330 -3.81892483499089330 1.42081284536133179 Reciprocal Space Part .00000000E+00 .24190713E+00 .48134296E+00 .71587281E+00 .94313460E+00 .11608735E+01 .13669746E+01 .15594931E+01 .17366816E+01 .18970136E+01 .20392032E+01 .21622207E+01 .22653035E+01 .23479626E+01 .24099842E+01 .24514270E+01 .24726145E+01 .24741237E+01 .24567692E+01 .24215837E+01 .23697959E+01 .23028052E+01 .22221538E+01 .21294985E+01 .20265799E+01 .19151923E+01 .17971534E+01 .16742740E+01 .15483304E+01 .14210370E+01 .12940221E+01 .11688056E+01 .10467802E+01 .92919538E+00 .81714463E+00 .71155640E+00 .61318834E+00 .52262508E+00 .44027930E+00 .36639596E+00 .30105950E+00 .24420362E+00 .19562346E+00 .15498971E+00 .12186422E+00 .95716908E-01 .75943293E-01 .61882440E-01 .52834833E-01 .48079811E-01 .46892228E-01 .48558017E-01 .52388387E-01 .57732421E-01 .63987899E-01 .70610211E-01 .77119283E-01 .83104495E-01 .88227596E-01 .92223688E-01 .94900397E-01 .96135352E-01 .95872176E-01 .94115169E-01 .90922917E-01 .86401051E-01 .80694419E-01 .73978879E-01 .66452981E-01 .58329740E-01 .49828715E-01 .41168581E-01 .32560350E-01 .24201382E-01 .16270280E-01 .89227536E-02 .22884849E-02 -.35309816E-02 -.84633498E-02 -.12465719E-01 -.15523834E-01 -.17650532E-01 -.18883476E-01 -.19282310E-01 -.18925339E-01 -.17905890E-01 -.16328465E-01 -.14304828E-01 -.11950138E-01 -.93792522E-02 -.67032934E-02 -.40265698E-02 -.14439170E-02 .96148255E-03 .31197699E-02 .49755497E-02 .64885011E-02 .76334748E-02 .84001065E-02 .87919916E-02 Real Space Part .00000000E+00 .79674956E+00 .15859159E+01 .23600635E+01 .31120483E+01 .38351532E+01 .45232120E+01 .51707187E+01 .57729178E+01 .63258763E+01 .68265322E+01 .72727217E+01 .76631830E+01 .79975380E+01 .82762527E+01 .85005780E+01 .86724745E+01 .87945214E+01 .88698160E+01 .89018646E+01 .88944696E+01 .88516162E+01 .87773614E+01 .86757301E+01 .85506195E+01 .84057148E+01 .82444190E+01 .80697972E+01 .78845365E+01 .76909225E+01 .74908310E+01 .72857355E+01 .70767279E+01 .68645513E+01 .66496437E+01 .64321882E+01 .62121700E+01 .59894356E+01 .57637521E+01 .55348655E+01 .53025546E+01 .50666788E+01 .48272185E+01 .45843073E+01 .43382543E+01 .40895568E+01 .38389031E+01 .35871659E+01 .33353872E+01 .30847548E+01 .28365735E+01 .25922301E+01 .23531559E+01 .21207871E+01 .18965247E+01 .16816961E+01 .14775193E+01 .12850711E+01 .11052602E+01 .93880647E+00 .78622548E+00 .64782090E+00 .52368250E+00 .41369091E+00 .31752808E+00 .23469302E+00 .16452201E+00 .10621225E+00 .58848150E-01 .21429047E-01 -.71024369E-02 -.27832509E-01 -.41849597E-01 -.50219785E-01 -.53964937E-01 -.54044003E-01 -.51337836E-01 -.46637720E-01 -.40637642E-01 -.33930212E-01 -.27006003E-01 -.20256005E-01 -.13976760E-01 -.83777375E-02 -.35904248E-02 .32136120E-03 .33504644E-02 .55351505E-02 .69480767E-02 .76858459E-02 .78594557E-02 .75858795E-02 .69809449E-02 .61535968E-02 .52015693E-02 .42084251E-02 .32418692E-02 .23532017E-02 .15777427E-02 .93604221E-03 Reciprocal Space Part .00000000E+00 .31744093E+00 .62796632E+00 .92479987E+00 .12014407E+01 .14517937E+01 .16702913E+01 .18520039E+01 .19927369E+01 .20891120E+01 .21386315E+01 .21397237E+01 .20917694E+01 .19951083E+01 .18510259E+01 .16617203E+01 .14302515E+01 .11604730E+01 .85694736E+00 .52484880E+00 .16985417E+00 -.20197520E+00 -.58431776E+00 -.97071968E+00 -.13547235E+01 -.17299949E+01 -.20904447E+01 -.24303437E+01 -.27444280E+01 -.30279929E+01 -.32769731E+01 -.34880080E+01 -.36584915E+01 -.37866046E+01 -.38713313E+01 -.39124572E+01 -.39105517E+01 -.38669350E+01 -.37836290E+01 -.36632969E+01 -.35091693E+01 -.33249628E+01 -.31147888E+01 -.28830588E+01 -.26343861E+01 -.23734858E+01 -.21050774E+01 -.18337905E+01 -.15640757E+01 -.13001231E+01 -.10457895E+01 -.80453601E+00 -.57937641E+00 -.37283792E+00 -.18693396E+00 -.23149557E-01 .11756098E+00 .23476454E+00 .32852852E+00 .39939002E+00 .44831599E+00 .47665573E+00 .48608716E+00 .47855846E+00 .45622663E+00 .42139471E+00 .37644900E+00 .32379812E+00 .26581491E+00 .20478287E+00 .14284783E+00 .81976051E-01 .23919311E-01 -.29812460E-01 -.77970740E-01 -.11958010E+00 -.15394216E+00 -.18063212E+00 -.19948839E+00 -.21059606E+00 -.21426485E+00 -.21100257E+00 -.20148507E+00 -.18652355E+00 -.16703047E+00 -.14398496E+00 -.11839869E+00 -.91283257E-01 -.63619700E-01 -.36331110E-01 -.10258728E-01 .13857887E-01 .35396331E-01 .53862293E-01 .68895888E-01 .80273504E-01 .87905366E-01 .91829151E-01 .92200087E-01 .89278037E-01 Real Space Part .00000000E+00 -.20833035E+01 -.41655263E+01 -.62451081E+01 -.83195511E+01 -.10385006E+02 -.12435921E+02 -.14464767E+02 -.16461863E+02 -.18415296E+02 -.20310962E+02 -.22132707E+02 -.23862587E+02 -.25481222E+02 -.26968246E+02 -.28302832E+02 -.29464273E+02 -.30432608E+02 -.31189254E+02 -.31717642E+02 -.32003813E+02 -.32036975E+02 -.31809978E+02 -.31319701E+02 -.30567341E+02 -.29558576E+02 -.28303611E+02 -.26817098E+02 -.25117923E+02 -.23228879E+02 -.21176227E+02 -.18989155E+02 -.16699160E+02 -.14339360E+02 -.11943772E+02 -.95465606E+01 -.71812913E+01 -.48802088E+01 -.26735552E+01 -.58895310E+00 .13491329E+01 .31198413E+01 .47062558E+01 .60956367E+01 .72795389E+01 .82538163E+01 .90185169E+01 .95776756E+01 .99390140E+01 .10113561E+02 .10115209E+02 .99602166E+01 .96666821E+01 .92540003E+01 .87423176E+01 .81520050E+01 .75031602E+01 .68151530E+01 .61062235E+01 .53931413E+01 .46909323E+01 .40126745E+01 .33693654E+01 .27698580E+01 .22208628E+01 .17270086E+01 .12909577E+01 .91356460E+00 .59407062E+00 .33032511E+00 .11902304E+00 -.44049687E-01 -.16377201E+00 -.24545238E+00 -.29460892E+00 -.31677078E+00 -.31730480E+00 -.30127048E+00 -.27330483E+00 -.23753750E+00 -.19753537E+00 -.15627485E+00 -.11613935E+00 -.78938581E-01 -.45946163E-01 -.17951420E-01 .46784902E-02 .21930096E-01 .34072423E-01 .41586401E-01 .45097684E-01 .45315224E-01 .42977316E-01 .38806326E-01 .33472725E-01 .27568557E-01 .21590035E-01 .15928553E-01 .10869144E-01 .65951677E-02 PAW radial sets 321 0.721520152002725790 (5E20.12) augmentation charges (non sperical) -.157752259102E+00 .256865056813E-01 .447401437060E-01 .282550287931E-02 .256865056813E-01 -.513111026050E-02 -.610189826978E-02 .234333105778E-03 .447401437060E-01 -.610189826978E-02 .206642369840E+00 -.512388802954E-01 .282550287931E-02 .234333105778E-03 -.512388802954E-01 .161404628631E-01 uccopancies in atom .199999999995E+01 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .133333333287E+01 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 grid .292861757568E-04 .302384891324E-04 .312217693632E-04 .322370234141E-04 .332852909940E-04 .343676456204E-04 .354851957192E-04 .366390857593E-04 .378304974248E-04 .390606508255E-04 .403308057460E-04 .416422629358E-04 .429963654417E-04 .443944999831E-04 .458380983718E-04 .473286389788E-04 .488676482478E-04 .504567022590E-04 .520974283424E-04 .537915067449E-04 .555406723508E-04 .573467164586E-04 .592114886153E-04 .611368985105E-04 .631249179321E-04 .651775827859E-04 .672969951799E-04 .694853255777E-04 .717448150208E-04 .740777774238E-04 .764866019442E-04 .789737554287E-04 .815417849398E-04 .841933203642E-04 .869310771058E-04 .897578588667E-04 .926765605186E-04 .956901710669E-04 .988017767123E-04 .102014564011E-03 .105331823137E-03 .108756951255E-03 .112293455994E-03 .115944959045E-03 .119715199866E-03 .123608039513E-03 .127627464593E-03 .131777591350E-03 .136062669876E-03 .140487088466E-03 .145055378110E-03 .149772217137E-03 .154642436003E-03 .159671022236E-03 .164863125548E-03 .170224063108E-03 .175759324983E-03 .181474579766E-03 .187375680376E-03 .193468670057E-03 .199759788562E-03 .206255478546E-03 .212962392164E-03 .219887397881E-03 .227037587508E-03 .234420283464E-03 .242043046275E-03 .249913682317E-03 .258040251807E-03 .266431077064E-03 .275094751026E-03 .284040146052E-03 .293276423008E-03 .302813040649E-03 .312659765305E-03 .322826680882E-03 .333324199190E-03 .344163070606E-03 .355354395080E-03 .366909633507E-03 .378840619461E-03 .391159571315E-03 .403879104750E-03 .417012245681E-03 .430572443592E-03 .444573585311E-03 .459030009230E-03 .473956519990E-03 .489368403644E-03 .505281443305E-03 .521711935319E-03 .538676705943E-03 .556193128586E-03 .574279141596E-03 .592953266629E-03 .612234627622E-03 .632142970374E-03 .652698682767E-03 .673922815646E-03 .695837104379E-03 .718463991113E-03 .741826647755E-03 .765948999709E-03 .790855750370E-03 .816572406429E-03 .843125303987E-03 .870541635532E-03 .898849477784E-03 .928077820446E-03 .958256595896E-03 .989416709837E-03 .102159007295E-02 .105480963356E-02 .108910941142E-02 .112452453248E-02 .116109126493E-02 .119884705630E-02 .123783057181E-02 .127808173400E-02 .131964176357E-02 .136255322161E-02 .140686005323E-02 .145260763247E-02 .149984280887E-02 .154861395536E-02 .159897101787E-02 .165096556643E-02 .170465084799E-02 .176008184098E-02 .181731531158E-02 .187640987187E-02 .193742603983E-02 .200042630136E-02 .206547517423E-02 .213263927416E-02 .220198738308E-02 .227359051949E-02 .234752201127E-02 .242385757072E-02 .250267537214E-02 .258405613183E-02 .266808319080E-02 .275484260011E-02 .284442320898E-02 .293691675577E-02 .303241796195E-02 .313102462912E-02 .323283773910E-02 .333796155744E-02 .344650374009E-02 .355857544374E-02 .367429143961E-02 .379377023099E-02 .391713417460E-02 .404450960591E-02 .417602696847E-02 .431182094758E-02 .445203060811E-02 .459679953703E-02 .474627599036E-02 .490061304506E-02 .505996875575E-02 .522450631661E-02 .539439422848E-02 .556980647142E-02 .575092268290E-02 .593792834175E-02 .613101495811E-02 .633038026953E-02 .653622844353E-02 .674877028662E-02 .696822346022E-02 .719481270355E-02 .742877006381E-02 .767033513377E-02 .791975529717E-02 .817728598207E-02 .844319092237E-02 .871774242798E-02 .900122166363E-02 .929391893683E-02 .959613399516E-02 .990817633326E-02 .102303655097E-01 .105630314745E-01 .109065149065E-01 .112611675628E-01 .116273526388E-01 .120054451399E-01 .123958322659E-01 .127989138074E-01 .132151025550E-01 .136448247225E-01 .140885203828E-01 .145466439191E-01 .150196644899E-01 .155080665096E-01 .160123501446E-01 .165330318254E-01 .170706447755E-01 .176257395575E-01 .181988846371E-01 .187906669648E-01 .194016925775E-01 .200325872188E-01 .206839969800E-01 .213565889615E-01 .220510519564E-01 .227680971554E-01 .235084588754E-01 .242728953116E-01 .250621893137E-01 .258771491876E-01 .267186095236E-01 .275874320505E-01 .284845065186E-01 .294107516104E-01 .303671158820E-01 .313545787337E-01 .323741514141E-01 .334268780544E-01 .345138367389E-01 .356361406081E-01 .367949389994E-01 .379914186235E-01 .392268047802E-01 .405023626127E-01 .418193984038E-01 .431792609133E-01 .445833427591E-01 .460330818438E-01 .475299628269E-01 .490755186453E-01 .506713320832E-01 .523190373930E-01 .540203219690E-01 .557769280752E-01 .575906546298E-01 .594633590472E-01 .613969591405E-01 .633934350851E-01 .654548314468E-01 .675832592756E-01 .697808982676E-01 .720499989972E-01 .743928852218E-01 .768119562617E-01 .793096894569E-01 .818886427046E-01 .845514570782E-01 .873008595323E-01 .901396656953E-01 .930707827527E-01 .960972124246E-01 .992220540394E-01 .102448507708E+00 .105779877601E+00 .109219575332E+00 .112771123452E+00 .116438159057E+00 .120224437512E+00 .124133836297E+00 .128170358977E+00 .132338139305E+00 .136641445452E+00 .141084684380E+00 .145672406352E+00 .150409309599E+00 .155300245122E+00 .160350221666E+00 .165564410850E+00 .170948152458E+00 .176506959912E+00 .182246525918E+00 .188172728291E+00 .194291635982E+00 .200609515285E+00 .207132836263E+00 .213868279365E+00 .220822742274E+00 .228003346967E+00 .235417447012E+00 .243072635094E+00 .250976750795E+00 .259137888621E+00 .267564406289E+00 .276264933290E+00 .285248379723E+00 .294523945424E+00 .304101129382E+00 .313989739470E+00 .324199902489E+00 .334742074538E+00 .345627051723E+00 .356865981211E+00 .368470372648E+00 .380452109945E+00 .392823463449E+00 .405597102506E+00 .418786108438E+00 .432403987941E+00 .446464686913E+00 .460982604738E+00 .475972609033E+00 .491450050872E+00 .507430780509E+00 .523931163606E+00 .540968097998E+00 .558559030995E+00 .576721977248E+00 .595475537203E+00 .614838916143E+00 .634831943861E+00 .655475094963E+00 .676789509841E+00 .698797016317E+00 .721520152003E+00 .744982187373E+00 .769207149603E+00 .794219847171E+00 .820045895265E+00 aepotential .344620864381E+05 .335729348910E+05 .326607094679E+05 .317298527617E+05 .307850610750E+05 .298308294196E+05 .288714423118E+05 .279109409932E+05 .269531004174E+05 .260014122025E+05 .250590723857E+05 .241289743073E+05 .232137061556E+05 .223155526546E+05 .214365006885E+05 .205782481780E+05 .197422158561E+05 .189295613384E+05 .181411950859E+05 .173777977152E+05 .166398382559E+05 .159275929117E+05 .152411639803E+05 .145804985929E+05 .139454070005E+05 .133355801830E+05 .127506065798E+05 .121899878290E+05 .116531533851E+05 .111394739797E+05 .106482738762E+05 .101788419327E+05 .973044147139E+04 .930231902072E+04 .889371196167E+04 .850385516385E+04 .813198665588E+04 .777735243911E+04 .743921050565E+04 .711683412068E+04 .680951449358E+04 .651656285928E+04 .623731207683E+04 .597111778273E+04 .571735918511E+04 .547543952008E+04 .524478624895E+04 .502485103028E+04 .481510949625E+04 .461506088322E+04 .442422753164E+04 .424215429199E+04 .406840786784E+04 .390257606950E+04 .374426708320E+04 .359310864864E+04 .344874729194E+04 .331084749161E+04 .317909090091E+04 .305317553308E+04 .293281500979E+04 .281773778683E+04 .270768642593E+04 .260241688250E+04 .250169782385E+04 .240530996858E+04 .231304545700E+04 .222470724985E+04 .214010855063E+04 .205907226117E+04 .198143045752E+04 .190702389788E+04 .183570154950E+04 .176732014469E+04 .170174376187E+04 .163884341822E+04 .157849670118E+04 .152058740347E+04 .146500519043E+04 .141164527724E+04 .136040813035E+04 .131119918080E+04 .126392855649E+04 .121851082761E+04 .117486476841E+04 .113291313152E+04 .109258243223E+04 .105380275072E+04 .101650753965E+04 .980633446472E+03 .946120143433E+03 .912910169256E+03 .880948776621E+03 .850183792788E+03 .820565482959E+03 .792046425154E+03 .764581390092E+03 .738127227908E+03 .712642762779E+03 .688088691006E+03 .664427485954E+03 .641623309210E+03 .619641924627E+03 .598450617897E+03 .578018121645E+03 .558314542462E+03 .539311293781E+03 .520981031521E+03 .503297592970E+03 .486235939917E+03 .469772103352E+03 .453883132589E+03 .438547046213E+03 .423742785978E+03 .409450172651E+03 .395649864932E+03 .382323319715E+03 .369452755171E+03 .357021114941E+03 .345012034961E+03 .333409811120E+03 .322199369640E+03 .311366237899E+03 .300896517183E+03 .290776857231E+03 .280994431097E+03 .271536912121E+03 .262392451581E+03 .253549657589E+03 .244997574942E+03 .236725666004E+03 .228723792657E+03 .220982198738E+03 .213491493677E+03 .206242636794E+03 .199226922258E+03 .192435964878E+03 .185861686483E+03 .179496302942E+03 .173332311815E+03 .167362480543E+03 .161579835190E+03 .155977649674E+03 .150549435529E+03 .145288932112E+03 .140190097209E+03 .135247098073E+03 .130454302933E+03 .125806272739E+03 .121297753428E+03 .116923668358E+03 .112679111224E+03 .108559339155E+03 .104559766209E+03 .100675957051E+03 .969036209796E+02 .932386061771E+02 .896768941581E+02 .862145945364E+02 .828479399394E+02 .795732811790E+02 .763870825897E+02 .732859175903E+02 .702664644175E+02 .673255020247E+02 .644599061844E+02 .616666457159E+02 .589427788941E+02 .562854499948E+02 .536918860003E+02 .511593934268E+02 .486853553017E+02 .462672282535E+02 .439025397420E+02 .415888854025E+02 .393239265054E+02 .371053875305E+02 .349310538513E+02 .327987695257E+02 .307064351866E+02 .286520060380E+02 .266334899472E+02 .246489456285E+02 .226964809271E+02 .207742511855E+02 .188804577096E+02 .170133463090E+02 .151712059355E+02 .133523673943E+02 .115552021482E+02 .977812119341E+01 .801957401914E+01 .627804764882E+01 .455206574938E+01 .284018782908E+01 .114100849772E+01 -.546843190099E+00 -.222470432416E+01 -.389387865170E+01 -.555563702498E+01 -.721121777413E+01 -.886182701424E+01 -.105086388850E+02 -.121527957221E+02 -.137954081656E+02 -.154375552027E+02 -.170802841491E+02 -.187246105688E+02 -.203715181315E+02 -.220219584159E+02 -.236768506503E+02 -.253370814013E+02 -.270035042054E+02 -.286769391470E+02 -.303581723845E+02 -.320479556231E+02 -.337470055368E+02 -.354560031382E+02 -.371755930961E+02 -.389063829998E+02 -.406489425672E+02 -.424038027938E+02 -.441714550387E+02 -.459523500399E+02 -.477468968516E+02 -.495554616915E+02 -.513783666850E+02 -.532158884890E+02 -.550682567708E+02 -.569356525179E+02 -.588182061426E+02 -.607159953416E+02 -.626290426590E+02 -.645573126945E+02 -.665007088812E+02 -.684590697493E+02 -.704321645699E+02 -.724196882588E+02 -.744212553972E+02 -.764363932049E+02 -.784645332739E+02 -.805050018497E+02 -.825570084189E+02 -.846196323419E+02 -.866918072559E+02 -.887723029672E+02 -.908597045751E+02 -.929523886095E+02 -.950484960626E+02 -.971459023431E+02 -.992421844218E+02 -.101334585782E+03 -.103419980279E+03 -.105494836659E+03 -.107555186343E+03 -.109596598129E+03 -.111614164704E+03 -.113602507280E+03 -.115555806133E+03 -.117467866281E+03 -.119332228743E+03 -.121142338730E+03 -.122891782384E+03 -.124574603359E+03 -.126185709187E+03 -.127721375786E+03 -.129179849068E+03 -.130562037348E+03 -.131872249654E+03 -.133118881188E+03 -.134314825072E+03 -.135477192987E+03 -.136625659703E+03 -.137778518637E+03 -.138945648412E+03 -.140118549526E+03 -.141259817826E+03 -.142297364032E+03 -.143130166505E+03 -.143649392083E+03 -.143770896700E+03 -.143466650444E+03 -.142779438341E+03 -.141810639779E+03 -.140684648871E+03 -.139508468373E+03 -.138347629848E+03 -.137225671915E+03 -.136138333179E+03 -.135069529969E+03 -.134002012204E+03 -.132922043139E+03 -.131820225779E+03 -.130690626727E+03 -.129529519065E+03 -.128334338388E+03 -.127103016727E+03 -.125833658340E+03 -.124524453614E+03 -.123173726082E+03 -.121780032930E+03 -.120342269386E+03 -.118859752079E+03 -.117332272953E+03 -.115760124514E+03 -.114144101237E+03 -.112485482930E+03 -.110786005302E+03 -.109047821948E+03 -.107273460804E+03 -.105465777240E+03 -.103627905226E+03 -.101763207541E+03 -.998752256539E+02 -.979676297084E+02 -.960441689068E+02 -.941086224963E+02 -.921647514802E+02 -.902162518570E+02 -.882667076453E+02 -.863195480576E+02 core charge-density .625549835994E-05 .666800504134E-05 .710770694600E-05 .757639628637E-05 .807598331802E-05 .860850410778E-05 .917612881239E-05 .978117050118E-05 .104260945584E-04 .111135287033E-04 .118462736682E-04 .126273145781E-04 .134598330771E-04 .143472202518E-04 .152930904017E-04 .163012957151E-04 .173759419064E-04 .185214048808E-04 .197423484910E-04 .210437434593E-04 .224308875404E-04 .239094270056E-04 .254853795358E-04 .271651586146E-04 .289555995192E-04 .308639870146E-04 .328980848607E-04 .350661672522E-04 .373770523150E-04 .398401377963E-04 .424654390887E-04 .452636297410E-04 .482460846186E-04 .514249258846E-04 .548130719857E-04 .584242898380E-04 .622732504215E-04 .663755880027E-04 .707479632232E-04 .754081303033E-04 .803750086285E-04 .856687590020E-04 .913108648668E-04 .973242188169E-04 .103733214742E-03 .110563845969E-03 .117843809786E-03 .125602618763E-03 .133871719311E-03 .142684617931E-03 .152077015675E-03 .162086951316E-03 .172754953815E-03 .184124204661E-03 .196240710731E-03 .209153488342E-03 .222914759203E-03 .237580159043E-03 .253208959714E-03 .269864305635E-03 .287613465490E-03 .306528100151E-03 .326684547867E-03 .348164127795E-03 .371053463070E-03 .395444824619E-03 .421436497058E-03 .449133168056E-03 .478646342645E-03 .510094784058E-03 .543604982759E-03 .579311655433E-03 .617358275824E-03 .657897639406E-03 .701092464009E-03 .747116028632E-03 .796152852835E-03 .848399419223E-03 .904064941684E-03 .963372182234E-03 .102655831945E-02 .109387587165E-02 .116559367828E-02 .124199794286E-02 .132339334157E-02 .141010420110E-02 .150247575032E-02 .160087545001E-02 .170569440540E-02 .181734886664E-02 .193628182230E-02 .206296469151E-02 .219789912070E-02 .234161889100E-02 .249469194297E-02 .265772252544E-02 .283135347583E-02 .301626863953E-02 .321319543645E-02 .342290758323E-02 .364622797998E-02 .388403177110E-02 .413724958987E-02 .440687099725E-02 .469394812583E-02 .499959954031E-02 .532501432642E-02 .567145642088E-02 .604026919554E-02 .643288030937E-02 .685080684263E-02 .729566072830E-02 .776915449617E-02 .827310734610E-02 .880945156718E-02 .938023932048E-02 .998764980358E-02 .106339968159E-01 .113217367443E-01 .120534769893E-01 .128319848529E-01 .136601969090E-01 .145412288792E-01 .154783860366E-01 .164751741595E-01 .175353110613E-01 .186627387172E-01 .198616360155E-01 .211364321554E-01 .224918207178E-01 .239327744331E-01 .254645606710E-01 .270927576767E-01 .288232715768E-01 .306623541799E-01 .326166215923E-01 .346930736722E-01 .368991143409E-01 .392425727696E-01 .417317254593E-01 .443753192252E-01 .471825950990E-01 .501633131551E-01 .533277782643E-01 .566868667757E-01 .602520541187E-01 .640354433157E-01 .680497943852E-01 .723085546110E-01 .768258896433E-01 .816167153881E-01 .866967306317E-01 .920824503355E-01 .977912395230E-01 .103841347667E+00 .110251943473E+00 .117043149927E+00 .124236079476E+00 .131852869168E+00 .139916715573E+00 .148451909274E+00 .157483868688E+00 .167039172970E+00 .177145593679E+00 .187832124907E+00 .199129011493E+00 .211067774932E+00 .223681236533E+00 .237003537347E+00 .251070154350E+00 .265917912286E+00 .281584990564E+00 .298110924537E+00 .315536600407E+00 .333904243004E+00 .353257395572E+00 .373640890661E+00 .395100811173E+00 .417684440517E+00 .441440200801E+00 .466417577909E+00 .492667032246E+00 .520239893902E+00 .549188240900E+00 .579564759170E+00 .611422582830E+00 .644815113329E+00 .679795815970E+00 .716417992322E+00 .754734527020E+00 .794797607463E+00 .836658414955E+00 .880366785870E+00 .925970841497E+00 .973516585329E+00 .102304746666E+01 .107460390956E+01 .112822280638E+01 .118393697538E+01 .124177458210E+01 .130175852453E+01 .136390578269E+01 .142822673320E+01 .149472443039E+01 .156339385578E+01 .163422113833E+01 .170718274867E+01 .178224467121E+01 .185936155863E+01 .193847587451E+01 .201951703024E+01 .210240052383E+01 .218702708883E+01 .227328186302E+01 .236103358719E+01 .245013384581E+01 .254041636236E+01 .263169636304E+01 .272377002387E+01 .281641401710E+01 .290938517367E+01 .300242027945E+01 .309523602333E+01 .318752911609E+01 .327897659887E+01 .336923636007E+01 .345794787948E+01 .354473321719E+01 .362919826436E+01 .371093427085E+01 .378951966301E+01 .386452216249E+01 .393550121345E+01 .400201072252E+01 .406360211102E+01 .411982767477E+01 .417024424100E+01 .421441710619E+01 .425192423234E+01 .428236067202E+01 .430534318581E+01 .432051500785E+01 .432755070794E+01 .432616109105E+01 .431609806767E+01 .429715942168E+01 .426919339592E+01 .423210301053E+01 .418585002452E+01 .413045844838E+01 .406601751409E+01 .399268400981E+01 .391068388909E+01 .382031307013E+01 .372193734800E+01 .361599135397E+01 .350297650932E+01 .338345793746E+01 .325806031784E+01 .312746268671E+01 .299239221437E+01 .285361701458E+01 .271193806915E+01 .256818037860E+01 .242318347665E+01 .227779147070E+01 .213284279909E+01 .198915989658E+01 .184753899553E+01 .170874027411E+01 .157347856698E+01 .144241483371E+01 .131614854842E+01 .119521112569E+01 .108006043765E+01 .971076418067E+00 .868557721402E+00 .772719447114E+00 .683692073759E+00 .601521935591E+00 .526173696431E+00 .457535189769E+00 .395424650783E+00 .339599878201E+00 .289768462616E+00 .245598123128E+00 .206726459316E+00 .172769862786E+00 .143331658667E+00 .118009628694E+00 .964029802611E-01 .781187114291E-01 .627772595572E-01 .500173176187E-01 .394997339384E-01 .309104557903E-01 .239625219489E-01 .183971482330E-01 .139839814991E-01 .105206211709E-01 .783152347062E-02 .576641243399E-02 .419832401429E-02 .302140579039E-02 .214858584976E-02 .150921140926E-02 .104674188219E-02 .716563673537E-03 .483976205693E-03 .322381627428E-03 .211695211051E-03 .136980222199E-03 .873004178539E-04 .547754089416E-04 .338188194079E-04 .205362239785E-04 .122588804757E-04 .718986054261E-05 .414088618653E-05 .234058876995E-05 .129766794578E-05 kinetic energy-density .132176025795E+00 .133935190758E+00 .135761668823E+00 .137658262485E+00 .139627986720E+00 .141674035833E+00 .143799794426E+00 .146008844928E+00 .148304976284E+00 .150692193057E+00 .153174724964E+00 .155757037169E+00 .158443841093E+00 .161240106033E+00 .164151071593E+00 .167182260952E+00 .170339495149E+00 .173628908334E+00 .177056964154E+00 .180630473327E+00 .184356612448E+00 .188242944155E+00 .192297438694E+00 .196528496986E+00 .200944975290E+00 .205556211542E+00 .210372053444E+00 .215402888447E+00 .220659675688E+00 .226153980051E+00 .231898008388E+00 .237904648105E+00 .244187508236E+00 .250760963072E+00 .257640198646E+00 .264841262088E+00 .272381114163E+00 .280277685096E+00 .288549933816E+00 .297217911178E+00 .306302826851E+00 .315827120668E+00 .325814538349E+00 .336290211906E+00 .347280745353E+00 .358814305519E+00 .370920718749E+00 .383631573741E+00 .396980330632E+00 .411002437249E+00 .425735452489E+00 .441219177486E+00 .457495795227E+00 .474610018769E+00 .492609248970E+00 .511543742045E+00 .531466787872E+00 .552434899374E+00 .574508014020E+00 .597749707978E+00 .622227423754E+00 .648012712331E+00 .675181490499E+00 .703814314438E+00 .733996670649E+00 .765819285087E+00 .799378452009E+00 .834776383364E+00 .872121580296E+00 .911529228018E+00 .953121615574E+00 .997028581984E+00 .104338799046E+01 .109234623230E+01 .114405876274E+01 .119869066993E+01 .125641728002E+01 .131742479982E+01 .138191099985E+01 .145008593986E+01 .152217273989E+01 .159840839916E+01 .167904466597E+01 .176434896181E+01 .185460536262E+01 .195011564109E+01 .205120037326E+01 .215820011361E+01 .227147664259E+01 .239141429086E+01 .251842134511E+01 .265293153969E+01 .279540564002E+01 .294633312225E+01 .310623395535E+01 .327566049175E+01 .345519947206E+01 .364547415152E+01 .384714655437E+01 .406091986370E+01 .428754095473E+01 .452780307932E+01 .478254871036E+01 .505267255494E+01 .533912474579E+01 .564291422071E+01 .596511230019E+01 .630685647417E+01 .666935440928E+01 .705388818805E+01 .746181879232E+01 .789459084458E+01 .835373761891E+01 .884088633706E+01 .935776376336E+01 .990620211314E+01 .104881452909E+02 .111056554739E+02 .117609200576E+02 .124562589809E+02 .131941324473E+02 .139771490622E+02 .148080744026E+02 .156898400404E+02 .166255530370E+02 .176185059297E+02 .186721872297E+02 .197902924519E+02 .209767356968E+02 .222356618045E+02 .235714591012E+02 .249887727582E+02 .264925187826E+02 .280878986594E+02 .297804146618E+02 .315758858496E+02 .334804647683E+02 .355006548677E+02 .376433286489E+02 .399157465539E+02 .423255766040E+02 .448809147943E+02 .475903062448E+02 .504627671092E+02 .535078072330E+02 .567354535528E+02 .601562742178E+02 .637814034155E+02 .676225668666E+02 .716921079591E+02 .760030144672E+02 .805689458084E+02 .854042607667E+02 .905240456056E+02 .959441424815E+02 .101681178049E+03 .107752592143E+03 .114176666392E+03 .120972552609E+03 .128160300793E+03 .135760886523E+03 .143796237537E+03 .152289259245E+03 .161263858899E+03 .170744968109E+03 .180758563383E+03 .191331684306E+03 .202492448959E+03 .214270066138E+03 .226694843879E+03 .239798193771E+03 .253612630490E+03 .268171765933E+03 .283510297290E+03 .299663988351E+03 .316669643277E+03 .334565072038E+03 .353389046636E+03 .373181247220E+03 .393982197127E+03 .415833185818E+03 .438776178681E+03 .462853712577E+03 .488108776000E+03 .514584672670E+03 .542324867365E+03 .571372812760E+03 .601771756058E+03 .633564524166E+03 .666793286221E+03 .701499292269E+03 .737722586982E+03 .775501697325E+03 .814873293226E+03 .855871820381E+03 .898529104489E+03 .942873926389E+03 .988931567784E+03 .103672332747E+04 .108626600830E+04 .113757137544E+04 .119064558683E+04 .124548859720E+04 .130209353751E+04 .136044607208E+04 .142052373640E+04 .148229525921E+04 .154571987295E+04 .161074661763E+04 .167731364382E+04 .174534752129E+04 .181476256062E+04 .188546015605E+04 .195732815867E+04 .203024028995E+04 .210405560636E+04 .217861802691E+04 .225375593595E+04 .232928187445E+04 .240499233356E+04 .248066766472E+04 .255607212096E+04 .263095404408E+04 .270504621268E+04 .277806636514E+04 .284971791180E+04 .291969084901E+04 .298766288709E+04 .305330080234E+04 .311626202128E+04 .317619644332E+04 .323274850470E+04 .328555948400E+04 .333427004551E+04 .337852301282E+04 .341796636105E+04 .345225641087E+04 .348106120307E+04 .350406402702E+04 .352096707125E+04 .353149515895E+04 .353539952622E+04 .353246159564E+04 .352249669327E+04 .350535765276E+04 .348093824682E+04 .344917638314E+04 .341005700022E+04 .336361459689E+04 .330993533011E+04 .324915861635E+04 .318147817463E+04 .310714245333E+04 .302645438806E+04 .293977044482E+04 .284749891086E+04 .275009740545E+04 .264806959424E+04 .254196110373E+04 .243235464705E+04 .231986438895E+04 .220512959614E+04 .208880763954E+04 .197156643697E+04 .185407644573E+04 .173700236837E+04 .162099461974E+04 .150668097393E+04 .139465831045E+04 .128548489127E+04 .117967334783E+04 .107768468195E+04 .979923607561E+03 .886735573996E+03 .798405745392E+03 .715159972906E+03 .637167313519E+03 .564542994768E+03 .497350259215E+03 .435599806459E+03 .379246858276E+03 .328187667685E+03 .282258420739E+03 .241239058244E+03 .204862611625E+03 .172828208383E+03 .144814513432E+03 .120490951119E+03 .995258554820E+02 .815921605138E+02 .663716392437E+02 .535583897932E+02 .428618420638E+02 .340093008571E+02 .267479559883E+02 .208462991666E+02 .160949283081E+02 .123067613777E+02 .931671330706E+01 .698090988085E+01 .517552365756E+01 .379532122669E+01 .275201013792E+01 .197246887711E+01 .139693522036E+01 .977217978443E+00 .674985355080E+00 .460170689103E+00 .309524004753E+00 .205326232749E+00 .134272726203E+00 .865241474580E-01 .549161358338E-01 .343144068647E-01 .210989666792E-01 .127597318321E-01 .758574113557E-02 .443101963639E-02 .254169787533E-02 .143092283623E-02 .790186700406E-03 pspotential -.153267498751E+03 -.153268334719E+03 -.153269144358E+03 -.153269928498E+03 -.153270687940E+03 -.153271423465E+03 -.153272135824E+03 -.153272825746E+03 -.153273493938E+03 -.153274141086E+03 -.153274767850E+03 -.153275374873E+03 -.153275962777E+03 -.153276532163E+03 -.153277083615E+03 -.153277617698E+03 -.153278134957E+03 -.153278635922E+03 -.153279121108E+03 -.153279591009E+03 -.153280046109E+03 -.153280486871E+03 -.153280913748E+03 -.153281327177E+03 -.153281727581E+03 -.153282115370E+03 -.153282490940E+03 -.153282854677E+03 -.153283206952E+03 -.153283548126E+03 -.153283878548E+03 -.153284198557E+03 -.153284508479E+03 -.153284808632E+03 -.153285099324E+03 -.153285380850E+03 -.153285653501E+03 -.153285917553E+03 -.153286173278E+03 -.153286420936E+03 -.153286660782E+03 -.153286893059E+03 -.153287118007E+03 -.153287335853E+03 -.153287546822E+03 -.153287751128E+03 -.153287948980E+03 -.153288140580E+03 -.153288326123E+03 -.153288505800E+03 -.153288679792E+03 -.153288848278E+03 -.153289011428E+03 -.153289169410E+03 -.153289322383E+03 -.153289470504E+03 -.153289613923E+03 -.153289752785E+03 -.153289887232E+03 -.153290017399E+03 -.153290143418E+03 -.153290265418E+03 -.153290383520E+03 -.153290497845E+03 -.153290608507E+03 -.153290715618E+03 -.153290819284E+03 -.153290919611E+03 -.153291016697E+03 -.153291110640E+03 -.153291201533E+03 -.153291289466E+03 -.153291374526E+03 -.153291456797E+03 -.153291536359E+03 -.153291613289E+03 -.153291687662E+03 -.153291759550E+03 -.153291829021E+03 -.153291896142E+03 -.153291960976E+03 -.153292023584E+03 -.153292084023E+03 -.153292142348E+03 -.153292198613E+03 -.153292252867E+03 -.153292305158E+03 -.153292355532E+03 -.153292404029E+03 -.153292450691E+03 -.153292495556E+03 -.153292538656E+03 -.153292580026E+03 -.153292619695E+03 -.153292657691E+03 -.153292694037E+03 -.153292728756E+03 -.153292761868E+03 -.153292793388E+03 -.153292823331E+03 -.153292851708E+03 -.153292878528E+03 -.153292903794E+03 -.153292927509E+03 -.153292949673E+03 -.153292970281E+03 -.153292989325E+03 -.153293006793E+03 -.153293022672E+03 -.153293036943E+03 -.153293049582E+03 -.153293060563E+03 -.153293069855E+03 -.153293077423E+03 -.153293083226E+03 -.153293087219E+03 -.153293089351E+03 -.153293089567E+03 -.153293087804E+03 -.153293083994E+03 -.153293078063E+03 -.153293069929E+03 -.153293059505E+03 -.153293046693E+03 -.153293031390E+03 -.153293013483E+03 -.153292992849E+03 -.153292969357E+03 -.153292942866E+03 -.153292913222E+03 -.153292880262E+03 -.153292843808E+03 -.153292803672E+03 -.153292759650E+03 -.153292711525E+03 -.153292659062E+03 -.153292602011E+03 -.153292540105E+03 -.153292473056E+03 -.153292400559E+03 -.153292322284E+03 -.153292237881E+03 -.153292146975E+03 -.153292049166E+03 -.153291944026E+03 -.153291831096E+03 -.153291709890E+03 -.153291579885E+03 -.153291440524E+03 -.153291291215E+03 -.153291131321E+03 -.153290960167E+03 -.153290777030E+03 -.153290581140E+03 -.153290371673E+03 -.153290147752E+03 -.153289908442E+03 -.153289652744E+03 -.153289379593E+03 -.153289087853E+03 -.153288776312E+03 -.153288443679E+03 -.153288088575E+03 -.153287709530E+03 -.153287304978E+03 -.153286873247E+03 -.153286412556E+03 -.153285921003E+03 -.153285396563E+03 -.153284837074E+03 -.153284240234E+03 -.153283603586E+03 -.153282924511E+03 -.153282200217E+03 -.153281427727E+03 -.153280603866E+03 -.153279725251E+03 -.153278788273E+03 -.153277789085E+03 -.153276723588E+03 -.153275587408E+03 -.153274375886E+03 -.153273084050E+03 -.153271706604E+03 -.153270237900E+03 -.153268671918E+03 -.153267002237E+03 -.153265222017E+03 -.153263323962E+03 -.153261300295E+03 -.153259142728E+03 -.153256842423E+03 -.153254389959E+03 -.153251775295E+03 -.153248987724E+03 -.153246015835E+03 -.153242847465E+03 -.153239469645E+03 -.153235868555E+03 -.153232029459E+03 -.153227936653E+03 -.153223573395E+03 -.153218921843E+03 -.153213962975E+03 -.153208676519E+03 -.153203040866E+03 -.153197032984E+03 -.153190628326E+03 -.153183800728E+03 -.153176522303E+03 -.153168763333E+03 -.153160492144E+03 -.153151674979E+03 -.153142275862E+03 -.153132256458E+03 -.153121575910E+03 -.153110190681E+03 -.153098054380E+03 -.153085117571E+03 -.153071327580E+03 -.153056628283E+03 -.153040959881E+03 -.153024258665E+03 -.153006456759E+03 -.152987481856E+03 -.152967256927E+03 -.152945699921E+03 -.152922723439E+03 -.152898234395E+03 -.152872133647E+03 -.152844315614E+03 -.152814667865E+03 -.152783070683E+03 -.152749396601E+03 -.152713509918E+03 -.152675266173E+03 -.152634511599E+03 -.152591082542E+03 -.152544804840E+03 -.152495493173E+03 -.152442950375E+03 -.152386966703E+03 -.152327319066E+03 -.152263770217E+03 -.152196067893E+03 -.152123943913E+03 -.152047113229E+03 -.151965272928E+03 -.151878101180E+03 -.151785256138E+03 -.151686374786E+03 -.151581071732E+03 -.151468937946E+03 -.151349539448E+03 -.151222415938E+03 -.151087079381E+03 -.150943012535E+03 -.150789667437E+03 -.150626463844E+03 -.150452787634E+03 -.150267989181E+03 -.150071381702E+03 -.149862239601E+03 -.149639796804E+03 -.149403245124E+03 -.149151732663E+03 -.148884362277E+03 -.148600190139E+03 -.148298224436E+03 -.147977424245E+03 -.147636698633E+03 -.147274906062E+03 -.146890854152E+03 -.146483299908E+03 -.146050950508E+03 -.145592464773E+03 -.145106455457E+03 -.144591492526E+03 -.144046107597E+03 -.143468799752E+03 -.142858042941E+03 -.142212295229E+03 -.141530010130E+03 -.140809650298E+03 -.140049703820E+03 -.139248703340E+03 -.138405248186E+03 -.137518029605E+03 -.136585859073E+03 -.135607699519E+03 -.134582699073E+03 -.133510226679E+03 -.132389908643E+03 -.131221664747E+03 -.130005742202E+03 -.128742745182E+03 -.127433657208E+03 -.126079853056E+03 -.124683096318E+03 -.123245518152E+03 -.121769572251E+03 -.120257960715E+03 -.118713525584E+03 -.117139101555E+03 -.115537327466E+03 -.113910418052E+03 -.112259903701E+03 -.110586354425E+03 -.108889113652E+03 -.107166074813E+03 -.105413536199E+03 -.103626169033E+03 -.101788508452E+03 -.999430277917E+02 -.980420648473E+02 -.960785627187E+02 -.940556466143E+02 -.921485909176E+02 -.902256659693E+02 -.882744476111E+02 -.863187908432E+02 core charge-density (pseudized) .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 .000000000000E+00 pseudo wavefunction .165601274856E-03 .170986215157E-03 .176546260279E-03 .182287104195E-03 .188214626029E-03 .194334896081E-03 .200654182042E-03 .207178955413E-03 .213915898130E-03 .220871909412E-03 .228054112820E-03 .235469863558E-03 .243126756002E-03 .251032631476E-03 .259195586288E-03 .267623980014E-03 .276326444066E-03 .285311890524E-03 .294589521270E-03 .304168837407E-03 .314059648988E-03 .324272085066E-03 .334816604067E-03 .345704004495E-03 .356945435997E-03 .368552410777E-03 .380536815389E-03 .392910922904E-03 .405687405487E-03 .418879347365E-03 .432500258235E-03 .446564087093E-03 .461085236521E-03 .476078577438E-03 .491559464327E-03 .507543750959E-03 .524047806630E-03 .541088532924E-03 .558683381021E-03 .576850369569E-03 .595608103136E-03 .614975791265E-03 .634973268142E-03 .655621012910E-03 .676940170642E-03 .698952573993E-03 .721680765562E-03 .745148020973E-03 .769378372712E-03 .794396634742E-03 .820228427910E-03 .846900206184E-03 .874439283748E-03 .902873862971E-03 .932233063289E-03 .962546951024E-03 .993846570176E-03 .102616397421E-02 .105953225889E-02 .109398559615E-02 .112955926913E-02 .116628970826E-02 .120421452859E-02 .124337256831E-02 .128380392853E-02 .132555001431E-02 .136865357713E-02 .141315875859E-02 .145911113565E-02 .150655776733E-02 .155554724285E-02 .160612973141E-02 .165835703357E-02 .171228263430E-02 .176796175772E-02 .182545142368E-02 .188481050614E-02 .194609979345E-02 .200938205063E-02 .207472208357E-02 .214218680549E-02 .221184530537E-02 .228376891874E-02 .235803130072E-02 .243470850144E-02 .251387904391E-02 .259562400442E-02 .268002709556E-02 .276717475196E-02 .285715621874E-02 .295006364293E-02 .304599216783E-02 .314504003038E-02 .324730866178E-02 .335290279132E-02 .346193055363E-02 .357450359938E-02 .369073720957E-02 .381075041359E-02 .393466611106E-02 .406261119765E-02 .419471669497E-02 .433111788476E-02 .447195444729E-02 .461737060442E-02 .476751526719E-02 .492254218825E-02 .508261011925E-02 .524788297332E-02 .541852999284E-02 .559472592264E-02 .577665118885E-02 .596449208355E-02 .615844095538E-02 .635869640641E-02 .656546349531E-02 .677895394718E-02 .699938637020E-02 .722698647920E-02 .746198732663E-02 .770462954092E-02 .795516157261E-02 .821383994844E-02 .848092953369E-02 .875670380303E-02 .904144512013E-02 .933544502630E-02 .963900453860E-02 .995243445741E-02 .102760556841E-01 .106101995490E-01 .109552081499E-01 .113114347013E-01 .116792438955E-01 .120590122749E-01 .124511286162E-01 .128559943277E-01 .132740238587E-01 .137056451223E-01 .141512999320E-01 .146114444525E-01 .150865496644E-01 .155771018444E-01 .160836030610E-01 .166065716853E-01 .171465429196E-01 .177040693415E-01 .182797214664E-01 .188740883277E-01 .194877780754E-01 .201214185942E-01 .207756581406E-01 .214511660017E-01 .221486331730E-01 .228687730598E-01 .236123221990E-01 .243800410052E-01 .251727145395E-01 .259911533031E-01 .268361940553E-01 .277087006579E-01 .286095649458E-01 .295397076241E-01 .305000791949E-01 .314916609108E-01 .325154657596E-01 .335725394789E-01 .346639616015E-01 .357908465336E-01 .369543446654E-01 .381556435158E-01 .393959689112E-01 .406765862011E-01 .419988015081E-01 .433639630173E-01 .447734623020E-01 .462287356896E-01 .477312656669E-01 .492825823258E-01 .508842648510E-01 .525379430496E-01 .542452989239E-01 .560080682881E-01 .578280424287E-01 .597070698116E-01 .616470578325E-01 .636499746161E-01 .657178508593E-01 .678527817232E-01 .700569287714E-01 .723325219554E-01 .746818616470E-01 .771073207187E-01 .796113466687E-01 .821964637939E-01 .848652754061E-01 .876204660936E-01 .904648040245E-01 .934011432916E-01 .964324262953E-01 .995616861634E-01 .102792049205E+00 .106126737391E+00 .109569070868E+00 .113122470484E+00 .116790460339E+00 .120576670337E+00 .124484838752E+00 .128518814779E+00 .132682561076E+00 .136980156286E+00 .141415797513E+00 .145993802769E+00 .150718613337E+00 .155594796077E+00 .160627045623E+00 .165820186468E+00 .171179174922E+00 .176709100891E+00 .182415189482E+00 .188302802382E+00 .194377438986E+00 .200644737239E+00 .207110474140E+00 .213780565882E+00 .220661067553E+00 .227758172370E+00 .235078210363E+00 .242627646458E+00 .250413077873E+00 .258441230761E+00 .266718955998E+00 .275253224027E+00 .284051118653E+00 .293119829670E+00 .302466644194E+00 .312098936569E+00 .322024156685E+00 .332249816565E+00 .342783475014E+00 .353632720169E+00 .364805149715E+00 .376308348564E+00 .388149863728E+00 .400337176150E+00 .412877669191E+00 .425778593474E+00 .439047027769E+00 .452689835565E+00 .466713616955E+00 .481124655463E+00 .495928859375E+00 .511131697159E+00 .526738126515E+00 .542752516577E+00 .559178562785E+00 .576019193926E+00 .593276470840E+00 .610951476266E+00 .629044195346E+00 .647553386288E+00 .666476440712E+00 .685809233285E+00 .705545960242E+00 .725678966536E+00 .746198561387E+00 .767092822191E+00 .788347386848E+00 .809945234816E+00 .831866457373E+00 .854088017907E+00 .876583503344E+00 .899322868247E+00 .922272173564E+00 .945393322553E+00 .968643796991E+00 .991976397530E+00 .101533899278E+01 .103867428264E+01 .106191958231E+01 .108500663448E+01 .110786145843E+01 .113040424569E+01 .115254931351E+01 .117420512822E+01 .119527441206E+01 .121565434786E+01 .123523689697E+01 .125390924631E+01 .127155440041E+01 .128805193389E+01 .130327891850E+01 .131711103614E+01 .132942388590E+01 .134009448735E+01 .134900297496E+01 .135603446881E+01 .136108109375E+01 .136404410364E+01 .136483604759E+01 .136338289235E+01 .135962598792E+01 .135352373274E+01 .134505276160E+01 .133420844359E+01 .132100444141E+01 .130547105033E+01 .128765200718E+01 .126759944388E+01 .124536666092E+01 .122099842355E+01 .119451854586E+01 .116591463800E+01 .113513192355E+01 .110229857916E+01 .106760690066E+01 .103126913660E+01 .993503299915E+00 .954531323645E+00 .914577215088E+00 .873865221786E+00 ae wavefunction -.779383096528E-03 -.804670312887E-03 -.830777581751E-03 -.857731471485E-03 -.885559409570E-03 -.914289710274E-03 -.943951603198E-03 -.974575262735E-03 -.100619183847E-02 -.103883348655E-02 -.107253340205E-02 -.110732585237E-02 -.114324621168E-02 -.118033099650E-02 -.121861790238E-02 -.125814584174E-02 -.129895498293E-02 -.134108679051E-02 -.138458406684E-02 -.142949099492E-02 -.147585318269E-02 -.152371770861E-02 -.157313316876E-02 -.162414972543E-02 -.167681915716E-02 -.173119491046E-02 -.178733215307E-02 -.184528782898E-02 -.190512071508E-02 -.196689147963E-02 -.203066274263E-02 -.209649913792E-02 -.216446737738E-02 -.223463631706E-02 -.230707702532E-02 -.238186285320E-02 -.245906950689E-02 -.253877512250E-02 -.262106034307E-02 -.270600839809E-02 -.279370518532E-02 -.288423935523E-02 -.297770239805E-02 -.307418873338E-02 -.317379580270E-02 -.327662416455E-02 -.338277759273E-02 -.349236317747E-02 -.360549142956E-02 -.372227638785E-02 -.384283572975E-02 -.396729088528E-02 -.409576715439E-02 -.422839382787E-02 -.436530431191E-02 -.450663625628E-02 -.465253168635E-02 -.480313713910E-02 -.495860380302E-02 -.511908766224E-02 -.528474964477E-02 -.545575577518E-02 -.563227733166E-02 -.581449100761E-02 -.600257907796E-02 -.619672957020E-02 -.639713644035E-02 -.660399975388E-02 -.681752587179E-02 -.703792764195E-02 -.726542459571E-02 -.750024315008E-02 -.774261681542E-02 -.799278640894E-02 -.825100027389E-02 -.851751450485E-02 -.879259317897E-02 -.907650859340E-02 -.936954150911E-02 -.967198140099E-02 -.998412671452E-02 -.103062851291E-01 -.106387738280E-01 -.109819197754E-01 -.113360599999E-01 -.117015418854E-01 -.120787234691E-01 -.124679737464E-01 -.128696729834E-01 -.132842130364E-01 -.137119976791E-01 -.141534429365E-01 -.146089774276E-01 -.150790427142E-01 -.155640936577E-01 -.160645987838E-01 -.165810406541E-01 -.171139162452E-01 -.176637373357E-01 -.182310308994E-01 -.188163395071E-01 -.194202217343E-01 -.200432525764E-01 -.206860238705E-01 -.213491447237E-01 -.220332419481E-01 -.227389605007E-01 -.234669639306E-01 -.242179348300E-01 -.249925752914E-01 -.257916073683E-01 -.266157735405E-01 -.274658371825E-01 -.283425830349E-01 -.292468176777E-01 -.301793700053E-01 -.311410917014E-01 -.321328577144E-01 -.331555667305E-01 -.342101416451E-01 -.352975300301E-01 -.364187045964E-01 -.375746636502E-01 -.387664315412E-01 -.399950591018E-01 -.412616240742E-01 -.425672315256E-01 -.439130142467E-01 -.453001331341E-01 -.467297775521E-01 -.482031656720E-01 -.497215447865E-01 -.512861915962E-01 -.528984124638E-01 -.545595436345E-01 -.562709514173E-01 -.580340323242E-01 -.598502131628E-01 -.617209510776E-01 -.636477335360E-01 -.656320782528E-01 -.676755330486E-01 -.697796756363E-01 -.719461133288E-01 -.741764826622E-01 -.764724489270E-01 -.788357056004E-01 -.812679736711E-01 -.837710008495E-01 -.863465606530E-01 -.889964513581E-01 -.917224948098E-01 -.945265350766E-01 -.974104369411E-01 -.100376084214E+00 -.103425377862E+00 -.106560233929E+00 -.109782581249E+00 -.113094358924E+00 -.116497513566E+00 -.119993996267E+00 -.123585759308E+00 -.127274752560E+00 -.131062919588E+00 -.134952193412E+00 -.138944491932E+00 -.143041712971E+00 -.147245728938E+00 -.151558381071E+00 -.155981473248E+00 -.160516765342E+00 -.165165966088E+00 -.169930725446E+00 -.174812626431E+00 -.179813176378E+00 -.184933797634E+00 -.190175817616E+00 -.195540458251E+00 -.201028824724E+00 -.206641893546E+00 -.212380499881E+00 -.218245324131E+00 -.224236877725E+00 -.230355488105E+00 -.236601282866E+00 -.242974173035E+00 -.249473835456E+00 -.256099694256E+00 -.262850901371E+00 -.269726316115E+00 -.276724483765E+00 -.283843613151E+00 -.291081553233E+00 -.298435768663E+00 -.305903314322E+00 -.313480808822E+00 -.321164407001E+00 -.328949771388E+00 -.336832042685E+00 -.344805809276E+00 -.352865075782E+00 -.361003230735E+00 -.369213013385E+00 -.377486479727E+00 -.385814967803E+00 -.394189062379E+00 -.402598559074E+00 -.411032428077E+00 -.419478777565E+00 -.427924816961E+00 -.436356820221E+00 -.444760089293E+00 -.453118917987E+00 -.461416556449E+00 -.469635176497E+00 -.477755838092E+00 -.485758457214E+00 -.493621775488E+00 -.501323331879E+00 -.508839436836E+00 -.516145149286E+00 -.523214256890E+00 -.530019260023E+00 -.536531359954E+00 -.542720451743E+00 -.548555122378E+00 -.554002654726E+00 -.559029037887E+00 -.563598984561E+00 -.567675956067E+00 -.571222195686E+00 -.574198770982E+00 -.576565625816E+00 -.578281642748E+00 -.579304716540E+00 -.579591839480E+00 -.579099199228E+00 -.577782289902E+00 -.575596037067E+00 -.572494937302E+00 -.568433212954E+00 -.563364982657E+00 -.557244448127E+00 -.550026097668E+00 -.541664926755E+00 -.532116675918E+00 -.521338086057E+00 -.509287171175E+00 -.495923508326E+00 -.481208544420E+00 -.465105919304E+00 -.447581804307E+00 -.428605255216E+00 -.408148578344E+00 -.386187708121E+00 -.362702594311E+00 -.337677596716E+00 -.311101884914E+00 -.282969840345E+00 -.253281457808E+00 -.222042743227E+00 -.189266104353E+00 -.154970730897E+00 -.119182960394E+00 -.819366258111E-01 -.432733805088E-01 -.324299545533E-02 .380963775271E-01 .806779844544E-01 .124426300356E+00 .169256927002E+00 .215076575501E+00 .261783156083E+00 .309265998475E+00 .357406219523E+00 .406077232836E+00 .455145352347E+00 .504470381268E+00 .553906024273E+00 .603299959640E+00 .652493503846E+00 .701320993687E+00 .749609226077E+00 .797177403836E+00 .843837924822E+00 .889398035072E+00 .933662031769E+00 .976433575826E+00 .101751780301E+01 .105672315067E+01 .109386297533E+01 .112875707838E+01 .116123322551E+01 .119112869576E+01 .121829185458E+01 .124258372123E+01 .126387948974E+01 .128206996159E+01 .129706285239E+01 .130878394122E+01 .131717803816E+01 .132220975218E+01 .132386404652E+01 .132214657395E+01 .131708378801E+01 .130872283014E+01 .129713119621E+01 .128239618878E+01 .126462416508E+01 .124393959283E+01 .122048392909E+01 .119441433896E+01 .116590227308E+01 .113513192355E+01 .110229857916E+01 .106760690066E+01 .103126913660E+01 .993503299915E+00 .954531323645E+00 .914577215088E+00 .873865221786E+00 pseudo wavefunction -.412220112469E-04 -.425624482010E-04 -.439464728195E-04 -.453755024641E-04 -.468510005858E-04 -.483744782236E-04 -.499474955513E-04 -.515716634757E-04 -.532486452866E-04 -.549801583594E-04 -.567679759144E-04 -.586139288326E-04 -.605199075306E-04 -.624878638966E-04 -.645198132893E-04 -.666178366018E-04 -.687840823927E-04 -.710207690860E-04 -.733301872437E-04 -.757147019107E-04 -.781767550374E-04 -.807188679802E-04 -.833436440837E-04 -.860537713465E-04 -.888520251743E-04 -.917412712218E-04 -.947244683276E-04 -.978046715442E-04 -.100985035267E-03 -.104268816463E-03 -.107659378009E-03 -.111160192133E-03 -.114774843972E-03 -.118507035241E-03 -.122360588027E-03 -.126339448699E-03 -.130447691954E-03 -.134689524986E-03 -.139069291798E-03 -.143591477648E-03 -.148260713640E-03 -.153081781474E-03 -.158059618336E-03 -.163199321955E-03 -.168506155828E-03 -.173985554604E-03 -.179643129654E-03 -.185484674815E-03 -.191516172325E-03 -.197743798948E-03 -.204173932299E-03 -.210813157375E-03 -.217668273302E-03 -.224746300292E-03 -.232054486837E-03 -.239600317127E-03 -.247391518721E-03 -.255436070452E-03 -.263742210605E-03 -.272318445350E-03 -.281173557452E-03 -.290316615266E-03 -.299756982024E-03 -.309504325423E-03 -.319568627522E-03 -.329960194969E-03 -.340689669551E-03 -.351768039092E-03 -.363206648708E-03 -.375017212419E-03 -.387211825149E-03 -.399802975108E-03 -.412803556582E-03 -.426226883132E-03 -.440086701234E-03 -.454397204349E-03 -.469173047458E-03 -.484429362069E-03 -.500181771710E-03 -.516446407924E-03 -.533239926792E-03 -.550579525983E-03 -.568482962361E-03 -.586968570171E-03 -.606055279807E-03 -.625762637196E-03 -.646110823808E-03 -.667120677320E-03 -.688813712947E-03 -.711212145472E-03 -.734338911988E-03 -.758217695378E-03 -.782872948560E-03 -.808329919522E-03 -.834614677163E-03 -.861754137983E-03 -.889776093630E-03 -.918709239353E-03 -.948583203367E-03 -.979428577181E-03 -.101127694691E-02 -.104416092559E-02 -.107811418657E-02 -.111317149796E-02 -.114936875821E-02 -.118674303286E-02 -.122533259242E-02 -.126517695159E-02 -.130631690962E-02 -.134879459210E-02 -.139265349403E-02 -.143793852429E-02 -.148469605160E-02 -.153297395193E-02 -.158282165747E-02 -.163429020713E-02 -.168743229878E-02 -.174230234307E-02 -.179895651908E-02 -.185745283172E-02 -.191785117100E-02 -.198021337325E-02 -.204460328423E-02 -.211108682442E-02 -.217973205627E-02 -.225060925375E-02 -.232379097404E-02 -.239935213163E-02 -.247737007471E-02 -.255792466414E-02 -.264109835484E-02 -.272697627989E-02 -.281564633733E-02 -.290719927965E-02 -.300172880635E-02 -.309933165926E-02 -.320010772105E-02 -.330416011687E-02 -.341159531922E-02 -.352252325622E-02 -.363705742327E-02 -.375531499834E-02 -.387741696092E-02 -.400348821471E-02 -.413365771428E-02 -.426805859572E-02 -.440682831139E-02 -.455010876899E-02 -.469804647501E-02 -.485079268268E-02 -.500850354455E-02 -.517134026996E-02 -.533946928727E-02 -.551306241133E-02 -.569229701603E-02 -.587735621227E-02 -.606842903139E-02 -.626571061432E-02 -.646940240646E-02 -.667971235858E-02 -.689685513379E-02 -.712105232080E-02 -.735253265363E-02 -.759153223789E-02 -.783829478379E-02 -.809307184612E-02 -.835612307119E-02 -.862771645107E-02 -.890812858518E-02 -.919764494940E-02 -.949656017280E-02 -.980517832225E-02 -.101238131949E-01 -.104527886188E-01 -.107924387616E-01 -.111431084476E-01 -.115051534833E-01 -.118789409908E-01 -.122648497510E-01 -.126632705538E-01 -.130746065579E-01 -.134992736592E-01 -.139377008669E-01 -.143903306890E-01 -.148576195256E-01 -.153400380707E-01 -.158380717219E-01 -.163522209980E-01 -.168830019638E-01 -.174309466622E-01 -.179966035535E-01 -.185805379595E-01 -.191833325146E-01 -.198055876210E-01 -.204479219077E-01 -.211109726928E-01 -.217953964482E-01 -.225018692639E-01 -.232310873126E-01 -.239837673115E-01 -.247606469798E-01 -.255624854903E-01 -.263900639122E-01 -.272441856433E-01 -.281256768272E-01 -.290353867542E-01 -.299741882405E-01 -.309429779831E-01 -.319426768846E-01 -.329742303434E-01 -.340386085044E-01 -.351368064621E-01 -.362698444117E-01 -.374387677378E-01 -.386446470349E-01 -.398885780472E-01 -.411716815209E-01 -.424951029540E-01 -.438600122329E-01 -.452676031415E-01 -.467190927260E-01 -.482157205004E-01 -.497587474713E-01 -.513494549631E-01 -.529891432198E-01 -.546791297580E-01 -.564207474440E-01 -.582153422637E-01 -.600642707520E-01 -.619688970453E-01 -.639305895159E-01 -.659507169443E-01 -.680306441808E-01 -.701717272434E-01 -.723753077929E-01 -.746427069221E-01 -.769752181897E-01 -.793740998211E-01 -.818405659956E-01 -.843757771268E-01 -.869808290391E-01 -.896567409320E-01 -.924044420163E-01 -.952247566937E-01 -.981183881437E-01 -.101085900167E+00 -.104127697127E+00 -.107244001807E+00 -.110434831009E+00 -.113699968673E+00 -.117038936314E+00 -.120450960536E+00 -.123934937372E+00 -.127489393177E+00 -.131112441808E+00 -.134801737757E+00 -.138554424943E+00 -.142367080808E+00 -.146235655364E+00 -.150155404816E+00 -.154120819373E+00 -.158125544834E+00 -.162162297548E+00 -.166222772304E+00 -.170297542723E+00 -.174375953731E+00 -.178446005655E+00 -.182494229536E+00 -.186505553254E+00 -.190463158067E+00 -.194348325228E+00 -.198140272376E+00 -.201815979445E+00 -.205350003927E+00 -.208714285396E+00 -.211877939310E+00 -.214807040213E+00 -.217464394627E+00 -.219809304039E+00 -.221797318607E+00 -.223379982348E+00 -.224504570832E+00 -.225113822576E+00 -.225145665596E+00 -.224532940792E+00 -.223203124070E+00 -.221078049349E+00 -.218073634810E+00 -.214099614936E+00 -.209059281106E+00 -.202849233644E+00 -.195359148430E+00 -.186471561366E+00 -.176061674254E+00 -.163997186071E+00 -.150138154291E+00 -.134336891962E+00 -.116437908003E+00 -.962779008330E-01 -.736858195368E-01 -.484830127511E-01 -.204834941246E-01 .105056345896E-01 .446835448931E-01 .822547466436E-01 .123427745979E+00 .168413145922E+00 .217420989654E+00 .270657084570E+00 .328317970202E+00 .390584105101E+00 .457610748007E+00 .529515901005E+00 .606351591923E+00 .688292477140E+00 .775483611861E+00 .868104097163E+00 .966343881368E+00 .107040649767E+01 .118051230869E+01 .129690233012E+01 ae wavefunction .151059377480E-03 .155960524120E-03 .161020612578E-03 .166244792305E-03 .171638379267E-03 .177206861306E-03 .182955903670E-03 .188891354729E-03 .195019251859E-03 .201345827531E-03 .207877515575E-03 .214620957660E-03 .221583009967E-03 .228770750086E-03 .236191484124E-03 .243852754039E-03 .251762345212E-03 .259928294254E-03 .268358897063E-03 .277062717136E-03 .286048594142E-03 .295325652768E-03 .304903311844E-03 .314791293754E-03 .324999634147E-03 .335538691950E-03 .346419159699E-03 .357652074193E-03 .369248827483E-03 .381221178204E-03 .393581263265E-03 .406341609899E-03 .419515148098E-03 .433115223427E-03 .447155610239E-03 .461650525311E-03 .476614641884E-03 .492063104159E-03 .508011542228E-03 .524476087471E-03 .541473388430E-03 .559020627168E-03 .577135536133E-03 .595836415542E-03 .615142151292E-03 .635072233421E-03 .655646775136E-03 .676886532411E-03 .698812924191E-03 .721448053199E-03 .744814727376E-03 .768936481966E-03 .793837602267E-03 .819543147059E-03 .846078972739E-03 .873471758171E-03 .901749030273E-03 .930939190367E-03 .961071541300E-03 .992176315370E-03 .102428470306E-02 .105742888264E-02 .109164205057E-02 .112695845284E-02 .116341341721E-02 .120104338633E-02 .123988595187E-02 .127997988956E-02 .132136519524E-02 .136408312197E-02 .140817621812E-02 .145368836653E-02 .150066482477E-02 .154915226652E-02 .159919882404E-02 .165085413180E-02 .170416937133E-02 .175919731719E-02 .181599238422E-02 .187461067603E-02 .193511003469E-02 .199755009177E-02 .206199232064E-02 .212850009012E-02 .219713871947E-02 .226797553469E-02 .234107992624E-02 .241652340816E-02 .249437967854E-02 .257472468145E-02 .265763667029E-02 .274319627253E-02 .283148655597E-02 .292259309636E-02 .301660404653E-02 .311361020695E-02 .321370509767E-02 .331698503180E-02 .342354919032E-02 .353349969836E-02 .364694170279E-02 .376398345126E-02 .388473637250E-02 .400931515794E-02 .413783784463E-02 .427042589925E-02 .440720430340E-02 .454830163989E-02 .469385018009E-02 .484398597219E-02 .499884893033E-02 .515858292446E-02 .532333587081E-02 .549325982298E-02 .566851106323E-02 .584925019418E-02 .603564223044E-02 .622785669018E-02 .642606768641E-02 .663045401763E-02 .684119925789E-02 .705849184563E-02 .728252517141E-02 .751349766390E-02 .775161287407E-02 .799707955702E-02 .825011175122E-02 .851092885468E-02 .877975569759E-02 .905682261099E-02 .934236549099E-02 .963662585794E-02 .993985090987E-02 .102522935698E-01 .105742125261E-01 .109058722650E-01 .112475430948E-01 .115995011607E-01 .119620284495E-01 .123354127833E-01 .127199478006E-01 .131159329245E-01 .135236733165E-01 .139434798145E-01 .143756688539E-01 .148205623706E-01 .152784876835E-01 .157497773562E-01 .162347690359E-01 .167338052661E-01 .172472332744E-01 .177754047297E-01 .183186754705E-01 .188774051983E-01 .194519571368E-01 .200426976531E-01 .206499958378E-01 .212742230423E-01 .219157523701E-01 .225749581184E-01 .232522151676E-01 .239478983153E-01 .246623815501E-01 .253960372634E-01 .261492353938E-01 .269223425006E-01 .277157207625E-01 .285297268961E-01 .293647109914E-01 .302210152575E-01 .310989726746E-01 .319989055478E-01 .329211239561E-01 .338659240917E-01 .348335864849E-01 .358243741068E-01 .368385303458E-01 .378762768513E-01 .389378112376E-01 .400233046424E-01 .411328991343E-01 .422667049611E-01 .434247976343E-01 .446072148414E-01 .458139531821E-01 .470449647194E-01 .483001533414E-01 .495793709266E-01 .508824133076E-01 .522090160269E-01 .535588498806E-01 .549315162446E-01 .563265421791E-01 .577433753083E-01 .591813784716E-01 .606398241459E-01 .621178886351E-01 .636146460304E-01 .651290619393E-01 .666599869875E-01 .682061500989E-01 .697661515563E-01 .713384558542E-01 .729213843511E-01 .745131077342E-01 .761116383119E-01 .777148221508E-01 .793203310770E-01 .809256545684E-01 .825280915617E-01 .841247422088E-01 .857124996153E-01 .872880416035E-01 .888478225428E-01 .903880652988E-01 .919047533556E-01 .933936231734E-01 .948501568487E-01 .962695751503E-01 .976468310133E-01 .989766035796E-01 .100253292878E+00 .101471015254E+00 .102623599651E+00 .103704584878E+00 .104707217978E+00 .105624453851E+00 .106448956270E+00 .107173100449E+00 .107788977341E+00 .108288399829E+00 .108662911011E+00 .108903794772E+00 .109002088849E+00 .108948600619E+00 .108733925814E+00 .108348470429E+00 .107782476040E+00 .107026048811E+00 .106069192420E+00 .104901845194E+00 .103513921706E+00 .101895359105E+00 .100036168453E+00 .979264913315E-01 .955566619749E-01 .929172751856E-01 .899992602665E-01 .867939611894E-01 .832932231985E-01 .794894860197E-01 .753758838152E-01 .709463519862E-01 .661957408865E-01 .611199364627E-01 .557159877905E-01 .499822414220E-01 .439184824105E-01 .375260818220E-01 .308081504919E-01 .237696987296E-01 .164178016160E-01 .876176947364E-02 .813323004364E-03 -.741322752467E-02 -.159007998325E-01 -.246293549443E-01 -.335757116697E-01 -.427133621408E-01 -.520122910084E-01 -.614388017831E-01 -.709553547884E-01 -.805204219704E-01 -.900883637045E-01 -.996093305631E-01 -.109029187229E+00 -.118289445417E+00 -.127327179510E+00 -.136074889026E+00 -.144460276770E+00 -.152405938844E+00 -.159829009187E+00 -.166640846770E+00 -.172746868312E+00 -.178046592839E+00 -.182433887306E+00 -.185797331820E+00 -.188020606003E+00 -.188982836131E+00 -.188558895599E+00 -.186619682941E+00 -.183032406141E+00 -.177660891660E+00 -.170365923942E+00 -.161005611726E+00 -.149435772257E+00 -.135510322374E+00 -.119081665288E+00 -.100001062586E+00 -.781189819864E-01 -.532854121368E-01 -.253501363098E-01 .583704303801E-02 .404261369719E-01 .785668685721E-01 .120408646344E+00 .166100622522E+00 .215791847373E+00 .269631532049E+00 .327769434397E+00 .390356384479E+00 .457544969431E+00 .529490400826E+00 .606351591923E+00 .688292477140E+00 .775483611861E+00 .868104097163E+00 .966343881368E+00 .107040649767E+01 .118051230869E+01 .129690233012E+01 pseudo wavefunction .876800942919E-08 .934750820283E-08 .996530744023E-08 .106239385109E-07 .113261000886E-07 .120746692089E-07 .128727130575E-07 .137235015379E-07 .146305206693E-07 .155974868702E-07 .166283621861E-07 .177273705236E-07 .188990149574E-07 .201480961813E-07 .214797321784E-07 .228993791914E-07 .244128540793E-07 .260263581512E-07 .277465025757E-07 .295803354691E-07 .315353707747E-07 .336196190504E-07 .358416202909E-07 .382104789196E-07 .407359010930E-07 .434282344708E-07 .462985106142E-07 .493584901867E-07 .526207111420E-07 .560985400973E-07 .598062271014E-07 .637589640228E-07 .679729467968E-07 .724654417870E-07 .772548565319E-07 .823608151682E-07 .878042388385E-07 .936074314137E-07 .997941708807E-07 .106389806770E-06 .113421364022E-06 .120917653723E-06 .128909391148E-06 .137429321620E-06 .146512354678E-06 .156195707115E-06 .166519055469E-06 .177524698598E-06 .189257730987E-06 .201766227524E-06 .215101440481E-06 .229318009513E-06 .244474185538E-06 .260632069415E-06 .277857866393E-06 .296222157385E-06 .315800188158E-06 .336672177651E-06 .358923646660E-06 .382645768248E-06 .407935741319E-06 .434897188879E-06 .463640582620E-06 .494283695562E-06 .526952084616E-06 .561779605040E-06 .598908958892E-06 .638492279736E-06 .680691755993E-06 .725680295482E-06 .773642233894E-06 .824774090084E-06 .879285371278E-06 .937399431503E-06 .999354386754E-06 .106540409064E-05 .113581917451E-05 .121088815635E-05 .129091862290E-05 .137623848999E-05 .146719734613E-05 .156416788485E-05 .166754743180E-05 .177775957271E-05 .189525588897E-05 .202051780793E-05 .215405857544E-05 .229642535878E-05 .244820148864E-05 .261000884915E-05 .278251042597E-05 .296641302275E-05 .316247015708E-05 .337148514794E-05 .359431440709E-05 .383187094802E-05 .408512812686E-05 .435512363048E-05 .464296372811E-05 .494982780407E-05 .527697318997E-05 .562574031625E-05 .599755820430E-05 .639395032137E-05 .681654082259E-05 .726706120540E-05 .774735740376E-05 .825939735129E-05 .880527904412E-05 .938723913663E-05 .100076621053E-04 .106690900180E-04 .113742329492E-04 .121259800829E-04 .129274115503E-04 .137818110482E-04 .146926792929E-04 .156637483622E-04 .166989969852E-04 .178026668427E-04 .189792799449E-04 .202336571571E-04 .215709379492E-04 .229966014514E-04 .245164888998E-04 .261368275659E-04 .278642562675E-04 .297058525640E-04 .316691617501E-04 .337622277638E-04 .359936261373E-04 .383724991248E-04 .409085931505E-04 .436122987313E-04 .464946930367E-04 .495675852597E-04 .528435649859E-04 .563360537566E-04 .600593600386E-04 .640287378248E-04 .682604491045E-04 .727718304609E-04 .775813640660E-04 .827087533641E-04 .881750037533E-04 .940025085951E-04 .100215140902E-03 .106838351079E-03 .113899271120E-03 .121426825680E-03 .129451850478E-03 .138007218521E-03 .147127974656E-03 .156851478992E-03 .167217559805E-03 .178268676513E-03 .190050093415E-03 .202610064881E-03 .216000032767E-03 .230274836838E-03 .245492939072E-03 .261716662751E-03 .279012447307E-03 .297451119968E-03 .317108185303E-03 .338064133837E-03 .360404770996E-03 .384221567711E-03 .409612034101E-03 .436680117756E-03 .465536628216E-03 .496299689376E-03 .529095221642E-03 .564057455770E-03 .601329480479E-03 .641063826030E-03 .683423086115E-03 .728580580566E-03 .776721061532E-03 .828041465956E-03 .882751717358E-03 .941075580128E-03 .100325156974E-02 .106953392247E-02 .114019362857E-02 .121551953281E-02 .129581950697E-02 .138142169865E-02 .147267586158E-02 .156995477238E-02 .167365573951E-02 .178420221022E-02 .190204548166E-02 .202766652295E-02 .216157791508E-02 .230432591607E-02 .245649265950E-02 .261869849446E-02 .279160447600E-02 .297591501533E-02 .317238069977E-02 .338180129278E-02 .360502892529E-02 .384297148989E-02 .409659625027E-02 .436693367886E-02 .465508153640E-02 .496220920774E-02 .528956230910E-02 .563846758260E-02 .601033809478E-02 .640667875647E-02 .682909218230E-02 .727928490893E-02 .775907399167E-02 .827039400030E-02 .881530443543E-02 .939599758743E-02 .100148068609E-01 .106742155883E-01 .113768663561E-01 .121255708695E-01 .129233203788E-01 .137732966940E-01 .146788838121E-01 .156436801832E-01 .166715116379E-01 .177664450033E-01 .189328024277E-01 .201751764366E-01 .214984457406E-01 .229077918110E-01 .244087162380E-01 .260070588813E-01 .277090168194E-01 .295211640968E-01 .314504722621E-01 .335043316825E-01 .356905736097E-01 .380174929610E-01 .404938717663E-01 .431290032176E-01 .459327162362E-01 .489154004572E-01 .520880315025E-01 .554621963885E-01 .590501188839E-01 .628646845960E-01 .669194655242E-01 .712287437731E-01 .758075340664E-01 .806716046432E-01 .858374960531E-01 .913225372928E-01 .971448586440E-01 .103323400480E+00 .109877917210E+00 .116828975410E+00 .124197945074E+00 .132006982779E+00 .140279005407E+00 .149037652906E+00 .158307238415E+00 .168112683857E+00 .178479438948E+00 .189433381339E+00 .201000695392E+00 .213207726887E+00 .226080810723E+00 .239646068460E+00 .253929172356E+00 .268955072346E+00 .284747682278E+00 .301329521590E+00 .318721308578E+00 .336941501427E+00 .356005783316E+00 .375926488182E+00 .396711964169E+00 .418365872421E+00 .440886419795E+00 .464265525259E+00 .488487921304E+00 .513530193674E+00 .539359765212E+00 .565933832605E+00 .593198268522E+00 .621086505922E+00 .649518426467E+00 .678399280811E+00 .707618675275E+00 .737049666855E+00 .766548016726E+00 .795951661151E+00 .825080467758E+00 .853736354175E+00 .881703854475E+00 .908751226040E+00 .934632194409E+00 .959088435217E+00 .981852888934E+00 .100265399395E+01 .102122090455E+01 .103728972981E+01 .105061078496E+01 .106095678522E+01 .106813183090E+01 .107198092903E+01 .107239966993E+01 .106934352597E+01 .106283606749E+01 .105297520198E+01 .103993634791E+01 .102397126974E+01 .100540114852E+01 .984602376785E+00 .961983587564E+00 .937952609537E+00 .912872443939E+00 .887006052763E+00 .860452992548E+00 ae wavefunction .106376700892E-06 .113087413803E-06 .120167236645E-06 .127639483744E-06 .135528816674E-06 .143861331680E-06 .152664652631E-06 .161968029723E-06 .171802444287E-06 .182200720122E-06 .193197641780E-06 .204830080265E-06 .217137126625E-06 .230160233977E-06 .243943368496E-06 .258533169978E-06 .273979122604E-06 .290333736564E-06 .307652741272E-06 .325995290924E-06 .345424183216E-06 .366006092090E-06 .387811815424E-06 .410916538653E-06 .435400115376E-06 .461347366055E-06 .488848395999E-06 .517998933913E-06 .548900692345E-06 .581661751487E-06 .616396967856E-06 .653228409491E-06 .692285819420E-06 .733707109229E-06 .777638884741E-06 .824237005887E-06 .873667183032E-06 .926105612138E-06 .981739651318E-06 .104076854150E-05 .110340417408E-05 .116987190869E-05 .124041144428E-05 .131527774710E-05 .139474203931E-05 .147909285209E-05 .156863714758E-05 .166370151417E-05 .176463343984E-05 .187180266875E-05 .198560264655E-05 .210645206009E-05 .223479647791E-05 .237111009795E-05 .251589760950E-05 .266969617698E-05 .283307755347E-05 .300665033235E-05 .319106234635E-05 .338700322333E-05 .359520710936E-05 .381645556972E-05 .405158067970E-05 .430146831748E-05 .456706167228E-05 .484936498185E-05 .514944751434E-05 .546844781039E-05 .580757820245E-05 .616812962949E-05 .655147676623E-05 .695908348745E-05 .739250868932E-05 .785341249074E-05 .834356283974E-05 .886484255102E-05 .941925680293E-05 .100089411236E-04 .106361698981E-04 .113033654302E-04 .120131075958E-04 .127681441243E-04 .135714015515E-04 .144259968849E-04 .153352500294E-04 .163026970217E-04 .173321041264E-04 .184274828491E-04 .195931059255E-04 .208335243507E-04 .221535855148E-04 .235584525170E-04 .250536247328E-04 .266449597174E-04 .283386965292E-04 .301414805655E-04 .320603900083E-04 .341029639827E-04 .362772325379E-04 .385917485686E-04 .410556217999E-04 .436785549684E-04 .464708823404E-04 .494436107148E-04 .526084630715E-04 .559779250320E-04 .595652943117E-04 .633847333553E-04 .674513253550E-04 .717811338686E-04 .763912662638E-04 .812999412304E-04 .865265606192E-04 .920917858780E-04 .980176193759E-04 .104327490922E-03 .111046349803E-03 .118200762693E-03 .125819017788E-03 .133931235567E-03 .142569486591E-03 .151767916764E-03 .161562880536E-03 .171993082532E-03 .183099728119E-03 .194926683483E-03 .207520645769E-03 .220931323935E-03 .235211630950E-03 .250417888030E-03 .266610041664E-03 .283851894174E-03 .302211348653E-03 .321760669129E-03 .342576756879E-03 .364741443858E-03 .388341804248E-03 .413470485229E-03 .440226058081E-03 .468713390831E-03 .499044043701E-03 .531336688690E-03 .565717554690E-03 .602320899606E-03 .641289511049E-03 .682775237216E-03 .726939549682E-03 .773954139915E-03 .824001551398E-03 .877275849343E-03 .933983330099E-03 .994343272418E-03 .105858873288E-02 .112696738786E-02 .119974242457E-02 .127719348371E-02 .135961765659E-02 .144733053946E-02 .154066734799E-02 .163998409513E-02 .174565883545E-02 .185809297922E-02 .197771267987E-02 .210497029824E-02 .224034594739E-02 .238434912175E-02 .253752041457E-02 .270043332766E-02 .287369617763E-02 .305795410281E-02 .325389117523E-02 .346223262206E-02 .368374716102E-02 .391924945424E-02 .416960268529E-02 .443572126384E-02 .471857366264E-02 .501918539142E-02 .533864211224E-02 .567809290071E-02 .603875365747E-02 .642191067419E-02 .682892435788E-02 .726123311760E-02 .772035741668E-02 .820790399386E-02 .872557025585E-02 .927514884363E-02 .985853237406E-02 .104777183579E-01 .111348142943E-01 .118320429415E-01 .125717477618E-01 .133563985387E-01 .141885971617E-01 .150710835746E-01 .160067418798E-01 .169986065912E-01 .180498690246E-01 .191638838151E-01 .203441755463E-01 .215944454747E-01 .229185783311E-01 .243206491763E-01 .258049302872E-01 .273758980435E-01 .290382397858E-01 .307968606070E-01 .326568900396E-01 .346236885944E-01 .367028541013E-01 .389002278011E-01 .412219001270E-01 .436742161149E-01 .462637803697E-01 .489974615148E-01 .518823960404E-01 .549259914628E-01 .581359287001E-01 .615201635596E-01 .650869272297E-01 .688447256561E-01 .728023376806E-01 .769688118071E-01 .813534614566E-01 .859658585633E-01 .908158253555E-01 .959134241600E-01 .101268945060E+00 .106892891232E+00 .112795961776E+00 .118989031859E+00 .125483129974E+00 .132289412126E+00 .139419132743E+00 .146883612124E+00 .154694200223E+00 .162862236587E+00 .171399006251E+00 .180315691438E+00 .189623318879E+00 .199332702626E+00 .209454382222E+00 .219998556134E+00 .230975010377E+00 .242393042285E+00 .254261379434E+00 .266588093757E+00 .279380510946E+00 .292645115267E+00 .306387449993E+00 .320612013705E+00 .335322152738E+00 .350519950160E+00 .366206111659E+00 .382379848796E+00 .399038760101E+00 .416178710538E+00 .433793709878E+00 .451875790568E+00 .470414885758E+00 .489398708235E+00 .508812631219E+00 .528639572274E+00 .548859882133E+00 .569451240978E+00 .590388565945E+00 .611643935260E+00 .633186536732E+00 .654982651249E+00 .676995685242E+00 .699186268990E+00 .721512438144E+00 .743929910111E+00 .766392449272E+00 .788852279292E+00 .811260446533E+00 .833566980334E+00 .855720670381E+00 .877668337660E+00 .899353638918E+00 .920715675787E+00 .941687868576E+00 .962197568574E+00 .982166651298E+00 .100151294021E+01 .102015199363E+01 .103799875596E+01 .105496880038E+01 .107097916191E+01 .108594890868E+01 .109979961198E+01 .111245582099E+01 .112384558656E+01 .113390103606E+01 .114255897893E+01 .114976151523E+01 .115545662016E+01 .115959868275E+01 .116214898256E+01 .116307609395E+01 .116235621160E+01 .115997339441E+01 .115591972686E+01 .115019539897E+01 .114280870681E+01 .113377597710E+01 .112312142000E+01 .111087691529E+01 .109708173797E+01 .108178222991E+01 .106503142466E+01 .104688863309E+01 .102741899727E+01 .100669302004E+01 .984786077433E+00 .961777919909E+00 .937752168082E+00 .912795806820E+00 .886998680870E+00 .860452992548E+00 pseudo wavefunction -.484981210978E-08 -.517034782341E-08 -.551206851094E-08 -.587637433806E-08 -.626475801078E-08 -.667881089163E-08 -.712022952007E-08 -.759082256394E-08 -.809251823026E-08 -.862737216586E-08 -.919757588020E-08 -.980546572483E-08 -.104535324664E-07 -.111444314922E-07 -.118809936904E-07 -.126662370496E-07 -.135033790242E-07 -.143958497179E-07 -.153473059381E-07 -.163616461796E-07 -.174430265977E-07 -.185958780382E-07 -.198249241917E-07 -.211352009493E-07 -.225320770357E-07 -.240212760075E-07 -.256088997050E-07 -.273014532535E-07 -.291058717175E-07 -.310295485164E-07 -.330803657184E-07 -.352667263361E-07 -.375975887573E-07 -.400825034508E-07 -.427316520988E-07 -.455558893145E-07 -.485667871188E-07 -.517766823542E-07 -.551987272348E-07 -.588469432353E-07 -.627362785426E-07 -.668826693048E-07 -.713031049274E-07 -.760156976854E-07 -.810397569369E-07 -.863958682405E-07 -.921059777024E-07 -.981934818985E-07 -.104683323739E-06 -.111602094668E-06 -.118978143621E-06 -.126841693181E-06 -.135224963409E-06 -.144162303866E-06 -.153690334354E-06 -.163848094962E-06 -.174677206025E-06 -.186222038665E-06 -.198529896590E-06 -.211651209915E-06 -.225639741800E-06 -.240552808727E-06 -.256451515356E-06 -.273401004888E-06 -.291470725984E-06 -.310734717316E-06 -.331271910937E-06 -.353166455688E-06 -.376508061991E-06 -.401392369417E-06 -.427921338563E-06 -.456203668815E-06 -.486355243727E-06 -.518499605835E-06 -.552768462857E-06 -.589302227334E-06 -.628250591955E-06 -.669773142891E-06 -.714040013671E-06 -.761232582275E-06 -.811544214289E-06 -.865181055189E-06 -.922362874974E-06 -.983323968628E-06 -.104831411609E-05 -.111759960569E-05 -.119146432515E-05 -.127021092481E-05 -.135416205761E-05 -.144366170111E-05 -.153907656682E-05 -.164079760268E-05 -.174924159491E-05 -.186485287559E-05 -.198810514322E-05 -.211950340349E-05 -.225958603841E-05 -.240892701210E-05 -.256813822235E-05 -.273787200769E-05 -.291882382001E-05 -.311173507387E-05 -.331739618410E-05 -.353664980411E-05 -.377039427823E-05 -.401958732215E-05 -.428524994664E-05 -.456847064045E-05 -.487040982971E-05 -.519230463199E-05 -.553547392442E-05 -.590132374684E-05 -.629135306184E-05 -.670715989552E-05 -.715044788386E-05 -.762303325178E-05 -.812685225324E-05 -.866396910290E-05 -.923658443192E-05 -.984704430227E-05 -.104978498167E-04 -.111916673638E-04 -.119313395390E-04 -.127198967884E-04 -.135605698208E-04 -.144568028395E-04 -.154122676493E-04 -.164308786935E-04 -.175168090859E-04 -.186745077006E-04 -.199087173907E-04 -.212244944099E-04 -.226272291173E-04 -.241226680492E-04 -.257169374475E-04 -.274165683426E-04 -.292285232921E-04 -.311602248837E-04 -.332195861213E-04 -.354150428150E-04 -.377555881103E-04 -.402508092948E-04 -.429109270347E-04 -.457468371992E-04 -.487701554451E-04 -.519932647415E-04 -.554293660300E-04 -.590925322246E-04 -.629977657738E-04 -.671610600158E-04 -.715994645799E-04 -.763311550967E-04 -.813755075024E-04 -.867531772382E-04 -.924861836656E-04 -.985980000416E-04 -.105113649416E-03 -.112059806841E-03 -.119464908308E-03 -.127359266843E-03 -.135775196248E-03 -.144747142968E-03 -.154311826620E-03 -.164508389768E-03 -.175378557515E-03 -.186966807581E-03 -.199320551533E-03 -.212490327900E-03 -.226530007941E-03 -.241497014895E-03 -.257452557576E-03 -.274461879255E-03 -.292594522804E-03 -.311924613169E-03 -.332531158267E-03 -.354498369521E-03 -.377916003265E-03 -.402879724382E-03 -.429491493587E-03 -.457859979859E-03 -.488100999641E-03 -.520337984491E-03 -.554702478997E-03 -.591334670871E-03 -.630383955233E-03 -.672009535253E-03 -.716381061407E-03 -.763679311757E-03 -.814096915808E-03 -.867839124620E-03 -.925124630025E-03 -.986186435947E-03 -.105127278500E-02 -.112064814366E-02 -.119459424963E-02 -.127341122495E-02 -.135741875884E-02 -.144695736438E-02 -.154238971319E-02 -.164410205274E-02 -.175250571083E-02 -.186803869227E-02 -.199116737280E-02 -.212238829545E-02 -.226223007509E-02 -.241125541661E-02 -.257006325271E-02 -.273929100740E-02 -.291961699125E-02 -.311176293483E-02 -.331649666668E-02 -.353463494230E-02 -.376704643060E-02 -.401465486427E-02 -.427844236040E-02 -.455945291747E-02 -.485879609456E-02 -.517765087828E-02 -.551726974244E-02 -.587898290465E-02 -.626420278338E-02 -.667442865800E-02 -.711125153281E-02 -.757635920484E-02 -.807154153319E-02 -.859869590547E-02 -.915983289434E-02 -.975708209415E-02 -.103926981239E-01 -.110690667787E-01 -.117887113070E-01 -.125542987846E-01 -.133686465518E-01 -.142347286687E-01 -.151556823396E-01 -.161348142443E-01 -.171756067022E-01 -.182817235853E-01 -.194570158786E-01 -.207055267687E-01 -.220314961265E-01 -.234393642216E-01 -.249337744894E-01 -.265195751357E-01 -.282018193402E-01 -.299857637799E-01 -.318768651574E-01 -.338807743746E-01 -.360033279438E-01 -.382505361751E-01 -.406285676186E-01 -.431437291758E-01 -.458024412223E-01 -.486112070040E-01 -.515765754874E-01 -.547050967478E-01 -.580032688826E-01 -.614774753320E-01 -.651339113731E-01 -.689784984396E-01 -.730167847954E-01 -.772538309642E-01 -.816940781960E-01 -.863411981213E-01 -.911979216348E-01 -.962658449377E-01 -.101545210582E+00 -.107034661297E+00 -.112730964337E+00 -.118628704124E+00 -.124719941003E+00 -.130993834083E+00 -.137436226395E+00 -.144029190886E+00 -.150750536321E+00 -.157573272760E+00 -.164465037129E+00 -.171387480481E+00 -.178295619833E+00 -.185137159123E+00 -.191851785719E+00 -.198370451268E+00 -.204614648334E+00 -.210495697360E+00 -.215914062001E+00 -.220758714745E+00 -.224906578945E+00 -.228222077845E+00 -.230556825737E+00 -.231749500859E+00 -.231625943672E+00 -.229999527507E+00 -.226671850571E+00 -.221433798478E+00 -.214067024019E+00 -.204345884891E+00 -.192039869647E+00 -.176916526010E+00 -.158744882936E+00 -.137299327216E+00 -.112363856392E+00 -.837365817490E-01 -.512342988727E-01 -.146968800657E-01 .260088236197E-01 .709859473943E-01 .120305874995E+00 .174008258681E+00 .232103247571E+00 .294576302991E+00 .361395818621E+00 .432523481873E+00 .507926877214E+00 .587593208619E+00 .671542180701E+00 .759835015304E+00 .852575310011E+00 .949896029782E+00 .105192549120E+01 .115872396875E+01 .127018390490E+01 ae wavefunction -.472972142918E-07 -.502809550806E-07 -.534288103841E-07 -.567511463376E-07 -.602589280982E-07 -.639637587127E-07 -.678779204502E-07 -.720144186850E-07 -.763870284991E-07 -.810103441839E-07 -.858998318329E-07 -.910718852297E-07 -.965438852493E-07 -.102334263003E-06 -.108462566976E-06 -.114949534415E-06 -.121817167258E-06 -.129088812886E-06 -.136789250034E-06 -.144944780187E-06 -.153583324830E-06 -.162734528931E-06 -.172429871071E-06 -.182702780661E-06 -.193588762704E-06 -.205125530605E-06 -.217353147560E-06 -.230314177081E-06 -.244053843261E-06 -.258620201423E-06 -.274064319833E-06 -.290440473203E-06 -.307806348753E-06 -.326223265675E-06 -.345756408863E-06 -.366475077844E-06 -.388452951924E-06 -.411768372601E-06 -.436504644380E-06 -.462750355197E-06 -.490599717748E-06 -.520152933077E-06 -.551516577900E-06 -.584804017213E-06 -.620135843834E-06 -.657640346671E-06 -.697454009563E-06 -.739722042725E-06 -.784598948928E-06 -.832249126674E-06 -.882847512809E-06 -.936580267150E-06 -.993645501866E-06 -.105425405856E-05 -.111863033617E-05 -.118701317300E-05 -.125965678643E-05 -.133683177411E-05 -.141882618059E-05 -.150594663373E-05 -.159851955544E-05 -.169689245154E-05 -.180143528606E-05 -.191254194527E-05 -.203063179756E-05 -.215615135520E-05 -.228957604481E-05 -.243141209348E-05 -.258219853821E-05 -.274250936664E-05 -.291295579765E-05 -.309418871095E-05 -.328690123535E-05 -.349183150611E-05 -.370976560225E-05 -.394154067566E-05 -.418804828444E-05 -.445023794372E-05 -.472912090816E-05 -.502577420112E-05 -.534134490660E-05 -.567705474085E-05 -.603420492205E-05 -.641418135716E-05 -.681846016657E-05 -.724861356850E-05 -.770631614632E-05 -.819335152374E-05 -.871161947402E-05 -.926314349147E-05 -.985007885489E-05 -.104747212149E-04 -.111395157389E-04 -.118470668493E-04 -.126001485937E-04 -.134017156874E-04 -.142549152716E-04 -.151630994328E-04 -.161298385333E-04 -.171589354034E-04 -.182544404518E-04 -.194206677522E-04 -.206622121687E-04 -.219839675864E-04 -.233911463173E-04 -.248892997576E-04 -.264843403742E-04 -.281825651068E-04 -.299906802733E-04 -.319158280768E-04 -.339656148119E-04 -.361481408815E-04 -.384720327353E-04 -.409464768529E-04 -.435812558999E-04 -.463867871929E-04 -.493741636189E-04 -.525551971624E-04 -.559424652033E-04 -.595493597589E-04 -.633901398516E-04 -.674799871989E-04 -.718350654298E-04 -.764725830466E-04 -.814108603629E-04 -.866694006623E-04 -.922689658382E-04 -.982316567873E-04 -.104580998849E-03 -.111342032598E-03 -.118541410310E-03 -.126207498457E-03 -.134370486580E-03 -.143062502931E-03 -.152317737297E-03 -.162172571418E-03 -.172665717465E-03 -.183838365057E-03 -.195734337304E-03 -.208400256429E-03 -.221885719513E-03 -.236243484964E-03 -.251529670323E-03 -.267803962068E-03 -.285129838100E-03 -.303574803640E-03 -.323210641291E-03 -.344113676076E-03 -.366365056271E-03 -.390051050939E-03 -.415263365070E-03 -.442099473296E-03 -.470662973201E-03 -.501063959273E-03 -.533419418624E-03 -.567853649606E-03 -.604498704550E-03 -.643494857881E-03 -.684991100905E-03 -.729145664640E-03 -.776126572096E-03 -.826112221479E-03 -.879292001813E-03 -.935866942584E-03 -.996050398993E-03 -.106006877451E-02 -.112816228242E-02 -.120058574819E-02 -.127760945438E-02 -.135952002996E-02 -.144662138604E-02 -.153923569969E-02 -.163770444806E-02 -.174238949449E-02 -.185367422883E-02 -.197196476371E-02 -.209769118885E-02 -.223130888538E-02 -.237329990186E-02 -.252417439411E-02 -.268447213049E-02 -.285476406427E-02 -.303565397484E-02 -.322778017906E-02 -.343181731416E-02 -.364847819316E-02 -.387851573387E-02 -.412272496194E-02 -.438194508841E-02 -.465706166164E-02 -.494900879337E-02 -.525877145797E-02 -.558738786364E-02 -.593595189361E-02 -.630561561495E-02 -.669759185176E-02 -.711315681877E-02 -.755365281070E-02 -.802049094143E-02 -.851515392653E-02 -.903919890089E-02 -.959426026278E-02 -.101820525334E-01 -.108043732203E-01 -.114631056710E-01 -.121602219014E-01 -.128977853819E-01 -.136779537620E-01 -.145029815117E-01 -.153752224563E-01 -.162971321775E-01 -.172712702531E-01 -.183003023012E-01 -.193870017956E-01 -.205342516131E-01 -.217450452710E-01 -.230224878088E-01 -.243697962648E-01 -.257902996938E-01 -.272874386674E-01 -.288647641945E-01 -.305259359947E-01 -.322747200519E-01 -.341149853699E-01 -.360506998488E-01 -.380859251916E-01 -.402248107488E-01 -.424715862004E-01 -.448305529696E-01 -.473060742583E-01 -.499025635849E-01 -.526244717049E-01 -.554762717828E-01 -.584624426843E-01 -.615874502485E-01 -.648557263988E-01 -.682716459433E-01 -.718395009169E-01 -.755634723093E-01 -.794475990276E-01 -.834957439357E-01 -.877115568190E-01 -.920984341201E-01 -.966594753010E-01 -.101397435685E+00 -.106314675651E+00 -.111413106042E+00 -.116694129691E+00 -.122158578946E+00 -.127806649124E+00 -.133637827802E+00 -.139650819919E+00 -.145843468624E+00 -.152212671869E+00 -.158754294736E+00 -.165463077504E+00 -.172332539485E+00 -.179354878656E+00 -.186520867151E+00 -.193819742660E+00 -.201239095858E+00 -.208764754003E+00 -.216380660953E+00 -.224068754007E+00 -.231808838183E+00 -.239578458923E+00 -.247352774701E+00 -.255104431738E+00 -.262803443932E+00 -.270417082304E+00 -.277909779489E+00 -.285243055812E+00 -.292375473379E+00 -.299262621885E+00 -.305857132353E+00 -.312108700555E+00 -.317964081005E+00 -.323366991509E+00 -.328257862320E+00 -.332573391282E+00 -.336245933981E+00 -.339202846653E+00 -.341365964104E+00 -.342651386442E+00 -.342969647620E+00 -.342226187351E+00 -.340321938987E+00 -.337153850317E+00 -.332615249521E+00 -.326596069998E+00 -.318982997231E+00 -.309659599289E+00 -.298506478860E+00 -.285401461366E+00 -.270219818938E+00 -.252834523455E+00 -.233116520853E+00 -.210935020787E+00 -.186157798852E+00 -.158651511825E+00 -.128282029310E+00 -.949147876852E-01 -.584151743313E-01 -.186489519831E-01 .245172652344E-01 .712154708464E-01 .121575645247E+00 .175725038559E+00 .233787339000E+00 .295881707164E+00 .362121655279E+00 .432613749428E+00 .507456111914E+00 .586736700416E+00 .670531340478E+00 .758901488024E+00 .851891699118E+00 .949526784875E+00 .105180863024E+01 .115871265627E+01 .127018390490E+01 End of Dataset)" }; // vector vasp_potcar_inputs_ /* std::string VaspTest::exeAppTest(std::ofstream &flog, std::ofstream &fresult, jobscript::JOBSCRIPT &job_script, const std::string &dir_path) const { std::string script_cmd_result; std::string module_load_result; std::string script_cmd; std::string modules_str; // job_script.generate(); fresult << module_name_version(job_script.getModules()[job_script.getModules().size()-1]) << "\t" << dir_path << "\t" << job_script.getJobName() << std::endl; // std::cout << job_script.getExeName() << " " << job_script.getExeArgs() << std::endl; if (modules_load(flog, job_script.getModules(), module_load_result)) { modules_str = modules_string(job_script.getModules()); #ifdef SLURM script_cmd = "module purge;" + modules_str + ";" + job_script.getExeName() + " " + job_script.getExeArgs() + " 2>&1"; #else script_cmd = "module purge;module load pbs;" + modules_str + ";" + job_script.getExeName() + " " + job_script.getExeArgs() + " 2>&1"; #endif flog << "Submit Command: " << script_cmd << std::endl; script_cmd_result = exec(script_cmd.c_str()); } else { script_cmd_result = "fatal"; } return script_cmd_result; } */ VaspTest::VaspTest(const jobscript::JOBSCRIPT &p_s): AppTest("vasp", "", p_s ,vasp_incar_inputs_.size()), log_file_name_(getHostName() + "_" + getTestName() + "_test.log"), result_file_name_(getHostName() + "_" + getTestName() + "_results.out"), flog_(log_file_name_,std::ios_base::app), fresult_(result_file_name_,std::ios_base::app) {} VaspTest::VaspTest(const jobscript::JOBSCRIPT &p_s, const std::string &s_a_n): AppTest("vasp", "", p_s ,vasp_incar_inputs_.size(), s_a_n), log_file_name_(getHostName() + "_" + getTestName() + "_test.log"), result_file_name_(getHostName() + "_" + getTestName() + "_results.out"), flog_(log_file_name_,std::ios_base::app), fresult_(result_file_name_,std::ios_base::app) {} /* void VaspTest::setTestNumber(int t_n) { test_number_ = t_n; } */ /* int VaspTest::getTestNumber(void) { return test_number_; } */ void VaspTest::runTest() { std::string cmd_result; std::string script_cmd_result; std::string vasp_dir; // std::cout << "Execute runTest member function from VaspTest object " << __FILE__ << "\t" <<__LINE__ << "\t" << getTestObjectCount() << "\t" << getTestNumber() << std::endl; if (!flog_.is_open()) { std::cerr << "Error: (" << __FILE__ << "," << __LINE__ << ") Opening file " << log_file_name_ << std::endl; exit(EXIT_FAILURE); } if (!fresult_.is_open()) { std::cerr << "Error: (" << __FILE__ << "," << __LINE__ << ") Opening file " << result_file_name_ << std::endl; exit(EXIT_FAILURE); } std::cout << "Testing: " << module_name_version(getJobScripts()[0].getModules()[getJobScripts()[0].getModules().size()-1]) << std::endl; int c_i = 0; for (auto vasp_incar_input: vasp_incar_inputs_) { // vasp_dir = "vasp_" + std::to_string(getTestObjectCount()) + "_" + std::to_string(c_i); vasp_dir = "vasp_" + std::to_string(getTestNumber()) + "_" + std::to_string(c_i); makeDir(vasp_dir); changeDir(vasp_dir); createFileFromStr("INCAR", vasp_incar_input); createFileFromStr("KPOINTS", vasp_kpoints_inputs_[c_i]); createFileFromStr("POSCAR", vasp_poscar_inputs_[c_i]); createFileFromStr("POTCAR", vasp_potcar_inputs_[c_i]); // script_cmd_result = subJobScript(flog_, getJobScripts()[c_i]); script_cmd_result = exeAppTest(flog_, fresult_, c_i, vasp_dir); checkSubmitResult(script_cmd_result, flog_, fresult_); changeDir(".."); ++c_i; } } } // namespace hpcswtest
85.521462
177
0.705939
[ "object", "vector" ]
2b0345d729789a7c6315e8d8e5c9f427eba97770
17,055
cc
C++
test/tensor.cc
fengwang/ceras
15d10e8909ded656f45201aecc45b8eefe961b2d
[ "BSD-3-Clause" ]
65
2020-12-07T01:15:41.000Z
2022-03-28T01:17:33.000Z
test/tensor.cc
fengwang/ceras
15d10e8909ded656f45201aecc45b8eefe961b2d
[ "BSD-3-Clause" ]
1
2021-04-08T13:20:39.000Z
2021-04-09T00:37:02.000Z
test/tensor.cc
fengwang/ceras
15d10e8909ded656f45201aecc45b8eefe961b2d
[ "BSD-3-Clause" ]
7
2021-01-07T08:52:39.000Z
2022-03-08T13:04:37.000Z
#include "../include/tensor.hpp" #include "../include/utils/fmt.hpp" #include <iostream> int main() { ceras::random_generator.seed( 123 ); ceras::tensor<double> A{ {2, 2}, {1.0, 2.0, 3.0, 1.0} }; std::cout << "A = \n" << A << std::endl; std::cout << "A*A = \n" << A*A << std::endl; ceras::tensor<double> B{ {2, 1}, {-1.0, 1.0} }; std::cout << "B = \n" << B << std::endl; std::cout << "A*B = \n" << A*B << std::endl; std::cout << "A*A*B = \n" << A*A*B << std::endl; int i = 0; { std::cout << fmt::format("test case: {}\n", i++) << std::endl; ceras::tensor<double> A{ {2, 2} }; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto all_one = ceras::ones<double>( {2, 2} ); std::cout << "ones( {2,2} ):\n" << all_one << std::endl; std::cout << "2*ones:\n" << 2.0 * all_one << std::endl; std::cout << "ones*2:\n" << all_one*2.0 << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::randn<double>( {2, 2} ); std::cout << "randn( {2,2} ):\n" << x << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::randn<double>( {2,} ); auto y = ceras::randn<double>( {2,} ); //auto y = ceras::ones<double>( {2,} ); std::cout << "x:\n" << x << std::endl; std::cout << "y:\n" << y << std::endl; std::cout << "x+y:\n" << x+y << std::endl; std::cout << "x-y:\n" << x-y << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::randn<double>( {2,2} ); auto y = ceras::randn<double>( {2,2} ); std::cout << "x:\n" << x << std::endl; std::cout << "y:\n" << y << std::endl; std::cout << "concatenate(x, y, 0):\n" << ceras::concatenate(x, y, 0) << std::endl; std::cout << "concatenate(x, y, 1):\n" << ceras::concatenate(x, y, 1) << std::endl; std::cout << "concatenate(x, y, -1):\n" << ceras::concatenate(x, y, -1) << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::randn<double>( {1,2} ); auto y = ceras::randn<double>( {2,2} ); std::cout << "x:\n" << x << std::endl; std::cout << "y:\n" << y << std::endl; std::cout << "concatenate(x, y, 0):\n" << ceras::concatenate(x, y, 0) << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::randn<double>( {2, 1} ); auto y = ceras::randn<double>( {2,2} ); std::cout << "x:\n" << x << std::endl; std::cout << "y:\n" << y << std::endl; std::cout << "concatenate(x, y, 1):\n" << ceras::concatenate(x, y, 1) << std::endl; } if (0) //runtime error expected { auto x = ceras::randn<double>( {2, 1} ); auto y = ceras::randn<double>( {2,2} ); std::cout << "x:\n" << x << std::endl; std::cout << "y:\n" << y << std::endl; std::cout << "concatenate(x, y, 0):\n" << ceras::concatenate(x, y, 0) << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::random<double>( {2, 2} ); std::cout << "randnom( {2,2} ):\n" << x << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::random<double>( {2, 3} ); std::cout << "x:\n" << x << std::endl; std::cout << "repmat(x, 1, 2):\n" << ceras::repmat(x, 1, 2) << std::endl; std::cout << "repmat(x, 2, 1):\n" << ceras::repmat(x, 2, 1) << std::endl; std::cout << "repmat(x, 2, 2):\n" << ceras::repmat(x, 2, 2) << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; std::cout << "Random matrix multiplication tests.\n"; unsigned long N = 10; for ( auto l = 1UL; l != N; ++l ) for ( auto m = 1UL; m != N; ++m ) for ( auto n = 1UL; n != N; ++n ) { auto x = ceras::random<double>( {l, m} ) * ceras::random<double>( {m,n} ); std::cout << x[0] << "\t"; } std::cout << "\n"; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::random<double>( {2, 3} ); std::cout << "x:\n" << x << std::endl; std::cout << "-x:\n" << -x << std::endl; std::cout << "-x+x:\n" << -x+x << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::random<double>( {2, 3} ); std::cout << "x:\n" << x << std::endl; std::cout << "x.ndim():\n" << x.ndim() << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::random<double>( {2, 3} ); std::cout << "x:\n" << x << std::endl; std::cout << "x.reset():\n" << x.reset() << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::random<double>( {2, 3} ); std::cout << "zeros_like(x):\n" << ceras::zeros_like(x) << std::endl; std::cout << "zeros([2, 3]):\n" << ceras::zeros<double>(x.shape()) << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::random<double>( {2, 3} ); std::cout << "x:\n" << x << std::endl; std::cout << "x-1:\n" << x-1.0 << std::endl; std::cout << "1-x:\n" << 1.0-x << std::endl; } // test gemm { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::tensor<double>{ {2, 2}, {0.0, 1.1, 2.3, 4.7} }; std::cout << "x:\n" << x << std::endl; auto y = ceras::tensor<double>{ {2, 2}, {0.5, 1.3, 2.1, 4.5} }; std::cout << "y:\n" << y << std::endl; auto a = ceras::tensor<double>{ {2, 2} }; ceras::gemm( x.data(), true, y.data(), true, 2, 2, 2, a.data() ); std::cout << "x' y' = \n" << a << std::endl; ceras::gemm( x.data(), true, y.data(), false, 2, 2, 2, a.data() ); std::cout << "x' y = \n" << a << std::endl; ceras::gemm( x.data(), false, y.data(), true, 2, 2, 2, a.data() ); std::cout << "x y' = \n" << a << std::endl; ceras::gemm( x.data(), false, y.data(), false, 2, 2, 2, a.data() ); std::cout << "x y = \n" << a << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::linspace( 0.0, 24.0, 24, false ); x.reshape( {2, 3, 4} ); std::cout << "x:\n" << x << std::endl; std::cout << "max(x):\n" << max(x) << std::endl; std::cout << "max(x, 0):\n" << max(x, 0) << std::endl; std::cout << "max(x, 1):\n" << max(x, 1) << std::endl; std::cout << "max(x, 2):\n" << max(x, 2) << std::endl; std::cout << "max(x, -1):\n" << max(x, -1) << std::endl; std::cout << "max(x, 0, true):\n" << max(x, 0, true) << std::endl; std::cout << "max(x, 1, true):\n" << max(x, 1, true) << std::endl; std::cout << "max(x, 2, true):\n" << max(x, 2, true) << std::endl; std::cout << "max(x, -1, true):\n" << max(x, -1, true) << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::linspace( 0.0, 24.0, 24, false ); x.reshape( {2, 3, 4} ); std::cout << "x:\n" << x << std::endl; std::cout << "min(x):\n" << min(x) << std::endl; std::cout << "min(x, 0):\n" << min(x, 0) << std::endl; std::cout << "min(x, 1):\n" << min(x, 1) << std::endl; std::cout << "min(x, 2):\n" << min(x, 2) << std::endl; std::cout << "min(x, -1):\n" << min(x, -1) << std::endl; std::cout << "min(x, 0, true):\n" << min(x, 0, true) << std::endl; std::cout << "min(x, 1, true):\n" << min(x, 1, true) << std::endl; std::cout << "min(x, 2, true):\n" << min(x, 2, true) << std::endl; std::cout << "min(x, -1, true):\n" << min(x, -1, true) << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::linspace( 0.0, 24.0, 24, false ); x.reshape( {2, 3, 4} ); std::cout << "x:\n" << x << std::endl; std::cout << "mean(x):\n" << mean(x) << std::endl; std::cout << "mean(x, 0):\n" << mean(x, 0) << std::endl; std::cout << "mean(x, 1):\n" << mean(x, 1) << std::endl; std::cout << "mean(x, 2):\n" << mean(x, 2) << std::endl; std::cout << "mean(x, -1):\n" << mean(x, -1) << std::endl; std::cout << "mean(x, 0, true):\n" << mean(x, 0, true) << std::endl; std::cout << "mean(x, 1, true):\n" << mean(x, 1, true) << std::endl; std::cout << "mean(x, 2, true):\n" << mean(x, 2, true) << std::endl; std::cout << "mean(x, -1, true):\n" << mean(x, -1, true) << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::linspace( 0.0, 24.0, 24, false ); x.reshape( {2, 3, 4} ); std::cout << "x:\n" << x << std::endl; std::cout << "sum(x):\n" << sum(x) << std::endl; std::cout << "sum(x, 0):\n" << sum(x, 0) << std::endl; std::cout << "sum(x, 1):\n" << sum(x, 1) << std::endl; std::cout << "sum(x, 2):\n" << sum(x, 2) << std::endl; std::cout << "sum(x, -1):\n" << sum(x, -1) << std::endl; std::cout << "sum(x, 0, true):\n" << sum(x, 0, true) << std::endl; std::cout << "sum(x, 1, true):\n" << sum(x, 1, true) << std::endl; std::cout << "sum(x, 2, true):\n" << sum(x, 2, true) << std::endl; std::cout << "sum(x, -1, true):\n" << sum(x, -1, true) << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::linspace( 0.0, 24.0, 24, false ); x.reshape( {6, 4} ); auto y = ceras::copy( x ); std::cout << "y:\n" << y << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::as_tensor( 1.0e-3 ); std::cout << "x:\n" << x << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::random<double>( {3, 3}, 0.0, 10.0 ); std::cout << "x:\n" << x << std::endl; auto sx = ceras::softmax( x ); std::cout << "softmax x:\n" << sx << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::linspace( 0.0, 6.0, 6, false ); x.reshape( {1, 6} ); std::cout << "x:\n" << x << std::endl; std::cout << "sum(x):\n" << sum(x) << std::endl; std::cout << "sum(x, 0):\n" << sum(x, 0) << std::endl; std::cout << "sum(x, 1):\n" << sum(x, 1) << std::endl; std::cout << "sum(x, -1):\n" << sum(x, -1) << std::endl; std::cout << "sum(x, 0, true):\n" << sum(x, 0, true) << std::endl; std::cout << "sum(x, 1, true):\n" << sum(x, 1, true) << std::endl; std::cout << "sum(x, -1, true):\n" << sum(x, -1, true) << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::linspace( 0.0, 6.0, 6, false ); x.reshape( { 6, 1} ); std::cout << "x:\n" << x << std::endl; std::cout << "sum(x):\n" << sum(x) << std::endl; std::cout << "sum(x, 0):\n" << sum(x, 0) << std::endl; std::cout << "sum(x, 1):\n" << sum(x, 1) << std::endl; std::cout << "sum(x, -1):\n" << sum(x, -1) << std::endl; std::cout << "sum(x, 0, true):\n" << sum(x, 0, true) << std::endl; std::cout << "sum(x, 1, true):\n" << sum(x, 1, true) << std::endl; std::cout << "sum(x, -1, true):\n" << sum(x, -1, true) << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::random<double>( {1, 2, 3, 4}, 0.0, 10.0 ); auto v4 = ceras::view_4d{ x.data(), 1, 2, 3, 4 }; std::cout << v4[0][0][0][0] << std::endl; std::cout << v4[0][1][2][3] << std::endl; auto v3 = ceras::view_3d{ x.data(), 2, 3, 4 }; std::cout << v3[0][0][0] << std::endl; std::cout << v3[1][2][3] << std::endl; v3[1][2][3] = 1.0; std::cout << v4[0][1][2][3] << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::random<double>( {1, 2, 3, 4}, 0.0, 10.0 ); std::cout << "Testing size(): expecting 24, got " << x.size() << std::endl; x.resize( {12, 1} ); std::cout << "Testing resize(): resize to {12, 1}, got:\n" << x << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::truncated_normal<double>( {3, 3}, 0.0, 10.0, 0.0, 1.0 ); std::cout << "x:\n" << x << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::random<float>( {8, 5} ); std::cout << "x:\n" << x << std::endl; //auto x12 = x.slice( 1, 2 ); //std::cout << "x(1,2):\n" << x12 << std::endl; //auto x68 = x.slice( 6, 8 ); //std::cout << "x(6,8):\n" << x68 << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::random<double>( {2,2} ); auto y = ceras::random<double>( {2,2} ); std::cout << "x:\n" << x << std::endl; std::cout << "y:\n" << y << std::endl; std::cout << "concatenate(x, y, 0):\n" << ceras::concatenate(x, y, 0) << std::endl; std::cout << "concatenate(x, y, 1):\n" << ceras::concatenate(x, y, 1) << std::endl; std::cout << "concatenate(x, y, -1):\n" << ceras::concatenate(x, y, -1) << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; ceras::tensor<unsigned char> x {{3, 3}}; std::cout << x << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; ceras::tensor<float> t = ceras::random<float>( {1, 2, 3, 4, 5, 6, 7} ); auto v = ceras::view<float, 7>{t.data(), {1, 2, 3,4 ,5, 6, 7}}; //auto v = ceras::view{t.data(), {1, 2, 3,4 ,5, 6, 7}}; std::cout << v[0][1][2][3][4][5][6] << std::endl; std::cout << v[0][1][2][1][2][5][3] << std::endl; } if (0) { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::random<double>( {2, 2} ); auto y = ceras::random<double>( {1, 2} ); std::cout << "x:\n" << x << std::endl; std::cout << "y:\n" << y << std::endl; x += y; std::cout << "x+=y:\n" << x << std::endl; } if (0) { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::random<double>( {2, 2} ); auto y = ceras::random<double>( {1, 2} ); std::cout << "x:\n" << x << std::endl; std::cout << "y:\n" << y << std::endl; x -= y; std::cout << "x-=y:\n" << x << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; std::vector<unsigned long> sa{8, 1, 6, 1}; std::vector<unsigned long> sb{7, 1, 5}; auto sab = ceras::broadcast_shape( sa, sb ); std::cout << fmt::format( "broadcasting shape {} and {}, got result {}.", sa, sb, sab ) << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; std::vector<unsigned long> sa{256, 256, 3}; std::vector<unsigned long> sb{3,}; auto sab = ceras::broadcast_shape( sa, sb ); std::cout << fmt::format( "broadcasting shape {} and {}, got result {}.", sa, sb, sab ) << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::random<double>( {7,} ); auto y = ceras::broadcast_tensor( x, std::vector<unsigned long>{ {9, 7} } ); std::cout << "x:\n" << x << std::endl; std::cout << "broadcasted(x, {9, 7}):\n" << y << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::random<double>( {7,1} ); auto y = ceras::broadcast_tensor( x, std::vector<unsigned long>{ {7, 9} } ); std::cout << "x:\n" << x << std::endl; std::cout << "broadcasted(x, {7, 9}):\n" << y << std::endl; } { std::cout << fmt::format("test case: {}\n", i++) << std::endl; auto x = ceras::random<double>( {2, 3, 4} ); std::cout << "x.reshape({3, 8})\n" << x.reshape({3, 8}) << std::endl; std::cout << "x.reshape({4, -1})\n" << x.reshape({4, -1UL}) << std::endl; } return 0; }
39.941452
109
0.428496
[ "shape", "vector" ]
2b15082b47ddb4f8be72a6eb3079843a31153bfe
1,671
hpp
C++
legacy/galaxy/resource/FontBook.hpp
reworks/rework
90508252c9a4c77e45a38e7ce63cfd99f533f42b
[ "Apache-2.0" ]
19
2020-02-02T16:36:46.000Z
2021-12-25T07:02:28.000Z
legacy/galaxy/resource/FontBook.hpp
reworks/rework
90508252c9a4c77e45a38e7ce63cfd99f533f42b
[ "Apache-2.0" ]
103
2020-10-13T09:03:42.000Z
2022-03-26T03:41:50.000Z
legacy/galaxy/resource/FontBook.hpp
reworks/rework
90508252c9a4c77e45a38e7ce63cfd99f533f42b
[ "Apache-2.0" ]
5
2020-03-13T06:14:37.000Z
2021-12-12T02:13:46.000Z
/// /// FontBook.hpp /// galaxy /// /// Refer to LICENSE.txt for more details. /// #ifndef GALAXY_RESOURCE_FONTBOOK_HPP_ #define GALAXY_RESOURCE_FONTBOOK_HPP_ #include "galaxy/fs/Serializable.hpp" #include "galaxy/graphics/text/Font.hpp" #include "galaxy/resource/ResourceCache.hpp" namespace galaxy { namespace res { /// /// Resource manager for fonts. /// class FontBook final : public ResourceCache<graphics::Font>, public fs::Serializable { public: /// /// Constructor. /// FontBook() noexcept = default; /// /// JSON constructor. /// /// \param file JSON file to load. /// FontBook(std::string_view file); /// /// Destructor. /// virtual ~FontBook() noexcept; /// /// Create FontBook from JSON. /// /// \param file JSON file to load. /// void create_from_json(std::string_view file); /// /// Clean up. /// void clear() noexcept override; /// /// Serializes object. /// /// \return JSON object containing data to write out. /// [[nodiscard]] nlohmann::json serialize() override; /// /// Deserializes from object. /// /// \param json Json object to retrieve data from. /// void deserialize(const nlohmann::json& json) override; private: /// /// Copy constructor. /// FontBook(const FontBook&) = delete; /// /// Move constructor. /// FontBook(FontBook&&) = delete; /// /// Copy assignment operator. /// FontBook& operator=(const FontBook&) = delete; /// /// Move assignment operator. /// FontBook& operator=(FontBook&&) = delete; }; } // namespace res } // namespace galaxy #endif
18.163043
86
0.605625
[ "object" ]
1a7878395f0cb031f010677ab3212a24e9be3dc7
1,887
cpp
C++
src/texture.cpp
FrMarchand/pbr-material-viewer
cc665a10f036dc13b6fd6c94c48d5b8ddc3596a4
[ "MIT" ]
5
2019-08-07T09:48:04.000Z
2021-08-12T07:31:51.000Z
src/texture.cpp
FrMarchand/pbr-material-viewer
cc665a10f036dc13b6fd6c94c48d5b8ddc3596a4
[ "MIT" ]
null
null
null
src/texture.cpp
FrMarchand/pbr-material-viewer
cc665a10f036dc13b6fd6c94c48d5b8ddc3596a4
[ "MIT" ]
4
2020-03-19T04:30:55.000Z
2021-08-08T01:28:28.000Z
#include "texture.h" #include <stb_image.h> #include <iostream> #include <vector> #include <cmrc\cmrc.hpp> CMRC_DECLARE(resources); Texture::Texture() { glGenTextures(1, &mID); } Texture::Texture(const GLchar* texturePath, bool srgb) { glGenTextures(1, &mID); loadTexture(texturePath, srgb); } Texture::~Texture() { release(); } GLuint Texture::getId() const { return mID; } void Texture::bind(GLenum textureUnit) const { glActiveTexture(textureUnit); glBindTexture(GL_TEXTURE_2D, mID); } void Texture::loadTexture(const GLchar* texturePath, bool srgb) { glBindTexture(GL_TEXTURE_2D, mID); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps int width, height, nrChannels; stbi_set_flip_vertically_on_load(false); unsigned char *data = stbi_load(texturePath, &width, &height, &nrChannels, 4); if (!data) { // Fall back to embedded resources auto fs = cmrc::resources::get_filesystem(); if (fs.exists(texturePath)) { auto shaderRes = fs.open(texturePath); std::string str(shaderRes.begin(), shaderRes.size()); data = stbi_load_from_memory((const unsigned char*)str.c_str(), str.size(), &width, &height, &nrChannels, 4); } } if (data) { GLenum format = GL_RGBA; if (srgb) { format = GL_SRGB_ALPHA; } glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); } void Texture::release() { glDeleteTextures(1, &mID); mID = 0; }
23.886076
112
0.732909
[ "vector" ]
1a799b585e9a9fbf481ab70eb15628cbb17da394
1,706
cpp
C++
sem_2/course_algorithms/contest_5/E.cpp
KingCakeTheFruity/mipt
e32cfe5e53236cdd2933d8b666ca995508300f0f
[ "MIT" ]
null
null
null
sem_2/course_algorithms/contest_5/E.cpp
KingCakeTheFruity/mipt
e32cfe5e53236cdd2933d8b666ca995508300f0f
[ "MIT" ]
null
null
null
sem_2/course_algorithms/contest_5/E.cpp
KingCakeTheFruity/mipt
e32cfe5e53236cdd2933d8b666ca995508300f0f
[ "MIT" ]
null
null
null
/* Сложность задачи заключается только в том, чтобы ввести данные. В остальном все как обычно - из ненас. L запускаем дфс по ориентированным ребрам. Делаем вид, что сами нашли парсоч */ #include <cstdlib> #include <cstdio> #include <vector> #include <set> using std::vector; using std::set; void dfs(const vector<set<int>> &g, int v, vector<int> &used) { if (used[v]) { return; } used[v] = true; for (auto u : g[v]) { dfs(g, u, used); } } int main() { int n, m; scanf("%d %d", &m, &n); vector<int> L(m); vector<int> R(n); vector<set<int>> g(m + n); for (int i = 0; i < m; ++i) { int x = 0; scanf("%d", &x); for (int j = 0; j < x; ++j) { int y = 0; scanf("%d", &y); --y; g[i].insert(m + y); // g[m + y].insert(i); - пока что ребра направляем только направо } } vector<int> matching(m + n, -1); for (int i = 0; i < m; ++i) { int x = 0; scanf("%d", &x); --x; if (x == -1) { continue; } matching[i] = m + x; matching[m + x] = i; g[i].erase(m + x); // | g[m + x].insert(i); // | переворачивает ребра, входящие в парсоч } vector<int> used(m + n); for (int v = 0; v < m; ++v) { if (matching[v] == -1) { dfs(g, v, used); // запускаем дфс из ненасыщенных левых } } vector<int> l_ans; vector<int> r_ans; for (int i = 0; i < m; ++i) { if (!used[i]) { l_ans.push_back(i); } } for (int i = 0; i < n; ++i) { if (used[m + i]) { r_ans.push_back(i); } } printf("%lu\n", l_ans.size() + r_ans.size()); printf("%lu ", l_ans.size()); for (auto x : l_ans) { printf("%d ", x + 1); } printf("\n"); printf("%lu ", r_ans.size()); for (auto x : r_ans) { printf("%d ", x + 1); } printf("\n"); return 0; }
17.232323
118
0.523447
[ "vector" ]
1a7a17cfb50d65b0e5858b3379a7130c1f15250f
5,669
cpp
C++
source/FAST/Data/ImagePyramid.cpp
nikolaseu/FAST
4aa0dc0f6337449faeaf55e8be7043c6ab2e86e9
[ "BSD-2-Clause" ]
null
null
null
source/FAST/Data/ImagePyramid.cpp
nikolaseu/FAST
4aa0dc0f6337449faeaf55e8be7043c6ab2e86e9
[ "BSD-2-Clause" ]
null
null
null
source/FAST/Data/ImagePyramid.cpp
nikolaseu/FAST
4aa0dc0f6337449faeaf55e8be7043c6ab2e86e9
[ "BSD-2-Clause" ]
null
null
null
#include "ImagePyramid.hpp" #include <openslide/openslide.h> #include <FAST/Utility.hpp> #include <FAST/Data/Image.hpp> #include <FAST/Algorithms/ImageChannelConverter/ImageChannelConverter.hpp> namespace fast { void ImagePyramid::create(openslide_t *fileHandle, std::vector<ImagePyramid::Level> levels) { m_fileHandle = fileHandle; m_levels = levels; for(int i = 0; i < m_levels.size(); ++i) { int x = m_levels.size() - i - 1; m_levels[i].patches = x*x*x + 10; } mBoundingBox = BoundingBox(Vector3f(getFullWidth(), getFullHeight(), 0)); } int ImagePyramid::getNrOfLevels() { return m_levels.size(); } int ImagePyramid::getLevelWidth(int level) { return m_levels.at(level).width; } int ImagePyramid::getLevelHeight(int level) { return m_levels.at(level).height; } int ImagePyramid::getLevelPatches(int level) { return m_levels.at(level).patches; } int ImagePyramid::getFullWidth() { return m_levels[0].width; } int ImagePyramid::getFullHeight() { return m_levels[0].height; } void ImagePyramid::free(ExecutionDevice::pointer device) { freeAll(); } void ImagePyramid::freeAll() { m_levels.clear(); openslide_close(m_fileHandle); } ImagePyramid::~ImagePyramid() { freeAll(); } ImagePyramid::Patch ImagePyramid::getPatch(std::string tile) { auto parts = split(tile, "_"); if(parts.size() != 3) throw Exception("incorrect tile format"); int level = std::stoi(parts[0]); int tile_x = std::stoi(parts[1]); int tile_y = std::stoi(parts[2]); return getPatch(level, tile_x, tile_y); } ImagePyramid::Patch ImagePyramid::getPatch(int level, int tile_x, int tile_y) { // Create patch int levelWidth = getLevelWidth(level); int levelHeight = getLevelHeight(level); int tiles = getLevelPatches(level); ImagePyramid::Patch tile; tile.offsetX = tile_x * (int) std::floor((float) levelWidth / tiles); tile.offsetY = tile_y * (int) std::floor((float) levelHeight / tiles); tile.width = std::floor(((float) levelWidth / tiles)); if(tile_x == tiles - 1) tile.width = levelWidth - tile.offsetX; tile.height = std::floor((float) levelHeight / tiles); if(tile_y == tiles - 1) tile.height = levelHeight - tile.offsetY; //std::cout << "Loading data from disk for tile " << tile_x << " " << tile_y << " " << level << " " << tile_offset_x << " " << tile_offset_y << std::endl; // Read the actual data std::size_t bytes = tile.width*tile.height*4; tile.data = std::shared_ptr<uchar[]>(new uchar[bytes]); // TODO use make_shared instead (C++20) float scale = (float)getFullWidth()/levelWidth; openslide_read_region(m_fileHandle, (uint32_t *) tile.data.get(), tile.offsetX*scale, tile.offsetY*scale, level, tile.width, tile.height); return tile; } SharedPointer<Image> ImagePyramid::getLevelAsImage(int level) { if(level < 0 || level >= getNrOfLevels()) throw Exception("Incorrect level given to getLevelAsImage" + std::to_string(level)); int width = getLevelWidth(level); int height = getLevelHeight(level); if(width > 16384 || height > 16384) throw Exception("Image level is too large to convert into a FAST image"); auto image = Image::New(); auto data = make_uninitialized_unique<uchar[]>(width*height*4); openslide_read_region(m_fileHandle, (uint32_t *)data.get(), 0, 0, level, width, height); image->create(width, height, TYPE_UINT8, 4, std::move(data)); image->setSpacing(Vector3f( (float)getFullWidth() / width, (float)getFullHeight() / height, 1.0f )); SceneGraph::setParentNode(image, std::dynamic_pointer_cast<SpatialDataObject>(mPtr.lock())); // Data is stored as BGRA, need to delete alpha channel and reverse it auto channelConverter = ImageChannelConverter::New(); channelConverter->setChannelsToRemove(false, false, false, true); channelConverter->setReverseChannels(true); channelConverter->setInputData(image); auto port = channelConverter->getOutputPort(); channelConverter->update(); return port->getNextFrame<Image>(); } SharedPointer<Image> ImagePyramid::getPatchAsImage(int level, int offsetX, int offsetY, int width, int height) { if(width > 16384 || height > 16384) throw Exception("Image level is too large to convert into a FAST image"); if(offsetX < 0 || offsetY < 0 || width <= 0 || height <= 0) throw Exception("Offset and size must be positive"); if(offsetX + width >= getLevelWidth(level) || offsetY + height >= getLevelHeight(level)) throw Exception("offset + size exceeds level size"); auto image = Image::New(); auto data = make_uninitialized_unique<uchar[]>(width*height*4); float scale = (float)getFullWidth()/getLevelWidth(level); openslide_read_region(m_fileHandle, (uint32_t *)data.get(), offsetX*scale, offsetY*scale, level, width, height); image->create(width, height, TYPE_UINT8, 4, std::move(data)); image->setSpacing(Vector3f( scale, scale, 1.0f )); // TODO Set transformation SceneGraph::setParentNode(image, std::dynamic_pointer_cast<SpatialDataObject>(mPtr.lock())); // Data is stored as BGRA, need to delete alpha channel and reverse it auto channelConverter = ImageChannelConverter::New(); channelConverter->setChannelsToRemove(false, false, false, true); channelConverter->setReverseChannels(true); channelConverter->setInputData(image); auto port = channelConverter->getOutputPort(); channelConverter->update(); return port->getNextFrame<Image>(); } }
35.43125
159
0.67825
[ "vector" ]
1a7ca5e03cfb7cba1e8b85a440ecc7a1a48dfb7b
2,632
hxx
C++
main/autodoc/inc/ary/idl/i_namelookup.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/autodoc/inc/ary/idl/i_namelookup.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/autodoc/inc/ary/idl/i_namelookup.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef ARY_IDL_I_NAMELOOKUP_HXX #define ARY_IDL_I_NAMELOOKUP_HXX // BASE CLASSES #include <ary/idl/i_types4idl.hxx> // USED SERVICES #include <ary/stdconstiter.hxx> #include <ary/itrange.hxx> #include <vector> #include <map> namespace ary { namespace idl { /** This class finds all occurrences in the current language of a name in the repository. */ class NameLookup { public: struct NameProperties { NameProperties() : nId(0), nClass(0), nOwner(0) {} NameProperties( Ce_id i_id, ClassId i_class, Ce_id i_owner ) : nId(i_id), nClass(i_class), nOwner(i_owner) {} Ce_id nId; ClassId nClass; Ce_id nOwner; }; /// Map from Name to NameProperties. typedef std::multimap<String, NameProperties> Map_Names; // LIFECYCLE NameLookup(); ~NameLookup(); // OPERATIONS void Add_Name( const String & i_name, Ce_id i_id, ClassId i_class, Ce_id i_owner ); private: // DATA Map_Names aNames; }; } // namespace idl } // namespace ary #endif
28.608696
65
0.493161
[ "vector" ]
1a7de9ade3c62261c27e123243cbc8ac75359c8f
13,230
cpp
C++
examples/SSAODemo.cpp
wessles/vkmerc
cb087f425cdbc0b204298833474cf62874505388
[ "Unlicense" ]
6
2020-10-09T02:48:54.000Z
2021-07-30T06:31:20.000Z
examples/SSAODemo.cpp
wessles/vkmerc
cb087f425cdbc0b204298833474cf62874505388
[ "Unlicense" ]
null
null
null
examples/SSAODemo.cpp
wessles/vkmerc
cb087f425cdbc0b204298833474cf62874505388
[ "Unlicense" ]
null
null
null
#include <Tracy.hpp> #include <iostream> #include <filesystem> #include <VulkanContext.h> #include <VulkanDevice.h> #include <VulkanSwapchain.h> #include <VulkanTexture.h> #include <VulkanDescriptorSet.h> #include <VulkanMesh.h> #include <VulkanMaterial.h> #include <VulkanUniform.h> #include <shader/ShaderCache.h> #include <scene/Skybox.hpp> #include <util/CascadedShadowmap.hpp> #define TINYGLTF_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #include <pbr/VulkanGltfModel.hpp> #include <pbr/VulkanObjModel.h> #include <pbr/Ue4BrdfLut.hpp> #include <pbr/CubemapFiltering.hpp> #include <rendergraph/RenderGraph.h> #include <scene/Scene.h> #include <BaseEngine.h> #include <util/FlyCam.h> #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtx/string_cast.hpp> #include <imgui\VulkanImguiInstance.hpp> #include <glm/gtc/random.hpp> #include <glm/gtx/transform2.hpp> using namespace std; using namespace vku; void* operator new(std::size_t count) { auto ptr = malloc(count); TracyAlloc(ptr, count); return ptr; } void operator delete(void* ptr) noexcept { TracyFree(ptr); free(ptr); } class Engine : public BaseEngine { public: Engine() { this->windowTitle = "SSAO Demo"; this->width = 900; this->height = 900; } FlyCam* flycam; Scene* scene; RenderGraphSchema* graphSchema; RenderGraph* graph; Pass* mainPass; Pass* blitPass; VulkanObjModel* platform; VulkanGltfModel* gltf; VulkanTexture* brdf; VulkanTexture* irradiancemap; VulkanTexture* specmap; VulkanTexture* skybox; VulkanImguiInstance* gui; std::vector<VkCommandBuffer> cmdBufs; struct SSAOParams { float nearPlane; float farPlane; float intensity; }; SSAOParams ssao{}; VulkanUniform* ssaoUniform; struct BlurUniform { glm::vec2 dir; int pixelStep; } ssaoHorizBlurParams{ {1,0}, 4 }, ssaoVertiBlurParams{ {0,1}, 4 }; VulkanUniform* ssaoHorizBlurUniform; VulkanUniform* ssaoVertiBlurUniform; //////////// // LIGHTS // //////////// struct LightUniform { glm::vec4 colorAndIntensity; // rgb=color, a=intensity }; struct LightPassUniform { uint32_t lightCount; LightUniform lights[]; }; VulkanUniform* lightDataUniform; struct Light : Object { VulkanMeshBuffer *meshBuf; Pass* pass; Light(VulkanDevice* device, Pass *pass) { meshBuf = new VulkanMeshBuffer(device, vku::sphere); this->pass = pass; } ~Light() { delete meshBuf; } virtual void render(VkCommandBuffer cmdBuf, uint32_t swapIdx, bool noMaterial) override { vkCmdPushConstants(cmdBuf, this->pass->material->pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(glm::mat4), &this->localTransform); meshBuf->draw(cmdBuf); } virtual glm::mat4 getAABBTransform() override { return glm::mat4(); } }; void initLights(Scene* scene, Pass * lights) { auto x = new Light(context->device, lights); scene->addObject(x); x->layer = 1 << 3; // light layer x->localTransform = glm::scale(glm::vec3(30.0,30.0,30.0)); } // Inherited via BaseEngine void postInit() { SceneInfo sInfo{}; scene = new Scene(context->device, sInfo); flycam = new FlyCam(context->windowHandle); graphSchema = new RenderGraphSchema(); { // ATTACHMENTS AttachmentSchema* albedo = graphSchema->attachment("albedo"); albedo->format = VK_FORMAT_R8G8B8A8_SRGB; albedo->isSampled = true; AttachmentSchema* emissive = graphSchema->attachment("emissive"); emissive->format = VK_FORMAT_R8G8B8A8_SRGB; emissive->isSampled = true; AttachmentSchema* normal = graphSchema->attachment("normal"); normal->format = VK_FORMAT_R16G16B16A16_SNORM; normal->isSampled = true; AttachmentSchema* position = graphSchema->attachment("position"); position->format = VK_FORMAT_R16G16B16A16_SFLOAT; position->isSampled = true; AttachmentSchema* material = graphSchema->attachment("material"); material->format = VK_FORMAT_R8G8B8A8_UNORM; material->isSampled = true; AttachmentSchema* ao = graphSchema->attachment("ao"); ao->format = VK_FORMAT_R8_UNORM; ao->isSampled = true; AttachmentSchema* ao2 = graphSchema->attachment("ao2"); ao2->format = VK_FORMAT_R8_UNORM; ao2->isSampled = true; AttachmentSchema* depth = graphSchema->attachment("depth"); depth->format = context->device->swapchain->depthFormat; depth->isDepth = true; depth->isSampled = true; AttachmentSchema* light = graphSchema->attachment("light"); light->format = VK_FORMAT_R8G8B8A8_SRGB; light->isSampled = true; AttachmentSchema* swap = graphSchema->attachment("swap"); swap->format = context->device->swapchain->screenFormat; swap->isSwapchain = true; // PASSES PassSchema* main = graphSchema->pass("main"); main->layerMask = 1 << 0; PassSchema* ssao = graphSchema->blitPass("ssao", { "ssao/ssao.frag", {} }); ssao->layerMask = 0; PassSchema* ssao_blur_x = graphSchema->blitPass("ssao_blur_x", { "bloom/blur.frag", {} }); ssao_blur_x->layerMask = 0; PassSchema* ssao_blur_y = graphSchema->blitPass("ssao_blur_y", { "bloom/blur.frag", {} }); ssao_blur_y->layerMask = 0; PassSchema* skybox = graphSchema->pass("skybox"); skybox->layerMask = 1 << 1; //PassSchema* merge = graphSchema->blitPass("merge", { "pbr/pbr_merge.frag", {} }); //merge->layerMask = 0; PassSchema* lights = graphSchema->pass("lights"); lights->materialOverride = true; VulkanMaterialInfo lightMatInfo{}; lightMatInfo.rasterizer.cullMode = VK_CULL_MODE_FRONT_BIT; lightMatInfo.shaderStages = { {"pbr/pbr_light.vert", {}}, {"pbr/pbr_light.frag", {}} }; lights->overrideMaterialInfo = lightMatInfo; lights->layerMask = 1 << 3; PassSchema* blit = graphSchema->blitPass("blit", { "blit/blit.frag",{} }); blit->layerMask = 1 << 2; // ATTACHMENT ACCESSES main->write(0, albedo, PassWriteOptions{ .clear = true, .colorClearValue = { 0.0f, 0.0f, 0.0f, 0.0f } }); main->write(1, emissive, PassWriteOptions{}); main->write(2, material, PassWriteOptions{}); main->write(3, normal, PassWriteOptions{}); main->write(4, position, PassWriteOptions{}); main->write(5, ao, PassWriteOptions{ .colorClearValue = {1.0} }); main->write(6, depth, PassWriteOptions{}); ssao->read(0, position, PassReadOptions{}); ssao->read(1, normal, PassReadOptions{}); ssao->read(2, depth, PassReadOptions{}); ssao->read(3, ao, PassReadOptions{}); ssao->write(0, ao2, PassWriteOptions{}); ssao_blur_x->read(0, ao2, PassReadOptions{}); ssao_blur_x->write(0, ao, PassWriteOptions{}); ssao_blur_y->read(0, ao, PassReadOptions{}); ssao_blur_y->write(0, ao2, PassWriteOptions{}); skybox->write(0, light, PassWriteOptions{ .clear = false, .sampled = false }); //merge->read(0, albedo); //merge->read(1, emissive); //merge->read(2, material); //merge->read(3, normal); //merge->read(4, position); //merge->read(5, ao2); //merge->write(0, light, PassWriteOptions{ .clear = false, .sampled = false }); lights->read(0, albedo); lights->read(1, emissive); lights->read(2, material); lights->read(3, normal); lights->read(4, position); lights->read(5, ao2); lights->write(0, light, PassWriteOptions{ .clear = false }); blit->read(0, light); blit->write(0, swap, PassWriteOptions{ .sampled = false }); } graph = new RenderGraph(graphSchema, scene, context->device->swapchain->swapChainLength); graph->createLayouts(); mainPass = graph->getPass("main"); Pass* merge = graph->getPass("merge"); Pass* lights = graph->getPass("lights"); initLights(scene, lights); gui = new VulkanImguiInstance(context, graph->getPass("blit")->pass); gui->layer = 1 << 2; scene->addObject(gui); ssaoUniform = new VulkanUniform(context->device, sizeof(SSAOParams)); for (VulkanDescriptorSet* set : graph->getPass("ssao")->materialInstance->descriptorSets) { set->write(0, this->ssaoUniform); } ssaoHorizBlurUniform = new VulkanUniform(context->device, sizeof(BlurUniform)); ssaoVertiBlurUniform = new VulkanUniform(context->device, sizeof(BlurUniform)); for (VulkanDescriptorSet* set : graph->getPass("ssao_blur_x")->materialInstance->descriptorSets) { set->write(0, ssaoHorizBlurUniform); } for (VulkanDescriptorSet* set : graph->getPass("ssao_blur_y")->materialInstance->descriptorSets) { set->write(0, ssaoVertiBlurUniform); } Skybox* skybox = new Skybox("res/textures/cubemap_day/", scene, graph->getPass("skybox")); skybox->layer = 1 << 1; scene->addObject(skybox); brdf = generateBRDFLUT(context->device); irradiancemap = generateIrradianceCube(context->device, skybox->skybox); specmap = generatePrefilteredCube(context->device, skybox->skybox); //for (VulkanDescriptorSet* set : merge->materialInstance->descriptorSets) { // set->write(0, specmap); // set->write(1, irradiancemap); // set->write(2, brdf); //} for (VulkanDescriptorSet* set : lights->materialInstance->descriptorSets) { set->write(0, specmap); set->write(1, irradiancemap); set->write(2, brdf); } gltf = new VulkanGltfModel("res/models/DamagedHelmet.glb", scene, mainPass); gltf->localTransform *= glm::scale(glm::vec3(0.5f)); gltf->localTransform *= glm::translate(glm::vec3(0, 0.8, 0)); scene->addObject(gltf); scene->addObject(new VulkanGltfModel("res/models/Sponza/glTF/Sponza.gltf", scene, mainPass)); cmdBufs.resize(context->device->swapchain->swapChainLength); for (uint32_t i = 0; i < cmdBufs.size(); i++) { cmdBufs[i] = context->device->createCommandBuffer(); } buildSwapchainDependants(); } float lightZenith{}; float lightAzimuth{}; int k = 0; void updateUniforms(uint32_t i) { flycam->update(); static auto startTime = std::chrono::high_resolution_clock::now(); auto currentTime = std::chrono::high_resolution_clock::now(); float time = std::chrono::duration<float, std::chrono::seconds::period>(currentTime - startTime).count(); float n = 0.01f; float f = 100.0f; VkExtent2D swapchainExtent = context->device->swapchain->swapChainExtent; SceneGlobalUniform global{}; float tanFOVx = glm::tan(flycam->getFOV() / 2.0f); float screenSizeX = 2 * n * tanFOVx; float screenSizeY = 2 * n * tanFOVx * swapchainExtent.height / swapchainExtent.width; glm::vec3 pixelSize = glm::vec3(screenSizeX / swapchainExtent.width, screenSizeY / swapchainExtent.height, 0.0); glm::vec3 jitter{}; glm::vec2 rand = glm::sphericalRand(1.0); jitter += pixelSize * glm::vec3(rand.x, rand.y, 0); glm::mat4 transform = flycam->getTransform(); global.view = glm::translate(jitter)* glm::inverse(transform); global.proj = flycam->getProjMatrix(static_cast<float>(swapchainExtent.width), static_cast<float>(swapchainExtent.height), n, f); global.camPos = transform * glm::vec4(0.0, 0.0, 0.0, 1.0); global.screenRes = { swapchainExtent.width, swapchainExtent.height }; global.time = time; global.directionalLight = glm::vec4(1.0, 0.0, 0.0, 0.0); global.directionalLight = glm::rotate(glm::mat4(1.0f), -lightZenith, glm::vec3(0.0, 0.0, 1.0)) * global.directionalLight; global.directionalLight = glm::rotate(glm::mat4(1.0f), lightAzimuth, glm::vec3(0.0, 1.0, 0.0)) * global.directionalLight; scene->updateUniforms(i, 0, &global); ssao.nearPlane = n; ssao.farPlane = f; ssaoUniform->write(&ssao); ssaoHorizBlurUniform->write(&ssaoHorizBlurParams); ssaoVertiBlurUniform->write(&ssaoVertiBlurParams); } float ssaoRadius = 0.1f; bool aoEnabled = true; int timesDrawn = 0; VkCommandBuffer draw(uint32_t i) { { ZoneScopedN("Uniforms Updating"); updateUniforms(i); } { ZoneScopedN("ImGUI Processing"); gui->NextFrame(); ImGui::Begin("AO Demo"); ImGui::SliderFloat("Light Zenith", &lightZenith, 0.0f, 3.14f); ImGui::SliderFloat("Light Azimuth", &lightAzimuth, 0.0f, 6.28f); ImGui::SliderFloat("AO Intensity", &ssaoRadius, 0, 1); ImGui::Checkbox("Enable AO", &aoEnabled); if (aoEnabled) ssao.intensity = ssaoRadius; else ssao.intensity = 0.0; ImGui::SliderInt("Blur Size", &ssaoHorizBlurParams.pixelStep, 0.f, 8.f); ssaoVertiBlurParams.pixelStep = ssaoHorizBlurParams.pixelStep; ImGui::End(); gui->InternalRender(); } if (timesDrawn >= cmdBufs.size()) { ZoneScopedN("Resetting Command Buffer"); vkResetCommandBuffer(cmdBufs[i], 0); } else timesDrawn++; { ZoneScopedN("Begin Command Buffer"); cmdBufs[i] = context->device->beginCommandBuffer(); } { ZoneScopedN("Graph Recording"); graph->render(cmdBufs[i], i); } { ZoneScopedN("End Command Buffer"); vkEndCommandBuffer(cmdBufs[i]); } return cmdBufs[i]; } void buildSwapchainDependants() { graph->createInstances(); } void destroySwapchainDependents() { graph->destroyInstances(); } void preCleanup() { destroySwapchainDependents(); delete ssaoUniform; delete ssaoHorizBlurUniform; delete ssaoVertiBlurUniform; delete flycam; delete brdf; delete irradiancemap; delete specmap; graph->destroyLayouts(); delete scene; } }; int main() { Engine* demo = new Engine(); demo->run(); return 0; }
28.512931
172
0.696674
[ "render", "object", "vector", "transform" ]
1a7f8caaa55903f2b6c2463a8910d7fafe7b2bc8
1,709
cpp
C++
keybmouse_controller.cpp
dridk/tankfighter
2a4f9e72b524bb991ad1d5c665890845d4e288ba
[ "Zlib", "MIT" ]
1
2019-04-17T14:54:19.000Z
2019-04-17T14:54:19.000Z
keybmouse_controller.cpp
dridk/tankfighter
2a4f9e72b524bb991ad1d5c665890845d4e288ba
[ "Zlib", "MIT" ]
null
null
null
keybmouse_controller.cpp
dridk/tankfighter
2a4f9e72b524bb991ad1d5c665890845d4e288ba
[ "Zlib", "MIT" ]
1
2019-04-17T14:54:20.000Z
2019-04-17T14:54:20.000Z
#include "controller.h" #include "player.h" #include "geometry.h" #include "engine.h" #include <SFML/Graphics/RenderWindow.hpp> #include <SFML/Window/Mouse.hpp> #include <SFML/Window/Keyboard.hpp> #include <math.h> #include "input.h" #include "misc.h" using namespace sf; static void detectKeyboardMovement(Player *player, PlayerControllingData &pcd) { int vertical = 0; int horiz = 0; if (isLocalKeyPressed(Keyboard::Up) && !isLocalKeyPressed(Keyboard::Down)) { vertical = -1; } else if (isLocalKeyPressed(Keyboard::Down) && !isLocalKeyPressed(Keyboard::Up)) { vertical = 1; } if (isLocalKeyPressed(Keyboard::Left) && !isLocalKeyPressed(Keyboard::Right)) { horiz = -1; } else if (isLocalKeyPressed(Keyboard::Right) && !isLocalKeyPressed(Keyboard::Left)) { horiz = 1; } Vector2d v; v.y = vertical; v.x = horiz; if (horiz != 0 || vertical !=0) { normalizeVector(v, 1); pcd.move(v); } if (isLocalKeyPressed(Keyboard::Escape)) { player->getEngine()->quit(); } } static void detectMouseMovement(Player *player, PlayerControllingData &pcd) { double dx, dy; double angle = -1; Vector2d pos = player->getEngine()->getMousePosition(); dy = pos.y - player->position.y; dx = pos.x - player->position.x; if (dx != 0 && dy != 0) angle = angle_from_dxdy(dx, dy); if (angle >= 0 && angle <= 2*M_PI) { pcd.setCanonAngle(angle); } } void KeyboardMouseController::KeyboardMouseController::reportPlayerMovement(Player *player, PlayerControllingData &pcd) { detectKeyboardMovement(player, pcd); detectMouseMovement(player, pcd); if (Mouse::isButtonPressed(Mouse::Left) || isLocalKeyPressed(Keyboard::RControl) || isLocalKeyPressed(Keyboard::LControl)) { pcd.keepShooting(); } }
30.517857
125
0.705676
[ "geometry" ]
1a88425ee48af480dde8e2295d23b2280980eb29
7,976
cc
C++
src/coord/cluster/cluster_router.cc
lujingwei002/coord
cb5e5723293d8529663ca89e0c1d6b8c348fffff
[ "MIT" ]
null
null
null
src/coord/cluster/cluster_router.cc
lujingwei002/coord
cb5e5723293d8529663ca89e0c1d6b8c348fffff
[ "MIT" ]
null
null
null
src/coord/cluster/cluster_router.cc
lujingwei002/coord
cb5e5723293d8529663ca89e0c1d6b8c348fffff
[ "MIT" ]
null
null
null
#include "coord/cluster/cluster_router.h" #include "coord/cluster/cluster.h" #include "coord/cluster/cluster_notify.h" #include "coord/cluster/cluster_request.h" #include "coord/cluster/cluster_response.h" #include "coord/component/script_component.h" #include "util/date/date.h" #include "coord/coord.h" namespace coord { namespace cluster { CC_IMPLEMENT(ClusterRouter, "coord::cluster::ClusterRouter") ClusterRouter* newClusterRouter(Coord* coord) { ClusterRouter* router = new ClusterRouter(coord); return router; } cluster_router_handler::~cluster_router_handler() { if(this->ref >= 0) { luaL_unref(this->coord->Script->L, LUA_REGISTRYINDEX, this->ref); this->ref = 0; } } void cluster_router_handler::recvClusterRequest(Request* request) { if(this->recvClusterRequestFunc != nullptr){ this->recvClusterRequestFunc(request); } } void cluster_router_handler::recvClusterNotify(Notify* notify) { if(this->recvClusterNotifyFunc != nullptr){ this->recvClusterNotifyFunc(notify); } } ClusterRouter::ClusterRouter(Coord* coord){ this->coord = coord; } ClusterRouter::~ClusterRouter(){ } cluster_router_handler* ClusterRouter::searchHandler(const char* event, const char* route) { cluster_router_tree* tree = this->getTree(event); auto it = tree->handlerDict.find(route); if (it == tree->handlerDict.end()){ return NULL; } return it->second; } void ClusterRouter::recvClusterNotify(cluster::Notify* notify) { this->coord->coreLogDebug("[ClusterRouter] recvClusterNotify"); cluster_router_handler* handler = this->searchHandler("NOTIFY", notify->route.c_str()); if(handler == NULL){ this->coord->coreLogDebug("[ClusterRouter] recvClusterNotify failed, error='router not found', path=%s", notify->route.c_str()); return; } uint64_t t1 = this->coord->NanoTime(); handler->recvClusterNotify(notify); handler->times++; handler->consumeTime += (this->coord->NanoTime() - t1); } void ClusterRouter::recvClusterRequest(cluster::Request* request) { this->coord->coreLogDebug("[ClusterRouter] recvClusterRequest"); cluster_router_handler* handler = this->searchHandler("REQUEST", request->route.c_str()); if(handler == NULL){ this->coord->coreLogDebug("[ClusterRouter] recvClusterRequest failed, error='router not found', path=%s", request->route.c_str()); Response* response = request->GetResponse(); response->String("Not Found"); response->Reject(404); } else { uint64_t t1 = this->coord->NanoTime(); handler->recvClusterRequest(request); handler->times++; handler->consumeTime += (this->coord->NanoTime() - t1); } } void ClusterRouter::Trace() { for(auto const& it : this->trees){ auto event = it.first; auto tree = it.second; for(auto const& it1 : tree->handlerDict) { auto handler = it1.second; uint64_t averageTime = handler->times <= 0 ? 0 : (handler->consumeTime/handler->times); this->coord->coreLogDebug("[ClusterRouter] %10s | %10d | %10s | %s", event.c_str(), handler->times, date::FormatNano(averageTime), it1.first.c_str()); } } } bool ClusterRouter::Request(const char* route, ClusterRouter_RecvClusterRequest func){ if(func == NULL) { return this->addRoute("REQUEST", route, NULL); } else { cluster_router_handler* handler = new cluster_router_handler(this->coord, func); return this->addRoute("REQUEST", route, handler); } } bool ClusterRouter::Request(const char* route, ScriptComponent* object, int ref) { if(object == NULL) { return this->addRoute("REQUEST", route, NULL); } else { cluster_router_handler* handler = new cluster_router_handler(this->coord, std::bind(&ScriptComponent::recvClusterRequest, object, std::placeholders::_1, "recvClusterRequest", ref), ref); return this->addRoute("REQUEST", route, handler); } } int ClusterRouter::Request(lua_State* L) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype(L,1,"coord::cluster::ClusterRouter",0,&tolua_err) || !tolua_isstring(L,2,0,&tolua_err) || !tolua_isusertype(L,3,"coord::ScriptComponent",0,&tolua_err) || !tolua_isfunction(L,4,0,&tolua_err) || !tolua_isnoobj(L,5,&tolua_err) ) goto tolua_lerror; else #endif { const char* route = (const char*) tolua_tostring(L, 2, 0); coord::ScriptComponent* object = ((coord::ScriptComponent*) tolua_tousertype(L,3,0)); lua_pushvalue(L, 4); int ref = luaL_ref(L, LUA_REGISTRYINDEX); if (ref < 0) { tolua_error(L, "error in function 'Request'.\nattempt to set a nil function", NULL); return 0; } bool result = this->Request(route, object, ref); if(!result) { luaL_unref(L, LUA_REGISTRYINDEX, ref); } tolua_pushboolean(L, result); } return 1; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(L,"#ferror in function 'Request'.",&tolua_err); return 0; #endif } bool ClusterRouter::Notify(const char* path, ClusterRouter_RecvClusterNotify func){ if(func == NULL) { return this->addRoute("NOTIFY", path, NULL); } else { cluster_router_handler* handler = new cluster_router_handler(this->coord, func); return this->addRoute("NOTIFY", path, handler); } } bool ClusterRouter::Notify(const char* path, ScriptComponent* object, int ref) { if(object == NULL) { return this->addRoute("NOTIFY", path, NULL); } else { cluster_router_handler* handler = new cluster_router_handler(this->coord, std::bind(&ScriptComponent::recvClusterNotify, object, std::placeholders::_1, "recvClusterNotify", ref), ref); return this->addRoute("NOTIFY", path, handler); } } int ClusterRouter::Notify(lua_State* L) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype(L,1,"coord::cluster::ClusterRouter",0,&tolua_err) || !tolua_isstring(L,2,0,&tolua_err) || !tolua_isusertype(L,3,"coord::ScriptComponent",0,&tolua_err) || !tolua_isfunction(L,4,0,&tolua_err) || !tolua_isnoobj(L,5,&tolua_err) ) goto tolua_lerror; else #endif { const char* route = (const char*) tolua_tostring(L, 2, 0); coord::ScriptComponent* object = ((coord::ScriptComponent*) tolua_tousertype(L,3,0)); lua_pushvalue(L, 4); int ref = luaL_ref(L, LUA_REGISTRYINDEX); if (ref < 0) { tolua_error(L, "error in function 'Notify'.\nattempt to set a nil function", NULL); return 0; } bool result = this->Notify(route, object, ref); if(!result) { luaL_unref(L, LUA_REGISTRYINDEX, ref); } tolua_pushboolean(L, result); } return 1; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(L,"#ferror in function 'Notify'.",&tolua_err); return 0; #endif } bool ClusterRouter::addRoute(const char* event, const char* route, cluster_router_handler* handler) { cluster_router_tree* tree = this->getTree(event); //this->coord->coreLogDebug("[ClusterRouter] addRoute, event=%-10s, route=%-64s, handler=0x%x", event, route, handler); auto it = tree->handlerDict.find(route); if (it != tree->handlerDict.end()) { delete it->second; tree->handlerDict.erase(it); tree->handlerDict[route] = handler; } else { tree->handlerDict[route] = handler; } return true; } cluster_router_tree* ClusterRouter::getTree(const char* event) { const auto it = this->trees.find(event); if (it == this->trees.end()){ cluster_router_tree* tree = new cluster_router_tree(); this->trees[event] = tree; return tree; } else { return it->second; } } } }
34.08547
194
0.650075
[ "object" ]
1a896eecfe713f77ce5326a3e5a66debe9a898ae
2,924
cpp
C++
src/test/core/reflection.cpp
toeb/sine
96bcde571218f89a2b0b3cc51c19ad2b7be89c13
[ "MIT" ]
null
null
null
src/test/core/reflection.cpp
toeb/sine
96bcde571218f89a2b0b3cc51c19ad2b7be89c13
[ "MIT" ]
null
null
null
src/test/core/reflection.cpp
toeb/sine
96bcde571218f89a2b0b3cc51c19ad2b7be89c13
[ "MIT" ]
null
null
null
#include <core.testing.h> #include "conversion.h" #include <core.h> #include <string> #include <sstream> using namespace nspace; using namespace std; class Tmp : public virtual PropertyChangingObject{ REFLECTABLE_OBJECT(Tmp); PROPERTY(int,IntValue){} PROPERTY(std::string,StringValue){} }; void testAdapter1(){ Tmp t; PropertyAdapter adapter1(&t,"IntValue"); PropertyAdapter adapter2(&t, "StringValue"); auto observer = new DelegateObjectObserver<std::function<void (Observable *)>>([](Observable* observable){ auto a = dynamic_cast<PropertyAdapter*>(observable); if(!a)return ; //fail std::cout << a->getPropertyInfo()->getName() << " changed to "; a->serialize(std::cout); cout << endl; }); adapter1.addObjectObserver(observer); adapter2.addObjectObserver(observer); t.setIntValue(3); t.setStringValue("Lol"); adapter1.set(42); } TEST(Create, Prop){ class TestClass{ public: TestClass():_IntegerProperty(0){} SIMPLE_PROPERTY(int, IntegerProperty){ if(newvalue > oldvalue +4)cancel = true; } }a; CHECK_EQUAL(0,a.getIntegerProperty()); a.setIntegerProperty(3); CHECK_EQUAL(3,a.getIntegerProperty()); a.setIntegerProperty(20); CHECK_EQUAL(3,a.getIntegerProperty()); } TEST(Test1, PropertyChanging){ class TestClass : public PropertyChangingObject{ public: TestClass():_IntegerProperty(0){} NOTIFYING_PROPERTY(int, IntegerProperty){ if(newvalue > oldvalue +4)cancel = true; } }a; CHECK_EQUAL(0,a.getIntegerProperty()); a.setIntegerProperty(3); CHECK_EQUAL(3,a.getIntegerProperty()); a.setIntegerProperty(20); CHECK_EQUAL(3,a.getIntegerProperty()); bool success = false; std::string name; DelegatePropertyChangedListener listener([&name, &success](Object * object,const std::string & prop){ name = prop; if(prop=="IntegerProperty")success = true; }); a.listeners()|=&listener; a.setIntegerProperty(3); CHECK(!success); a.setIntegerProperty(4); CHECK(name=="IntegerProperty"); CHECK(success); } class TestClass2 : public virtual PropertyChangingObject{ REFLECTABLE_OBJECT(TestClass2); public: TestClass2():_IntegerProperty(0){} REFLECTABLE_PROPERTY(int, IntegerProperty){ if(newvalue > oldvalue +4)cancel = true; } }; TEST(Test1, Reflection){ TestClass2 a; CHECK_EQUAL(0,a.getIntegerProperty()); a.setIntegerProperty(3); CHECK_EQUAL(3,a.getIntegerProperty()); a.setIntegerProperty(20); CHECK_EQUAL(3,a.getIntegerProperty()); auto prop =a.getProperty("IntegerProperty"); CHECK(prop!=0); CHECK(prop->getName()=="IntegerProperty"); CHECK_EQUAL(3,a.getPropertyValue<int>("IntegerProperty")); a.setPropertyValue("IntegerProperty",5); CHECK_EQUAL(5,a.getIntegerProperty()); CHECK(a.getProperty("notexisting")==0); }
25.426087
109
0.680917
[ "object" ]
1a8ad6889f7042d47a555ec7c21552dfaeec83df
860
cpp
C++
src/question235.cpp
lxb1226/leetcode_cpp
554280de6be2a77e2fe41a5e77cdd0f884ac2e20
[ "MIT" ]
null
null
null
src/question235.cpp
lxb1226/leetcode_cpp
554280de6be2a77e2fe41a5e77cdd0f884ac2e20
[ "MIT" ]
null
null
null
src/question235.cpp
lxb1226/leetcode_cpp
554280de6be2a77e2fe41a5e77cdd0f884ac2e20
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { TreeNode* ancestor = root; while (true) { if(p->val < ancestor->val && q->val < ancestor->val){ ancestor = ancestor->left; }else if(p->val > ancestor->val && q->val > ancestor->val){ ancestor = ancestor->right; }else{ break; } } return ancestor; } }; int main(){ }
23.243243
90
0.544186
[ "vector" ]
1a9081dc551df70cc530f3c2210d2f17b6735a09
1,616
cpp
C++
command-line/pdf-reorder.cpp
FearlessSniper/Pdf-reorder
e7bae6ad2ab2f2e8c64de82efea3d1d64f53aa0e
[ "MIT" ]
null
null
null
command-line/pdf-reorder.cpp
FearlessSniper/Pdf-reorder
e7bae6ad2ab2f2e8c64de82efea3d1d64f53aa0e
[ "MIT" ]
null
null
null
command-line/pdf-reorder.cpp
FearlessSniper/Pdf-reorder
e7bae6ad2ab2f2e8c64de82efea3d1d64f53aa0e
[ "MIT" ]
null
null
null
/** * @file pdf-reorder.cpp * @author FearlessSniper (47030588+FearlessSniper@users.noreply.github.com) * @brief Reorders a PDF document to the correct order with the original order * be odd pages, then even pages * @version 0.1 * @date 2020-02-24 */ #include <iostream> #include <string> #include <cmath> #include "pdf-reorder.h" using namespace std; using namespace PoDoFo; int main(){ cout << "Please enter the PDF path: " << flush; string pdf_path; getline(cin, pdf_path); PdfMemDocument pdf_file(pdf_path.c_str()), new_pdf_file; new_pdf_file.Append(pdf_file); PdfObject *pages = new_pdf_file.GetCatalog()->GetIndirectKey(PdfName("Pages")); reorder_page_odds_evens(pages); pdf_path.erase(pdf_path.find(".pdf"), string(".pdf").length()); pdf_path += "_reordered.pdf"; new_pdf_file.Write(pdf_path.c_str()); return 0; } /** * \brief Reorder the pages of the PDF Document with the original order be odd pages, * then even. * \param pages A pointer to the Pages object of the PdfMemDocument. */ void reorder_page_odds_evens(PdfObject *&pages){ PdfArray page_kids = pages->GetIndirectKey(PdfName("Kids"))->GetArray(), new_page_kids; int n_pages = page_kids.size(); new_page_kids.reserve(n_pages); PdfArray::iterator it = page_kids.begin(); for (int i = 0, j = floor(n_pages / 2), k = 0; k < n_pages; i++, j++, k+=2){ new_page_kids.push_back(*(it + i)); if (it + j < page_kids.end()){ new_page_kids.push_back(*(it + j)); } } pages->GetDictionary().AddKey(PdfName("Kids"), new_page_kids); }
32.979592
91
0.670173
[ "object" ]
1a9c15b1fbd39ac84ccd696389659f8eff9d4b9b
5,700
cpp
C++
3. Red/Week 5/11. ConcurrentMap/main.cpp
AmaterasuOmikami/The-art-of-modern-Cpp-development
4f0958197da92d216ee526384a6f7386a0fe62a0
[ "MIT" ]
1
2022-02-17T10:58:58.000Z
2022-02-17T10:58:58.000Z
3. Red/Week 5/11. ConcurrentMap/main.cpp
AmaterasuOmikami/The-art-of-modern-Cpp-development
4f0958197da92d216ee526384a6f7386a0fe62a0
[ "MIT" ]
null
null
null
3. Red/Week 5/11. ConcurrentMap/main.cpp
AmaterasuOmikami/The-art-of-modern-Cpp-development
4f0958197da92d216ee526384a6f7386a0fe62a0
[ "MIT" ]
null
null
null
/* * В заготовке решения задачи «Шаблон Synchronized» мы уже слегка коснулись идеи * о том, что уменьшение размера критической секции позволяет повысить скорость * работы многопоточной программы. В этой задаче мы разовьём её больше. * * Давайте представим, что у нас есть map, к которому обращаются несколько * потоков. Чтобы синхронизировать доступ к нему, мы можем каждое обращение к * этому map'у защитить мьютексом (например, завернув наш map в шаблон * Synchronized). Теперь давайте представим, что у нас есть * Synchronized<map<int, int>>, в котором хранятся все ключи от 1 до 10000. * Интуитивно кажется, что когда из одного потока мы обращаемся к ключу 10, а из * другого — например, к ключу 6712, то нет смысла защищать эти обращения одним * и тем же мьютексом. Это отдельные области памяти, а внутреннюю структуру * словаря мы никак не изменяем. При этом, если мы будем обращаться к ключу 6712 * одновременно из нескольких потоков, то синхронизация, несомненно, понадобится. * * Отсюда возникает идея — разбить наш словарь на нескольких подсловарей с * непересекающимся набором ключей и защитить каждый из них отдельным мьютексом. * Тогда при обращении разных потоков к разным ключам они нечасто будут попадать * в один и тот же подсловарь, а значит, смогут параллельно его обрабатывать. * Эту идею вам предстоит реализовать в этой задаче. Вам надо написать шаблон * класса ConcurrentMap вот с таким интерфейсом: * - static_assert в начале класса говорит, что в данной задаче предполагается, * что ключами ConcurrentMap'а могут быть только целые числа. * - Конструктор класса ConcurrentMap<K, V> принимает количество подсловарей, на * которые надо разбить всё пространство ключей. * - operator[] должен вести себя так же, как аналогичный оператор у map — если * ключ key присутствует в словаре, он должен возвращать объект класса Access, * содержащий ссылку на соответствующее ему значение; если же key отсутствует * в словаре, в него надо добавить пару (key, V()) и вернуть объект класса * Access, содержащий ссылку на только что добавленное значение. * - Структура Access, должна вести себя так же, как и в шаблоне Synchronized, — * предоставлять ссылку на значение словаря и обеспечивать синхронизацию * доступа к нему. * - Метод BuildOrdinaryMap должен сливать вместе части словаря и возвращать * весь словарь целиком. При этом он должен быть потокобезопасным, то есть * корректно работать, когда другие потоки выполняют операции с ConcurrentMap. */ #include "test_runner.h" #include "profile.h" #include <algorithm> #include <future> #include <map> #include <vector> #include <deque> #include <string> #include <random> using namespace std; template<typename K, typename V> class ConcurrentMap { public: static_assert(is_integral_v<K>, "ConcurrentMap supports only integer keys"); struct Access { lock_guard<mutex> guard; V& ref_to_value; }; explicit ConcurrentMap(size_t bucket_count) : total_buckets_(bucket_count) { buckets_.resize(total_buckets_); } Access operator[](const K& key) { size_t index = key % total_buckets_; auto& bucket = buckets_[index]; return {lock_guard(bucket.sub_mutex), bucket.sub_map[key]}; } map<K, V> BuildOrdinaryMap() { map<K, V> ordinary_map; for (auto& bucket : buckets_) { for (const auto&[key, value] : bucket.sub_map) { ordinary_map[key] = operator[](key).ref_to_value; } } return ordinary_map; } private: const size_t total_buckets_; struct Bucket { map<K, V> sub_map; mutex sub_mutex; }; deque<Bucket> buckets_; }; void RunConcurrentUpdates( ConcurrentMap<int, int>& cm, size_t thread_count, int key_count) { auto kernel = [&cm, key_count](int seed) { vector<int> updates(key_count); iota(begin(updates), end(updates), -key_count / 2); shuffle(begin(updates), end(updates), default_random_engine(seed)); for (int i = 0; i < 2; ++i) { for (auto key : updates) { cm[key].ref_to_value++; } } }; vector<future<void>> futures; for (size_t i = 0; i < thread_count; ++i) { futures.push_back(async(kernel, i)); } } void TestConcurrentUpdate() { const size_t thread_count = 3; const size_t key_count = 50000; ConcurrentMap<int, int> cm(thread_count); RunConcurrentUpdates(cm, thread_count, key_count); const auto result = cm.BuildOrdinaryMap(); ASSERT_EQUAL(result.size(), key_count) for (auto&[k, v] : result) { AssertEqual(v, 6, "Key = " + to_string(k)); } } void TestReadAndWrite() { ConcurrentMap<size_t, string> cm(5); auto updater = [&cm] { for (size_t i = 0; i < 50000; ++i) { cm[i].ref_to_value += 'a'; } }; auto reader = [&cm] { vector<string> result(50000); for (size_t i = 0; i < result.size(); ++i) { result[i] = cm[i].ref_to_value; } return result; }; auto u_1 = async(updater); auto r_1 = async(reader); auto u_2 = async(updater); auto r_2 = async(reader); u_1.get(); u_2.get(); for (auto f : {&r_1, &r_2}) { auto result = f->get(); ASSERT(all_of(result.begin(), result.end(), [](const string& s) { return s.empty() || s == "a" || s == "aa"; })) } } void TestSpeedup() { { ConcurrentMap<int, int> single_lock(1); LOG_DURATION("Single lock") RunConcurrentUpdates(single_lock, 4, 50000); } { ConcurrentMap<int, int> many_locks(100); LOG_DURATION("100 locks") RunConcurrentUpdates(many_locks, 4, 50000); } } int main() { TestRunner tr; RUN_TEST(tr, TestConcurrentUpdate); RUN_TEST(tr, TestReadAndWrite); RUN_TEST(tr, TestSpeedup); }
31.666667
81
0.692982
[ "vector" ]
1aa93e33f943253643aef38b5625a3185fff5de0
11,080
cpp
C++
Sources/Internal/Platform/TemplateAndroid/CorePlatformAndroid.cpp
reven86/dava.engine
ca47540c8694668f79774669b67d874a30188c20
[ "BSD-3-Clause" ]
5
2020-02-11T12:04:17.000Z
2022-01-30T10:18:29.000Z
Sources/Internal/Platform/TemplateAndroid/CorePlatformAndroid.cpp
reven86/dava.engine
ca47540c8694668f79774669b67d874a30188c20
[ "BSD-3-Clause" ]
null
null
null
Sources/Internal/Platform/TemplateAndroid/CorePlatformAndroid.cpp
reven86/dava.engine
ca47540c8694668f79774669b67d874a30188c20
[ "BSD-3-Clause" ]
4
2019-11-28T19:24:34.000Z
2021-08-24T19:12:50.000Z
#include "Base/Platform.h" #if !defined(__DAVAENGINE_COREV2__) #if defined(__DAVAENGINE_ANDROID__) extern void FrameworkDidLaunched(); extern void FrameworkWillTerminate(); #include "Platform/DeviceInfo.h" #include "Input/InputSystem.h" #include "UI/UIEvent.h" #include "FileSystem/FileSystem.h" #include "Platform/TemplateAndroid/AssetsManagerAndroid.h" #include "Render/2D/Systems/RenderSystem2D.h" #include "Engine/Android/JNIBridge.h" #include "Platform/TemplateAndroid/CorePlatformAndroid.h" #include "Debug/DVAssertDefaultHandlers.h" namespace DAVA { AndroidSystemDelegate::AndroidSystemDelegate(JavaVM* vm) { Logger::Debug("AndroidSystemDelegate::AndroidSystemDelegate()"); this->vm = vm; environment = NULL; if (vm->GetEnv(reinterpret_cast<void**>(&environment), JNI_VERSION_1_4) != JNI_OK) { Logger::Debug("Failed to get the environment using GetEnv()"); } } Core::eDeviceFamily Core::GetDeviceFamily() { float32 width = UIControlSystem::Instance()->vcs->GetPhysicalScreenSize().dx; float32 height = UIControlSystem::Instance()->vcs->GetPhysicalScreenSize().dy; float32 dpi = GetScreenDPI(); float32 inches = sqrt((width * width) + (height * height)) / dpi; if (inches > 6.f) return DEVICE_PAD; return DEVICE_HANDSET; } CorePlatformAndroid::CorePlatformAndroid(const String& cmdLine) { Assert::SetupDefaultHandlers(); SetCommandLine(cmdLine); } int Core::Run(int argc, char* argv[], AppHandle handle) { // CoreWin32Platform * core = new CoreWin32Platform(); // core->CreateWin32Window(handle); // core->Run(); // core->ReleaseSingletons(); return 0; } void CorePlatformAndroid::Quit() { Logger::Debug("[CorePlatformAndroid::Quit]"); renderIsActive = false; // finish java activity JNI::JavaClass javaClass("com/dava/framework/JNIActivity"); Function<void()> finishActivity = javaClass.GetStaticMethod<void>("finishActivity"); finishActivity(); } void CorePlatformAndroid::QuitAction() { Logger::Debug("[CorePlatformAndroid::QuitAction] in"); if (Core::Instance()) { // will call gameCore->onAppFinished() destroy game singletons Core::Instance()->SystemAppFinished(); } FrameworkWillTerminate(); Logger::Debug("[CorePlatformAndroid::QuitAction] out"); } void CorePlatformAndroid::ProcessFrame() { if (renderIsActive) { if (viewSizeChanged) { ApplyPendingViewSize(); } Core::SystemProcessFrame(); } } void CorePlatformAndroid::SetScreenScaleMultiplier(float32 multiplier) { float32 curMultiplier = Core::GetScreenScaleMultiplier(); if (!FLOAT_EQUAL(multiplier, curMultiplier)) { Core::SetScreenScaleMultiplier(multiplier); RenderReset(pendingWidth, pendingHeight); } } void CorePlatformAndroid::ApplyPendingViewSize() { Logger::Debug("[CorePlatformAndroid::ApplyPendingViewSize] in"); Logger::Debug("[CorePlatformAndroid::] w = %d, h = %d, surfW = %d, surfH = %d", pendingWidth, pendingHeight, backbufferWidth, backbufferHeight); viewSizeChanged = false; DeviceInfo::InitializeScreenInfo(); UIControlSystem::Instance()->vcs->SetInputScreenAreaSize(pendingWidth, pendingHeight); UIControlSystem::Instance()->vcs->SetPhysicalScreenSize(backbufferWidth, backbufferHeight); UIControlSystem::Instance()->vcs->ScreenSizeChanged(); Logger::Debug("[CorePlatformAndroid::ApplyPendingViewSize] out"); Logger::FrameworkDebug("[CorePlatformAndroid::UpdateScreenMode] done"); } void CorePlatformAndroid::CreateAndroidWindow(const char8* docPathEx, const char8* docPathIn, const char8* assets, const char8* logTag, AndroidSystemDelegate* sysDelegate) { androidDelegate = sysDelegate; externalStorage = docPathEx; internalStorage = docPathIn; Core::CreateSingletons(); new AssetsManagerAndroid(assets); Logger::SetTag(logTag); } void CorePlatformAndroid::RenderReset(int32 w, int32 h) { Logger::Debug("[CorePlatformAndroid::RenderReset] start"); renderIsActive = true; pendingWidth = w; pendingHeight = h; // Android is always using hardware scaler for rendering. // By specifying a scaled size for the buffer, the hardware // scaler will be enabled and we will benefit in our rendering // to the specified window (buffer is going to be up-scaled // or down-scaled to the window size). // For more info see: http://android-developers.blogspot.com.by/2013/09/using-hardware-scaler-for-performance.html float32 scale = Core::GetScreenScaleMultiplier(); backbufferWidth = static_cast<int32>(scale * w); backbufferHeight = static_cast<int32>(scale * h); viewSizeChanged = true; if (wasCreated) { rhi::ResetParam params; params.width = static_cast<uint32>(backbufferWidth); params.height = static_cast<uint32>(backbufferHeight); params.window = rendererParams.window; Renderer::Reset(params); } else { wasCreated = true; ApplyPendingViewSize(); rendererParams.width = static_cast<uint32>(backbufferWidth); rendererParams.height = static_cast<uint32>(backbufferHeight); // Set proper width and height before call FrameworkDidlaunched FrameworkDidLaunched(); Core::Instance()->SystemAppStarted(); // We are always in foreground when initialize application // This condition avoids render resuming on startup // Render resuming on startup has no sence, but can breaks render foreground = true; StartForeground(); } Logger::Debug("[CorePlatformAndroid::RenderReset] end"); } void CorePlatformAndroid::OnCreateActivity() { DAVA::Thread::InitMainThread(); } void CorePlatformAndroid::OnDestroyActivity() { Logger::Info("[CorePlatformAndroid::OnDestroyActivity]"); renderIsActive = false; wasCreated = false; QuitAction(); } void CorePlatformAndroid::StartVisible() { // Logger::Debug("[CorePlatformAndroid::StartVisible]"); } void CorePlatformAndroid::StopVisible() { // Logger::Debug("[CorePlatformAndroid::StopVisible]"); } void CorePlatformAndroid::StartForeground() { Logger::Debug("[CorePlatformAndroid::StartForeground] in"); if (wasCreated) { DAVA::ApplicationCore* core = DAVA::Core::Instance()->GetApplicationCore(); if (!core) { DAVA::Core::Instance()->SetIsActive(true); } DAVA::Core::Instance()->GoForeground(); DAVA::Core::Instance()->FocusReceived(); if (!foreground) rhi::ResumeRendering(); if (core) { core->OnResume(); } foreground = true; } Logger::Debug("[CorePlatformAndroid::StartForeground] out"); } void CorePlatformAndroid::StopForeground(bool isLock) { Logger::Debug("[CorePlatformAndroid::StopForeground] in"); DAVA::ApplicationCore* core = DAVA::Core::Instance()->GetApplicationCore(); if (core) { core->OnSuspend(); } else { DAVA::Core::Instance()->SetIsActive(false); } DAVA::Core::Instance()->GoBackground(isLock); DAVA::Core::Instance()->FocusLost(); if (foreground) rhi::SuspendRendering(); foreground = false; Logger::Debug("[CorePlatformAndroid::StopForeground] out"); } void CorePlatformAndroid::KeyUp(int32 keyCode, uint32 modifiers) { InputSystem* inputSystem = InputSystem::Instance(); KeyboardDevice& keyboard = inputSystem->GetKeyboard(); UIEvent keyEvent; keyEvent.device = eInputDevices::KEYBOARD; keyEvent.phase = DAVA::UIEvent::Phase::KEY_UP; keyEvent.key = keyboard.GetDavaKeyForSystemKey(keyCode); keyEvent.timestamp = SystemTimer::GetMs() / 1000.0; keyEvent.modifiers = modifiers; inputSystem->ProcessInputEvent(&keyEvent); keyboard.OnKeyUnpressed(keyEvent.key); } void CorePlatformAndroid::KeyDown(int32 keyCode, uint32 modifiers) { InputSystem* inputSystem = InputSystem::Instance(); KeyboardDevice& keyboard = inputSystem->GetKeyboard(); UIEvent keyEvent; keyEvent.device = eInputDevices::KEYBOARD; keyEvent.phase = DAVA::UIEvent::Phase::KEY_DOWN; keyEvent.key = keyboard.GetDavaKeyForSystemKey(keyCode); keyEvent.timestamp = SystemTimer::GetMs() / 1000.0; keyEvent.modifiers = modifiers; inputSystem->ProcessInputEvent(&keyEvent); keyboard.OnKeyPressed(keyEvent.key); } void CorePlatformAndroid::OnGamepadElement(int32 elementKey, float32 value, bool isKeycode, uint32 modifiers) { GamepadDevice& gamepadDevice = InputSystem::Instance()->GetGamepadDevice(); uint32 davaKey = GamepadDevice::INVALID_DAVAKEY; if (isKeycode) { davaKey = gamepadDevice.GetDavaEventIdForSystemKeycode(elementKey); } else { davaKey = gamepadDevice.GetDavaEventIdForSystemAxis(elementKey); } if (davaKey == GamepadDevice::INVALID_DAVAKEY) { Logger::Debug("unknown gamepad element code: 0x%H", elementKey); return; } UIEvent newEvent; newEvent.element = static_cast<GamepadDevice::eDavaGamepadElement>(davaKey); newEvent.physPoint.x = value; newEvent.point.x = value; newEvent.phase = DAVA::UIEvent::Phase::JOYSTICK; newEvent.device = eInputDevices::GAMEPAD; newEvent.timestamp = SystemTimer::GetMs() / 1000.0; newEvent.modifiers = modifiers; gamepadDevice.SystemProcessElement(static_cast<GamepadDevice::eDavaGamepadElement>(davaKey), value); InputSystem::Instance()->ProcessInputEvent(&newEvent); } void CorePlatformAndroid::OnGamepadAvailable(bool isAvailable) { InputSystem::Instance()->GetGamepadDevice().SetAvailable(isAvailable); } void CorePlatformAndroid::OnGamepadTriggersAvailable(bool isAvailable) { InputSystem::Instance()->GetGamepadDevice().OnTriggersAvailable(isAvailable); } void CorePlatformAndroid::OnInput(Vector<UIEvent>& allInputs) { DVASSERT(!allInputs.empty()); if (!allInputs.empty()) { for (auto& e : allInputs) { UIControlSystem::Instance()->OnInput(&e); } } } bool CorePlatformAndroid::IsMultitouchEnabled() { return InputSystem::Instance()->GetMultitouchEnabled(); } bool CorePlatformAndroid::DownloadHttpFile(const String& url, const String& documentsPathname) { if (androidDelegate) { FilePath path(documentsPathname); return androidDelegate->DownloadHttpFile(url, path.GetAbsolutePathname()); } return false; } AndroidSystemDelegate* CorePlatformAndroid::GetAndroidSystemDelegate() const { return androidDelegate; } void CorePlatformAndroid::SetNativeWindow(void* nativeWindow) { rendererParams.window = nativeWindow; } int32 CorePlatformAndroid::GetViewWidth() const { return pendingWidth; } int32 CorePlatformAndroid::GetViewHeight() const { return pendingHeight; } } #endif // #if defined(__DAVAENGINE_ANDROID__) #endif // !__DAVAENGINE_COREV2__
27.839196
171
0.699278
[ "render", "vector" ]
1ab6ba807bd5ff7d3b9defda7fa434bc71875978
6,506
cpp
C++
problems_001-050/euler_37.cpp
sedihub/project_euler
2d7d40ee67a1e0402aa68e78a5f7d7cf18221db5
[ "Apache-2.0" ]
null
null
null
problems_001-050/euler_37.cpp
sedihub/project_euler
2d7d40ee67a1e0402aa68e78a5f7d7cf18221db5
[ "Apache-2.0" ]
null
null
null
problems_001-050/euler_37.cpp
sedihub/project_euler
2d7d40ee67a1e0402aa68e78a5f7d7cf18221db5
[ "Apache-2.0" ]
null
null
null
/* PROBLEM: The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. SOLUTION: We need to shrink the search space as much as possible. Being left-right and right-left prime truncatable are very stringent criteria that will allow us to significantly reduce the size of the search space. Since the number is prime-truncatable from both left to right and right to left, it must be only consisted of 1, 3, 7 and 9 digits. Further, it cannot have more than two 1 and 7 in its digits or else it will be divisible by 3. To see this, say it has 4 sevens. As we truncate we are bound to get to a truncation with only three sevens and the reset of the digits being 3s and 9s. The sum of the digits will be divisible by 3. Specifically, allowed sequences can only have the following start and ends: 3 1 ... 7 3 3 7 ... 7 3 3 1 ... 1 3 3 7 ... 1 3 7 ... 7 3 7 ... 1 3 3 1 ... 7 3 7 ... 7 7 3 3 7 3 1 7 3 1 3 Note that 1 and 7 cannot be any closer or else a subsequence will be divisible by 3. We can use recursion to find out all valid combinations of 9 and 3 in the place of ellipsis above. Note that we are not using the expected number of solutions! Finally, note that there are two exception that need to be included: 23 and 53! ANSWER: 748317 23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397 **/ #include <iostream> #include <vector> #include <set> #include <iterator> typedef unsigned long long int ullint; template <typename T> bool is_prime(T n) { if (n == 0) return false; else if (n == 1) return false; else if (n == 2) return true; else if (n == 3) return true; else if (n == 5) return true; else if (n % 2 == 0) return false; else if (n % 3 == 0) return false; else if (n % 5 == 0) return false; T k = 6; while (k * k <= n) { if (n % (k + 1) == 0) return false; if (n % (k + 5) == 0) return false; k += 6; } return true; } ullint char_to_int(char c) { return (ullint)(c - '0'); } bool is_bidirectional_truncatable_prime(const std::vector<char> &num_digits) { // Check right-truncated in the reverse order ullint right_truncated = 0; std::vector<char>::const_iterator it = num_digits.begin(); while (it != num_digits.end()) { right_truncated = 10 * right_truncated; right_truncated += char_to_int(*it); if (!is_prime<ullint>(right_truncated)) { // std::cout << "[RT] " << right_truncated << " is not prime!" << std::endl; return false; } it++; } // Check left-truncated in the reverse order ullint left_truncated = 0; ullint decimal = 1; std::vector<char>::const_reverse_iterator rit = num_digits.rbegin(); while (rit != num_digits.rend()) { left_truncated += decimal * char_to_int(*rit); decimal *= 10; if (!is_prime<ullint>(left_truncated)) { // std::cout << "[LT] " << left_truncated << " is not prime!" << std::endl; return false; } rit++; } return true; } ullint digits_vecor_to_ullint(const std::vector<char> &num_digits) { ullint n = 0; std::vector<char>::const_iterator it = num_digits.begin(); while (it != num_digits.end()) { n *= 10; n += char_to_int(*it); it++; } return n; } bool is_prime(const std::vector<char> &num_digits) { ullint n = digits_vecor_to_ullint(num_digits); return is_prime(n); } std::vector<ullint> dicsover_truncatable_primes( std::vector<char> &head, std::vector<char> &tail, bool verbose=false) /* Given a head and tail subsequences, explores their combination as well as their combination with 3 and 9 insertions. **/ { std::vector<ullint> candidates; std::vector<char> candidate; // Splice head and tail. Retain if it is a bidirectional truncatable prime: candidate = head; candidate.insert(candidate.end(), tail.begin(), tail.end()); if (verbose) { std::vector<char>::iterator it; for (it = head.begin(); it != head.end(); it++) { std::cout << *it; } std::cout << " + "; for (it = tail.begin(); it != tail.end(); it++) { std::cout << *it; } std::cout << " = "; for (it = candidate.begin(); it != candidate.end(); it++) { std::cout << *it; } std::cout << "\t" << is_bidirectional_truncatable_prime(candidate) << std::endl; } if (is_bidirectional_truncatable_prime(candidate)) { candidates.push_back(digits_vecor_to_ullint(candidate)); } // Recursively check the remaining possibilities: std::vector<ullint> new_candidates; // // Examine adding 3: candidate = head; candidate.push_back('3'); if (is_prime(candidate)) { new_candidates = dicsover_truncatable_primes(candidate, tail, verbose); candidates.insert(candidates.end(), new_candidates.begin(), new_candidates.end()); } // // Examine adding 9: candidate = head; candidate.push_back('9'); if (is_prime(candidate)) { new_candidates = dicsover_truncatable_primes(candidate, tail, verbose); candidates.insert(candidates.end(), new_candidates.begin(), new_candidates.end()); } return candidates; } int main() { std::set<ullint> truncatable_primes = {23, 53}; std::vector< std::vector<char> > heads = { {'3', '1'}, {'3', '7'}, {'7'}, {'3'}}; std::vector< std::vector<char> > tails = { {'7', '3'}, {'1', '3'}, {'7'}, {'3'}}; std::vector<ullint> discovered; std::vector< std::vector<char> >::iterator head_it; std::vector< std::vector<char> >::iterator tail_it; for (head_it = heads.begin(); head_it != heads.end(); head_it++) { for (tail_it = tails.begin(); tail_it != tails.end(); tail_it++) { discovered = dicsover_truncatable_primes(*head_it, *tail_it, false); truncatable_primes.insert(discovered.begin(), discovered.end()); } } ullint sum = 0; std::set<ullint>::iterator it; for (it = truncatable_primes.begin(); it != truncatable_primes.end(); it++) { std::cout << "\t" << *it << std::endl; sum += *it; } std::cout << "Sum of left-right and right-left truncatable primes is: " << sum << std::endl; return 0; }
28.915556
97
0.638795
[ "vector" ]
1ac1d100db1ac89d3131a925abd439b1a5497bde
34,797
cpp
C++
src/physics/havok/clothsetup.cpp
Caprica666/vixen
b71e9415bbfa5f080aee30a831e3b0c8f70fcc7d
[ "BSD-2-Clause" ]
1
2019-02-13T15:39:56.000Z
2019-02-13T15:39:56.000Z
src/physics/havok/clothsetup.cpp
Caprica666/vixen
b71e9415bbfa5f080aee30a831e3b0c8f70fcc7d
[ "BSD-2-Clause" ]
null
null
null
src/physics/havok/clothsetup.cpp
Caprica666/vixen
b71e9415bbfa5f080aee30a831e3b0c8f70fcc7d
[ "BSD-2-Clause" ]
2
2017-11-09T12:06:41.000Z
2019-02-13T15:40:02.000Z
#include "vixen.h" #include "physics/havok/vxphysics.h" #include "physics/havok/vxcloth.h" #include <Common/Base/KeyCode.h> #include <Common/Base/hkBase.h> #include <Common/Base/System/hkBaseSystem.h> #include <Common/Base/Math/QsTransform/hkQsTransform.h> #include <Common/SceneData/Skin/hkxSkinBinding.h> #include <Common/SceneData/Scene/hkxScene.h> #include <Common/SceneData/Scene/hkxSceneUtils.h> #include <Common/SceneData/Graph/hkxNode.h> #include <Animation/Animation/Rig/hkaSkeleton.h> #include <Cloth/Setup/SetupMesh/SceneData/hclSceneDataSetupMesh.h> #include <Cloth/Setup/SetupMesh/Named/hclNamedSetupMesh.h> #include <Cloth/Setup/SetupMesh/ExtendedUser/hclExtendedUserSetupMesh.h> #include <Cloth/Setup/TransformSet/Named/hclNamedTransformSetSetupObject.h> #include <Cloth/Setup/Execution/hclClothSetupExecution.h> #include <Cloth/Setup/Execution/hclUserSetupRuntimeDisplayData.h> #include <Cloth/Setup/Execution/hclUserSetupRuntimeSkeletonData.h> #include <Cloth/Setup/Cloth/hclClothSetupObject.h> #include <Cloth/Cloth/World/hclWorld.h> #include <Cloth/Cloth/Cloth/hclClothInstance.h> #include <Cloth/Cloth/Cloth/hclClothData.h> #include <Cloth/Cloth/Container/hclClothContainer.h> #include <Cloth/Cloth/SimCloth/hclSimClothInstance.h> #include <Cloth/Cloth/Buffer/hclBufferDefinition.h> #include <Cloth/Cloth/Buffer/hclBuffer.h> #include <Cloth/Cloth/Buffer/SceneData/hclSceneDataBuffer.h> #include <Cloth/Cloth/TransformSet/hclTransformSet.h> #include <Cloth/Cloth/Collide/Shape/Sphere/hclSphereShape.h> #include <Cloth/Cloth/Collide/Shape/Plane/hclPlaneShape.h> #include <Cloth/Cloth/Collide/hclCollidable.h> //#include <Cloth/Cloth/Operator/RecalculateNormals/hclRecalculateAllNormalsOperator.h> #include <Cloth/Cloth/Operator/Simulate/hclSimulateOperator.h> #include <Cloth/Cloth/Utilities/Instantiation/hclInstantiationUtil.h> #include "Physics/havok/math_interop.h" namespace Vixen { template <> inline bool Core::Dict<NameProp, void*, BaseDict>::CompareKeys(const NameProp& knew, const NameProp& kdict) { return String(knew).CompareNoCase(kdict) == 0; } template <> inline uint32 Core::Dict<NameProp, void*, BaseDict>::HashKey(const NameProp& np) const { return HashStr((const TCHAR*) np); } /* * Main cloth setup starting point to link Havok Cloth objects with the corresponding Vixen object. * Each Vixen Mesh object that is controlled by Havok Cloth maps to a Havok hclBuffer object. * Similarly, each Vixen Skeleton that drives a Havok Cloth skin maps to a Havok hclTransformSet object. * This class links all the Havok Cloth buffers and transform sets with the corresponding Vixen * objects using the Havok Cloth infrastructure. */ class ClothSetup : public hclUserSetupRuntimeDisplayData, public hclUserSetupRuntimeSkeletonData { public: ClothSetup(Scene* vixenscene, const hkxScene* havokscene); virtual void getDisplayBufferLayout(const char *objectName, hkUint32 section, hclBufferLayout &layoutOut) const; virtual void getStaticDisplayBufferLayout(const char *objectName, hkUint32 section, hclBufferLayout &layoutOut) const; static Mesh* FindMeshByName(const char* name, int section, Model* root); virtual const hclSetupMesh* getMeshDataForObject(const char *objectName) const; virtual hclTransformSetSetupObject* getTransformSetForObject(const char* skeletonName) const; Model* FindModel(const char* name) const; protected: const Mesh* FindMesh(const char* name, int section) const; void getBufferLayout(const Mesh* mesh, hclBufferLayout &dstlayout) const; const hkxScene* m_HavokScene; Scene* m_VixenScene; mutable PtrArray m_Transforms; mutable NameDict<void*> m_SetupMeshes; }; /* * Links a Vixen Mesh to a Havok hclBuffer at run time. * Implements the Havok calls necessary for Havok to directly * modify the vertices of the mesh and read it's triangles. */ class ClothBuffer : public hclBuffer { public: ClothBuffer(Mesh* mesh); virtual hkResult notifyBeginAccess(const hclBufferUsage& bufferUsage); virtual hkResult notifyEndAccess(); Ref<Mesh> m_Mesh; int m_SlotMap[4]; // Vixen vertex slot for positions, normals, tangents, bitangents }; /* * Provides context necessary for cloth setup, in this case the Vixen Scene * and the Havok hkxScene that contain the Vixen meshes and the Havok meshes * and cloth setup data. */ struct ClothBufferInput : public hclInstantiationInput { ClothBufferInput(const hkxScene* havok_scene, Scene* vixen_scene) : m_HavokScene(havok_scene), m_VixenScene(vixen_scene) { } const hkxScene* m_HavokScene; Scene* m_VixenScene; }; typedef hclInstantiationOutput ClothBufferOutput; /* * Provides input arguments for setting up cloth buffers. * This class assumes that static cloth buffers (read only) link only * to Havok meshes and that display buffers (writeable) link only * to Vixen meshes. */ class ClothBufferUtil : public hclInstantiationUtil { public: // Instantiate cloth buffers ClothBufferUtil(ClothBufferInput& input, ClothBufferOutput& output) : hclInstantiationUtil(input, output) { } private: virtual hclBuffer* getUserDisplayBuffer(const hclBufferDefinition* bufferDefinition); virtual hclBuffer* getUserStaticBuffer(const hclBufferDefinition* bufferDefinition); ClothBufferInput* getInput() { return static_cast<ClothBufferInput*>(m_input); } ClothBufferOutput* getOutput() { return static_cast<ClothBufferOutput*>(m_output); } NameDict<void*> m_UniqueBuffers; }; /* * Links a Havok Mesh to a set of Vixen Shape objects. * Each Havok MeshSection is linked to the Mesh object owned by a Vixen Shape. * Havok meshes with more than one section are represented as a Vixen Model * with a Shape child for each mesh section. * This class implements the Havok calls necessary to link the Vixen Shapes * representing the mesh to the corresponding Havok MeshSections. */ class ClothSetupMesh : public hclSetupMesh { public: ClothSetupMesh(const Model* meshroot, const hkMatrix4& worldFromMesh); ~ClothSetupMesh(); const char* getMeshName() const { return m_Name; } hkUint32 getNumberOfMeshSections() const { return (hkUint32) m_Sections.GetSize(); } void getWorldFromMeshTransform(hkMatrix4& t) const { m_WorldFromMesh.get4x4ColumnMajor((hkReal*) &t); } const hclSetupMeshSection* getSetupMeshSection(hkUint32 i) const { return (hclSetupMeshSection*) m_Sections.GetAt(i); } /* * We take vertex selections, vertex weights, and skinning info. from the Havok toolchain, * so the Vixen setup mesh does not need to implement the following functions * (i.e. the hclSceneDataSetupMesh implementations of these are used, via the hclExtendedUserSetupMesh). */ hkUint32 getNumberOfVertexChannels () const { return 0; } const char* getVertexChannelName(hkUint32 index) const { return HK_NULL; } hkUint32 getNumberOfTriangleChannels() const { return 0; } const char* getTriangleChannelName(hkUint32 index) const { return HK_NULL; } hkBool isSkinned() const { return false; } hkUint32 getNumberOfBones() const { return 0xffffffff; } const char* getBoneName(hkUint32 boneIndex) const { return HK_NULL; } void getBoneFromSkinTransform(hkUint32 boneIndex, hkMatrix4& boneFromSkin) const { } hclSetupMesh::TriangleChannelType getTriangleChannelType(hkUint32 index) const { return hclSetupMesh::HCL_TRIANGLE_CHANNEL_INVALID; } hclSetupMesh::VertexChannelType getVertexChannelType (hkUint32 index) const { return hclSetupMesh::HCL_VERTEX_CHANNEL_INVALID; } protected: Core::String m_Name; PtrArray m_Sections; hkMatrix4 m_WorldFromMesh; }; /* * Links a Havok MeshSection to a Vixen Mesh object. * This class implements the Havok calls necessary for Havok to access * the index and vertex arrays of the Vixen Mesh so it may be used * to display the output of a Havok Cloth simulation. */ class ClothSetupMeshSection : public hclSetupMeshSection { public: ClothSetupMeshSection(const ClothSetupMesh* setupMesh, Mesh* mesh); ~ClothSetupMeshSection(); const char* getMeshName() const { return m_Mesh->GetName(); } void getWorldFromMeshTransform(hkMatrix4& transformOut) const; hkUint32 getNumberOfMeshSections () const; hkUint32 getNumberOfBoneInfluences(hkUint32 vIndex) const { return 0; } void getBoneInfluence(hkUint32 vIndex, hkUint32 infIndex, hkUint32& boneIndex, hkReal& weight) const {} hkBool hasNormals() const { return (m_Mesh->GetStyle() & VertexPool::NORMALS) != 0; } hkBool hasTangents() const { return false; } // TODO: implement this hkBool hasBiTangents() const { return false; } // TODO: implement this hkUint32 getNumberOfVertices() const { return (hkUint32) m_Mesh->GetNumVtx(); } hkResult getVertexPosition(hkUint32 index, hkVector4& v) const; hkResult getVertexNormal(hkUint32 index, hkVector4& v) const; hkResult getTangent(hkUint32 index, hkVector4& v) const; hkResult getBiTangent(hkUint32 index, hkVector4& v) const; hkUint32 getNumberOfTriangles() const { return (hkUint32) m_Mesh->GetNumFaces(); } hkResult getTriangle(hkUint32 index, Triangle& triangle) const; hkResult getVertexTangent(hkUint32 index, hkVector4& tangentOut) const { return HK_FAILURE; } hkResult getVertexBiTangent(hkUint32 index, hkVector4& biTangentOut) const { return HK_FAILURE; } const hclSetupMesh* getMeshInterface() const { return m_SetupMesh; } const hclSetupMeshSection* getSetupMeshSection(hkUint32 index) const; protected: const ClothSetupMesh* m_SetupMesh; Ref<Mesh> m_Mesh; VertexArray::Iter m_Iter; }; /* * Links a Vixen RagDoll (Havok physics-based Skeleton) to a Havok Cloth hclTransformSetupSet. * This class implements the Havok calls necessary for Havok to access the current * pose of the skeleton to drive a skinned animation. */ class ClothTransformSetup : public hclTransformSetSetupObject { public: HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_CLOTH_SETUP ); ClothTransformSetup(const RagDoll* skeleton); // hclTransformSetSetupObject interface RagDoll* getSkeleton() const { return m_Skeleton; } const char* getName() const { return m_SkelName; } const char* getSkeletonName() const { return m_SkelName; } hkUint32 getNumberOfTransforms () const { return m_Skeleton->GetNumBones(); } const char* getTransformName(hkUint32 index) const { return m_Skeleton->GetBoneName(index); } int getTransformParentIndex(hkUint32 index) const; void getSetupTransforms(hkArray<hkMatrix4>& transformsOut) const; hclTransformSetDefinition* _createTransformSetDefinition(const hclClothSetupExecution& executionData) const; protected: Ref<RagDoll> m_Skeleton; Core::String m_SkelName; }; /* * Provides Havok cloth setup process access to the Vixen and Havok scene hierarchy. */ ClothSetup::ClothSetup(Scene* vixenscene, const hkxScene* havokscene) : hclUserSetupRuntimeDisplayData(), m_VixenScene(vixenscene), m_HavokScene(havokscene) { VX_ASSERT(vixenscene); VX_ASSERT(havokscene); } /* * Finds the Vixen Mesh corresponding to a Havok mesh section by name. * @param meshname name of Havok mesh to find. * @param section 0-based index of Havok mesh section. * @param root Vixen root Model for the mesh. If this is not null, * it should point to the Vixen Model whose child Shapes * represent Havok MeshSections or a single Vixen Shape * (for a Havok Mesh with only one section.) * * A Havok Mesh with more than one section is represented by a Vixen Model * with a child Shape for each Havok MeshSection. The name of the Model * is the same as the name of the Havok Mesh. The name of each child Shape * is the Mesh name with a numeric suffix for the mesh section (e.g. mesh-0, mesh-1). * For a Havok mesh with one section, a single Vixen Shape of the same name is used. * * @return Vixen Mesh corresponding to Havok MeshSection or NULL if not found. */ const Mesh* ClothSetup::FindMesh(const char* meshName, int section) const { return (const Mesh*) FindMeshByName(meshName, section, (Model*) m_VixenScene->GetModels()); } Mesh* ClothSetup::FindMeshByName(const char* meshName, int section, Model* root) { Shape* shape; Core::String name(TEXT('.')); Geometry* geo; VX_ASSERT(root); name += meshName; root = (Model*) root->Find(name, Group::FIND_DESCEND | Group::FIND_END); if (root == NULL) VX_ERROR(("ClothSetup: FindMesh %s ERROR model not found", name), NULL); if (root->IsClass(VX_Shape)) shape = (Shape*) root; else { name += TEXT('-'); name += Core::String(section); shape = (Shape*) root->Find(name, Group::FIND_CHILD | Group::FIND_END); if ((shape == NULL) || !shape->IsClass(VX_Shape)) VX_ERROR(("ClothSetup: FindMesh %s ERROR shape not found", name), NULL); } geo = shape->GetGeometry(); if ((geo == NULL) || !geo->IsClass(VX_Mesh)) VX_ERROR(("ClothSetup: FindMesh %s %d ERROR %s has no geometry", meshName, section, shape->GetName()), NULL); VX_TRACE(Physics::Debug > 1, ("ClothSetup: FindMesh %s %d -> %s %d verts, %d tris", meshName, section, shape->GetName(), geo->GetNumVtx(), geo->GetNumFaces())); return (Mesh*) geo; } /* * Finds the Vixen Model corresponding to a Havok Mesh by name. * @param meshname name of Havok mesh to find. * * A Havok Mesh with more than one section is represented by a Vixen Model * with a child Shape for each Havok MeshSection. The name of the Model * is the same as the name of the Havok Mesh. For a Havok mesh with one section, * a single Vixen Shape of the same name is used. * * @return Vixen Model or Shape corresponding to Havok Mesh. */ Model* ClothSetup::FindModel(const char* meshname) const { Model* root = m_VixenScene->GetModels(); Core::String name(TEXT('.')); name += meshname; if (root) return (Model*) root->Find(meshname, Group::FIND_DESCEND | Group::FIND_END); return NULL; } /* * Describes the layout of a Vixen Mesh to Havok in terms of hclBufferLayout. * @param mesh Vixen mesh to describe * @param dstlayout Havok layout structure to get mesh description. */ void ClothSetup::getBufferLayout(const Mesh* mesh, hclBufferLayout &dstlayout) const { const DataLayout* srclayout; const VertexArray* verts; VX_ASSERT(mesh); verts = mesh->GetVertices(); if (verts == NULL) return; verts->MakeLock(); verts->Lock(); srclayout = verts->GetLayout(); dstlayout.m_triangleFormat = hclBufferLayout::TF_THREE_INT32S; dstlayout.m_numSlots = 1; dstlayout.m_slots[0].m_stride = (hkUint8) srclayout->Size * sizeof(float); dstlayout.m_slots[0].m_flags = hclBufferLayout::SF_16BYTE_ALIGNED_START; for (int i = 0; i < srclayout->NumSlots; ++i) { const LayoutSlot& slot = srclayout->Slot[i]; int havokindex; if (slot.Name.Right(8) == TEXT("position")) havokindex = 0; else if (slot.Name.Right(6) == TEXT("normal")) havokindex = 1; else if (slot.Name.Right(7) == TEXT("bitangent")) havokindex = 2; else if (slot.Name.Right(6) == TEXT("tangent")) havokindex = 3; else continue; hclBufferLayout::BufferElement& dstelem = dstlayout.m_elementsLayout[havokindex]; dstelem.m_vectorConversion = hclRuntimeConversionInfo::VC_FLOAT3; dstelem.m_vectorSize = 3 * sizeof(float); dstelem.m_slotId = 0; dstelem.m_slotStart = (hkUint8) slot.Offset * sizeof(float); } verts->Unlock(); } /* * Describes the layout of the Vixen Mesh corresponding to a Havok MeshSection as hclBufferLayout. * The Vixen mesh will be used to display the output of a Havok Cloth simulation so it will be modified. * @param meshname name of Havok mesh to find. * @param section 0-based index of Havok mesh section. * @param dstlayout Havok layout structure to get mesh description. */ void ClothSetup::getDisplayBufferLayout(const char *meshname, hkUint32 section, hclBufferLayout &dstlayout) const { const Mesh* mesh = FindMesh(meshname, (int) section); if (mesh) { getBufferLayout(mesh, dstlayout); return; } VX_ERROR_RETURN(("ClothSetup: ERROR mesh %s %d not found in Vixen scene", meshname, section)); } /* * Describes the layout of a static buffer in terms of hclBufferLayout. * The buffer can come from either Vixen or Havok. If it is not found in the Vixen scene, * the Havok scene is then searched. * @param meshname name of scene mesh to find. * @param section 0-based index of Havok mesh section. * @param dstlayout Havok layout structure to get mesh description. */ void ClothSetup::getStaticDisplayBufferLayout(const char *objectName, hkUint32 section, hclBufferLayout &layout) const { const Mesh* mesh = FindMesh(objectName, (int) section); // static buffer came from a Vixen mesh if (mesh) { getBufferLayout(mesh, layout); return; } // Static buffer came from a Havok mesh. const hkxNode* node = m_HavokScene->findNodeByName(objectName); if (node == NULL) VX_ERROR_RETURN(("ClothSetup: ERROR node %s not found in Havok scene", objectName)); hclSceneDataBuffer::getSceneDataBufferLayout(node, section, layout); } /* * Describes a skeleton in the scene in terms of ClothTransformSetup. * @param skelname name of skeleton to get pose for * * The skeleton is assumed to be in the Vixen scene. This function makes a ClothTransformSetup * object (a subclass of the Havok hclTransformSetSetupObject) which provides Havok access * to the structure of the skeleton and the current pose. */ hclTransformSetSetupObject* ClothSetup::getTransformSetForObject(const char* skelname) const { Core::String name(TEXT('.')); const RagDoll* skel; name += skelname; name += TEXT(".skeleton"); skel = (const RagDoll*) m_VixenScene->GetEngines()->Find(name, Group::FIND_DESCEND | Group::FIND_END); if (skel && skel->IsClass(VX_Skeleton)) { ClothTransformSetup* transformSetSetup = new ClothTransformSetup(skel); skel->MakeLock(); if (transformSetSetup->isValid()) { void* ptr = transformSetSetup; m_Transforms.Append(ptr); return transformSetSetup; } else { delete transformSetSetup; HK_ERROR(0x0, "Transform set setup invalid."); } } HK_WARN_ALWAYS(0x0, "Skeleton " << skelname << " not found, so cannot make a requested hclTransformSetSetupObject (setup execution will fail)."); return NULL; } /* * Describes the set of Vixen Shapes for a scene object in terms of hclSetupMesh. * @param objname name of scene object (a Havok Mesh) * * Constructs the Havok cloth setup infrastructure for a single Havok Mesh. * This allows Havok to read and write the vertices of the Vixen Shape * objects which are used to display the results of simulation on the mesh. */ const hclSetupMesh* ClothSetup::getMeshDataForObject(const char *objname) const { hclExtendedUserSetupMesh::Options userSetupMeshOptions; const Model* meshroot = FindModel(objname); const hkxNode* node = m_HavokScene->findNodeByName(objname); hclSetupMesh* setupMesh = HK_NULL; hclSceneDataSetupMesh* havokSetupMesh; hclExtendedUserSetupMesh* extendedUserSetupMesh; hkMatrix4 worldFromMesh; MatrixH worldFromModel; hclSetupMesh* vixenSetupMesh; void** setupPtr; if ((meshroot == NULL) || (node == NULL)) return NULL; setupPtr = m_SetupMeshes.Find(objname); if (setupPtr != NULL) { setupMesh = (hclSetupMesh*) *setupPtr; if (setupMesh != NULL) return setupMesh; } worldFromMesh.setIdentity(); //m_HavokScene->getWorldFromNodeTransform(node, worldFromMesh, 0); //meshroot->TotalTransform(&worldFromModel); vixenSetupMesh = new ClothSetupMesh(meshroot, worldFromModel); havokSetupMesh = new hclSceneDataSetupMesh(node, worldFromMesh); userSetupMeshOptions.m_maxDistanceForMatch = 0.01f; userSetupMeshOptions.m_userSetupMesh = vixenSetupMesh; userSetupMeshOptions.m_sceneDataSetupMesh = havokSetupMesh; userSetupMeshOptions.m_useUserNormalIds = false; extendedUserSetupMesh = hclExtendedUserSetupMesh::create(userSetupMeshOptions); vixenSetupMesh->removeReference(); havokSetupMesh->removeReference(); setupMesh = extendedUserSetupMesh; m_SetupMeshes[objname] = setupMesh; return setupMesh; } /* * Creates a new hclBuffer for the given scene mesh. * @param bufferdef Havok buffer definition with name of Mesh and index of MeshSection. * This function tries to find a Vixen Shape with the corresponding name. * If this is found, a ClothBuffer is made which informs Havok about the Vixen Mesh. * @return ClothBuffer to describe Vixen Mesh or NULL if mesh not found in Vixen scene */ hclBuffer* ClothBufferUtil::getUserDisplayBuffer(const hclBufferDefinition* bufferdef) { Core::String bufname(bufferdef->m_name); const char* name; hclBuffer* buffer = NULL; void** bufptr; bufname += TEXT('-'); bufname += Core::String(bufferdef->m_subType); name = bufname; bufptr = m_UniqueBuffers.Find(name); if (bufptr) buffer = (hclBuffer*) *bufptr; if (buffer) { buffer->addReference(); return buffer; } ClothBufferInput* input = getInput(); Mesh* mesh = ClothSetup::FindMeshByName(bufferdef->m_name, bufferdef->m_subType, input->m_VixenScene->GetModels()); if (mesh) // Create buffer based on Vixen mesh { buffer = new ClothBuffer(mesh); m_UniqueBuffers[name] = buffer; buffer->addReference(); return buffer; } else { HK_WARN_ALWAYS(0xabba56fe, "Could not find object in the Vixen scene " << bufferdef->m_name); getOutput()->m_result = HK_FAILURE; } return NULL; } /* * Creates a new hclBuffer for the given scene mesh. * @param bufferdef Havok buffer definition with name of Mesh and index of MeshSection. * This function tries to find a Havok MeshSection in the Havok scene with the given name and index * and make a hclSceneDataBuffer from it. * Static meshes are exported via both the Vixen and Havok path. * Since they are the same, we use the Havok scene mesh for the static buffer. */ hclBuffer* ClothBufferUtil::getUserStaticBuffer(const hclBufferDefinition* bufferdef) { ClothBufferInput* input = getInput(); Core::String bufname(bufferdef->m_name); hkxNode* node = input->m_HavokScene->findNodeByName(bufname); hkxMesh* mesh; const char* name; hclBuffer* buffer = NULL; void** bufptr; bufname += TEXT('-'); bufname += Core::String(bufferdef->m_subType); name = bufname; bufptr = m_UniqueBuffers.Find(name); if (bufptr) buffer = (hclBuffer*) *bufptr; if (buffer) { buffer->addReference(); return buffer; } if (node == NULL) VX_ERROR(("ClothBufferUtil: ERROR static buffer %s not found", name), NULL); mesh = hkxSceneUtils::getMeshFromNode(node); if (mesh == NULL) VX_ERROR(("ClothBufferUtil: ERROR static buffer %s has no geometry", name), NULL); VX_TRACE(Physics::Debug > 1, ("ClothBufferUtil: found Havok static buffer %s", bufname)); buffer = new hclSceneDataBuffer(input->m_HavokScene, node, bufferdef->m_subType); m_UniqueBuffers[name] = buffer; buffer->addReference(); return buffer; } /* * Provides Havok access to the vertices of a Vixen Mesh. * @param mesh Vixen mesh. * * Constructs the Havok cloth setup infrastructure to allow Havok * to read and write the vertices of the Vixen Mesh. */ ClothBuffer::ClothBuffer(Mesh* mesh) { hkUint32 nvtx = (hkUint32) mesh->GetNumVtx(); const VertexArray* verts = mesh->GetVertices(); VX_ASSERT(verts); const DataLayout* layout = verts->GetLayout(); VX_ASSERT(layout); m_Mesh = mesh; verts->MakeLock(); mesh->GetIndices()->MakeLock(); m_positions.m_numElements = 0; m_normals.m_numElements = 0; m_tangents.m_numElements = 0; m_biTangents.m_numElements = 0; m_triangles.m_numElements = 0; m_positions.m_bufferStart = NULL; m_tangents.m_bufferStart = NULL; m_biTangents.m_bufferStart = NULL; m_triangles.m_bufferStart = NULL; m_SlotMap[0] = -1; m_SlotMap[1] = -1; m_SlotMap[2] = -1; m_SlotMap[3] = -1; for (int i = 0; i < layout->NumSlots; ++i) { const LayoutSlot& slot = layout->Slot[i]; if (slot.Name.Right(8) == TEXT("position")) { m_positions.m_numElements = nvtx; m_SlotMap[0] = i; } else if (slot.Name.Right(9) == TEXT("bitangent")) { m_biTangents.m_numElements = nvtx; m_SlotMap[2] = i; } else if (slot.Name.Right(7) == TEXT("tangent")) { m_tangents.m_numElements = nvtx; m_SlotMap[3] = i; } else if (slot.Name.Right(6) == TEXT("normal")) { m_normals.m_numElements = nvtx; m_SlotMap[1] = i; } else continue; } m_triangles.m_numElements = (hkUint32) mesh->GetNumFaces(); VX_TRACE(Physics::Debug > 1, ("ClothBuffer: %s %d verts, %d tris", mesh->GetName(), nvtx, m_triangles.m_numElements)); } /* * Called by Havok before accessing vertices of the Vixen mesh. * This function locks the vertex and index arrays associated with the mesh. */ hkResult ClothBuffer::notifyBeginAccess(const hclBufferUsage& bufferUsage) { const VertexArray* verts = m_Mesh->GetVertices(); VX_ASSERT(verts); const IndexArray* inds = m_Mesh->GetIndices(); VX_ASSERT(inds); const DataLayout* layout; const float* vertdata; intptr nvtx; int stride; VX_TRACE(Physics::Debug > 2, ("ClothBuffer: %s lock", m_Mesh->GetName())); inds->Lock(); verts->Lock(); nvtx = verts->GetNumVtx(); stride = verts->GetVtxSize() * sizeof(float); vertdata = verts->GetData(); layout = verts->GetLayout(); m_positions.m_bufferStart = HK_NULL; m_normals.m_bufferStart = HK_NULL; m_tangents.m_bufferStart = HK_NULL; m_biTangents.m_bufferStart = HK_NULL; m_positions.m_numElements = 0; m_normals.m_numElements = 0; m_tangents.m_numElements = 0; m_biTangents.m_numElements = 0; m_triangles.m_numElements = (hkUint32) inds->GetSize() / 3; m_triangles.m_bufferStart = (void*) inds->GetData(); m_triangles.m_stride = 3 * sizeof(int32); m_triangles.m_use16BitsIndices = false; if (m_SlotMap[0] >= 0) // POSITIONS { const LayoutSlot& slot = layout->Slot[m_SlotMap[0]]; m_positions.m_bufferStart = (void*) vertdata; m_positions.m_numElements = (hkUint32) nvtx; m_positions.m_stride = (hkUint8) stride; m_positions.m_flags = 0; } if (m_SlotMap[1] >= 0) // NORMALS { const LayoutSlot& slot = layout->Slot[m_SlotMap[1]]; m_normals.m_bufferStart = (void*) (vertdata + slot.Offset); m_normals.m_numElements = (hkUint32) nvtx; m_normals.m_stride = (hkUint8) stride; m_normals.m_flags = 0; } if (m_SlotMap[2] >= 0) // TANGENTS { const LayoutSlot& slot = layout->Slot[m_SlotMap[2]]; m_tangents.m_bufferStart = (void*) (vertdata + slot.Offset); m_tangents.m_numElements = (hkUint32) nvtx; m_tangents.m_stride = (hkUint8) stride; m_tangents.m_flags = 0; } if (m_SlotMap[3] >= 0) // BITANGENTS { const LayoutSlot& slot = layout->Slot[m_SlotMap[3]]; m_biTangents.m_bufferStart = (void*) (vertdata + slot.Offset); m_biTangents.m_numElements = (hkUint32) nvtx; m_biTangents.m_stride = (hkUint8) stride; m_biTangents.m_flags = 0; } return HK_SUCCESS; } /* * Called by Havok after accessing vertices of the Vixen mesh. * This function unlocks the vertex and index arrays associated with the mesh. */ hkResult ClothBuffer::notifyEndAccess() { const VertexArray* verts = m_Mesh->GetVertices(); const IndexArray* inds = m_Mesh->GetIndices(); verts->SetChanged(true); verts->Unlock(); inds->Unlock(); VX_TRACE(Physics::Debug > 2, ("ClothBuffer: %s unlock", m_Mesh->GetName())); return HK_SUCCESS; } ClothSetupMesh::ClothSetupMesh(const Model* meshroot, const hkMatrix4& worldFromMesh) : m_WorldFromMesh(worldFromMesh) { /* * Strip off the file name, isolating the mesh name */ m_Name = meshroot->GetName(); /* * Only one shape representing this object? * Just make one mesh section. */ if (meshroot->IsClass(VX_Shape) && !meshroot->IsParent()) { Mesh* mesh = (Mesh*) ((Shape*) meshroot)->GetGeometry(); VX_ASSERT(mesh && mesh->IsClass(VX_Mesh)); m_Sections.SetAt(0, new ClothSetupMeshSection(this, mesh)); return; } /* * Multiple shapes represent this mesh? Make a different * mesh section for each child. */ Shape::Iter iter(meshroot); Core::String meshname(meshroot->GetName()); Shape* shape; size_t len = meshname.GetLength(); int i = 0; while (shape = (Shape*) iter.Next()) { Core::String childname(shape->GetName()); if (!shape->IsClass(VX_Shape)) continue; if (childname.Left(len) != meshname) continue; Mesh* mesh = (Mesh*) shape->GetGeometry(); shape->GetAppearance()->Set(Appearance::CULLING, 0); VX_ASSERT(mesh && mesh->IsClass(VX_Mesh)); m_Sections.SetAt(i++, new ClothSetupMeshSection(this, mesh)); } } ClothSetupMesh::~ClothSetupMesh() { for (int i = 0; i < m_Sections.GetSize(); ++i) { delete m_Sections[i]; } } ClothSetupMeshSection::ClothSetupMeshSection(const ClothSetupMesh* setupMesh, Mesh* mesh) : m_SetupMesh(setupMesh), m_Mesh(mesh), m_Iter(mesh->GetVertices()) { mesh->GetVertices()->Lock(); } ClothSetupMeshSection::~ClothSetupMeshSection() { m_Mesh->GetVertices()->Unlock(); } hkResult ClothSetupMeshSection::getVertexPosition(hkUint32 index, hkVector4& dstpos) const { Vec3* srcpos = (Vec3*) m_Iter.GetVtx(index); if (srcpos) { dstpos.set(srcpos->x, srcpos->y, srcpos->z); return HK_SUCCESS; } return HK_FAILURE; } hkResult ClothSetupMeshSection::getVertexNormal(hkUint32 index, hkVector4& normal) const { Vec3* srcnml = (Vec3*) m_Iter.GetNormal(index); if (srcnml) { normal.set(srcnml->x, srcnml->y, srcnml->z); return HK_SUCCESS; } return HK_FAILURE; } hkResult ClothSetupMeshSection::getTriangle(hkUint32 index, Triangle& triangle) const { const IndexArray* inds = m_Mesh->GetIndices(); intptr numtris; if (inds == NULL) return HK_FAILURE; numtris = inds->GetSize() / 3; if (index >= numtris) { HK_ASSERT(0x0, "index >= num. triangles in ClothSetupMeshSection::getTriangle()"); return HK_FAILURE; } index *= 3; triangle.m_indices[0] = inds->GetAt(index); triangle.m_indices[1] = inds->GetAt(index + 1); triangle.m_indices[2] = inds->GetAt(index + 2); return HK_SUCCESS; } ClothTransformSetup::ClothTransformSetup(const RagDoll* skeleton) : m_Skeleton(skeleton) { int p; const Pose* pose = m_Skeleton->GetPose(); pose->MakeLock(); m_SkelName = skeleton->GetName(); if (m_SkelName.Right(9) == TEXT(".skeleton")) m_SkelName = m_SkelName.Left(m_SkelName.GetLength() - 9); p = m_SkelName.Find(TEXT('.')); if (p > 0) m_SkelName = m_SkelName.Mid(p + 1); } int ClothTransformSetup::getTransformParentIndex(hkUint32 index) const { if (!m_Skeleton.IsNull()) return m_Skeleton->GetParentBoneIndex(index); return -1; } void ClothTransformSetup::getSetupTransforms(hkArray<hkMatrix4>& transforms) const { int numBones = m_Skeleton->GetNumBones(); const Pose* pose = m_Skeleton->GetPose(); ObjectLock lock(pose); transforms.setSize(numBones); for (int b = 0; b < numBones; ++b) { MatrixH mtx; pose->GetWorldMatrix(b, mtx); transforms[b] = mtx; } } // This hclTransformSetDefinition object is stored in the cloth data, and is meant to be used at runtime during cloth instantiation to // determine which Vixen skeleton should be associated with each hclTransformSet in the cloth instance. // (Similarly to how the hclBufferDefinitions associate Vixen meshes with each hclBuffer in the cloth instance, at buffer instantiation time). // In our case, we know there is only one skeleton needed, so this information is only used as a check. hclTransformSetDefinition* ClothTransformSetup::_createTransformSetDefinition(const hclClothSetupExecution& executionData) const { hclTransformSetDefinition* transformSetDefinition = new hclTransformSetDefinition(); transformSetDefinition->m_name = m_SkelName; transformSetDefinition->m_type = HCL_TRANSFORMSET_TYPE_ANIMATION; transformSetDefinition->m_numTransforms = m_Skeleton->GetNumBones(); return transformSetDefinition; } ClothSkin* SetupCloth(Scene* vixenscene, hkxScene* havokscene, hclClothSetupObject* setupinfo) { hclClothSetupExecutionReporter reporter; hclClothSetupExecution::Options opts; ClothSetup setup(vixenscene, havokscene); hclClothData* data; ClothSkin* clothskin; Core::String name(setupinfo->getName()); opts.m_targetPlatform = hclClothData::HCL_PLATFORM_WIN32; opts.m_reporter = &reporter; hclClothSetupExecution exec(*setupinfo, setup, &setup, opts); data = exec.getClothData(); if (data == NULL) VX_ERROR(("Havok Cloth Setup failed for %s", name), NULL); clothskin = new ClothSkin(data); name += TEXT(".clothskin"); clothskin->SetName(name); return clothskin; } float ClothSkin::ComputeTime(float t) { return Engine::ComputeTime(t); } bool ClothSkin::OnStart() { if ((m_ClothInstance == NULL) && m_ClothData) { Scene* vixenscene = World3D::Get()->GetScene(); ClothSim* clothsim = (ClothSim*) Parent(); hclWorld* world; hclCollidable* ground = NULL; ClothBufferOutput output; hclClothData::InstanceOptions options; VX_ASSERT(clothsim); VX_ASSERT(clothsim->IsKindOf(&ClothSim::ClassInfo)); ClothBufferInput input(clothsim->GetHavokScene(), vixenscene); m_ClothInstance = m_ClothData->createInstance(options); ground = clothsim->GetGroundCollide(); if (ground != NULL) { for (int sc = 0; sc < m_ClothInstance->m_simClothInstances.getSize(); ++sc) { hclSimClothInstance* scinstance= m_ClothInstance->m_simClothInstances[sc]; scinstance->addWorldCollidable(ground); VX_TRACE(ClothSim::Debug || ClothSkin::Debug, ("ClothSkin: %s adding ground plane", GetName())); } } input.m_clothInstance = m_ClothInstance; world = ClothSim::GetWorld(); if (world == NULL) return false; VX_TRACE(Physics::Debug || ClothSim::Debug || ClothSkin::Debug, ("ClothSkin: %s creating cloth instance", GetName())); world->lockAll(); world->setOnTheFlyNotificationsEnabled(true); world->addClothInstance(m_ClothInstance); for (int i = 0; i < m_ClothData->m_transformSetDefinitions.getSize(); ++i) { const hclTransformSetDefinition* tsdef = m_ClothData->m_transformSetDefinitions[i]; Core::String skelname(TEXT('.')); RagDoll* skeleton; hclTransformSet* tset = new hclTransformSet(); skelname += tsdef->m_name; skelname += TEXT(".skeleton"); skeleton = (RagDoll*) vixenscene->GetEngines()->Find(skelname, Group::FIND_DESCEND | Group::FIND_END); if (skeleton == NULL) { VX_WARNING(("ClothSkin: %s cannot find skeleton %s", GetName(), skelname)); continue; } VX_ASSERT(skeleton->IsClass(VX_RagDoll)); VX_ASSERT(tsdef->m_numTransforms == skeleton->GetNumBones()); m_Skeletons.SetAt(i, skeleton); SetSkeleton(skeleton); skeleton->MakeLock(); HavokPose bindpose(skeleton); bindpose.GetTransforms(tset); m_ClothInstance->setTransformSet(i, tset); VX_TRACE(ClothSim::Debug || ClothSkin::Debug, ("ClothSkin: %s linked to skeleton %s", GetName(), skeleton->GetName())); } ClothBufferUtil makebuffers(input, output); makebuffers.instantiateBuffers(); m_ClothData->removeReference(); m_ClothData = HK_NULL; world->unlockAll(); } return Engine::OnStart(); } } // end Vixen
35.326904
146
0.7413
[ "mesh", "geometry", "object", "shape", "model", "transform" ]
1ac2342bd68493042981e10c594af8d2eeb22223
3,443
cc
C++
test/orange/surfaces/GeneralQuadric.test.cc
tmdelellis/celeritas
5252bcb0659892ae9082ca2b6716e3c84e18004b
[ "Apache-2.0", "MIT" ]
22
2020-03-31T14:18:22.000Z
2022-01-10T09:43:06.000Z
test/orange/surfaces/GeneralQuadric.test.cc
tmdelellis/celeritas
5252bcb0659892ae9082ca2b6716e3c84e18004b
[ "Apache-2.0", "MIT" ]
261
2020-04-29T15:14:29.000Z
2022-03-31T19:07:14.000Z
test/orange/surfaces/GeneralQuadric.test.cc
tmdelellis/celeritas
5252bcb0659892ae9082ca2b6716e3c84e18004b
[ "Apache-2.0", "MIT" ]
15
2020-05-01T19:47:19.000Z
2021-12-25T06:12:09.000Z
//----------------------------------*-C++-*----------------------------------// // Copyright 2021 UT-Battelle, LLC, and other Celeritas developers. // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: (Apache-2.0 OR MIT) //---------------------------------------------------------------------------// //! \file GeneralQuadric.test.cc //---------------------------------------------------------------------------// #include "orange/surfaces/GeneralQuadric.hh" #include "celeritas_test.hh" using celeritas::GeneralQuadric; using celeritas::no_intersection; using celeritas::SignedSense; using celeritas::SurfaceState; using celeritas::ipow; using celeritas::Real3; using celeritas::real_type; using Intersections = GeneralQuadric::Intersections; //---------------------------------------------------------------------------// // TEST HARNESS //---------------------------------------------------------------------------// class GeneralQuadricTest : public celeritas::Test { protected: void SetUp() override {} }; //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// /*! * This shape is an ellipsoid: * - with radii {3, 2, 1}, * - rotated by 60 degrees about the x axis, * - then 30 degrees about z, * - and finally translated by {1, 2, 3}. */ TEST_F(GeneralQuadricTest, all) { EXPECT_EQ(celeritas::SurfaceType::gq, GeneralQuadric::surface_type()); EXPECT_EQ(10, GeneralQuadric::Storage::extent); EXPECT_EQ(2, GeneralQuadric::Intersections{}.size()); const Real3 second{10.3125, 22.9375, 15.75}; const Real3 cross{-21.867141445557, -20.25, 11.69134295109}; const Real3 first{-11.964745962156, -9.1328585544429, -65.69134295109}; real_type zeroth = 77.652245962156; GeneralQuadric gq{second, cross, first, zeroth}; EXPECT_VEC_SOFT_EQ(second, gq.second()); EXPECT_VEC_SOFT_EQ(cross, gq.cross()); EXPECT_VEC_SOFT_EQ(first, gq.first()); EXPECT_SOFT_EQ(zeroth, gq.zeroth()); EXPECT_EQ(SignedSense::outside, gq.calc_sense({4, 5, 5})); EXPECT_EQ(SignedSense::inside, gq.calc_sense({1, 2, 3})); const Real3 center{1, 2, 3}; const Real3 on_surface{3.598076211353292, 3.5, 3}; const Real3 inward{-0.8660254037844386, -0.5, 0}; const Real3 outward{0.8660254037844386, 0.5, 0}; Intersections distances; // On surface, inward distances = gq.calc_intersections(on_surface, inward, SurfaceState::on); EXPECT_SOFT_EQ(6.0, distances[0]); EXPECT_SOFT_EQ(no_intersection(), distances[1]); // "Not on surface", inward distances = gq.calc_intersections(on_surface, inward, SurfaceState::off); EXPECT_SOFT_EQ(1e-16, distances[0]); EXPECT_SOFT_EQ(6.0, distances[1]); // On surface, outward distances = gq.calc_intersections(on_surface, outward, SurfaceState::on); EXPECT_SOFT_EQ(no_intersection(), distances[0]); EXPECT_SOFT_EQ(no_intersection(), distances[1]); // In center distances = gq.calc_intersections(center, outward, SurfaceState::off); EXPECT_SOFT_EQ(3.0, distances[1]); EXPECT_SOFT_EQ(no_intersection(), distances[0]); // Outside, hitting both const Real3 pos{-2.464101615137754, 0, 3}; distances = gq.calc_intersections(pos, outward, SurfaceState::off); EXPECT_SOFT_EQ(1.0, distances[0]); EXPECT_SOFT_EQ(7.0, distances[1]); }
35.864583
79
0.593959
[ "shape" ]
1ac32786576d4b759f76632679a9c5963bd0c2e0
14,969
cpp
C++
test/com/ResultToTextTest/ResultToTextTest.cpp
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
test/com/ResultToTextTest/ResultToTextTest.cpp
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
test/com/ResultToTextTest/ResultToTextTest.cpp
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
//=---------------------------------------------------------------------= // // $Id$ $Name$ // // The contents of this file are subject to the AAF SDK Public Source // License Agreement Version 2.0 (the "License"); You may not use this // file except in compliance with the License. The License is available // in AAFSDKPSL.TXT, or you may obtain a copy of the License from the // Advanced Media Workflow Association, Inc., or its successor. // // 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. Refer to Section 3.3 of the License for proper use // of this Exhibit. // // WARNING: Please contact the Advanced Media Workflow Association, // Inc., for more information about any additional licenses to // intellectual property covering the AAF Standard that may be required // to create and distribute AAF compliant products. // (http://www.amwa.tv/policies). // // Copyright Notices: // The Original Code of this file is Copyright 1998-2009, licensor of the // Advanced Media Workflow Association. All rights reserved. // // The Initial Developer of the Original Code of this file and the // licensor of the Advanced Media Workflow Association is // Avid Technology. // All rights reserved. // //=---------------------------------------------------------------------= #include "AAF.h" #include "AAFResult.h" #include <iostream> #include <iomanip> void testCode(AAFRESULT code) { aafUInt32 len; HRESULT hr; std::wcout.setf(std::ios::showbase); std::wcout << std::hex << std::setw(8) << std::setfill(L'0') << code << L" -> "; hr = AAFResultToTextBufLen(code, &len); if (AAFRESULT_SUCCEEDED(hr)) { aafCharacter* buffer = (aafCharacter*)new char[len]; hr = AAFResultToText(code, buffer, len); if (AAFRESULT_SUCCEEDED(hr)) { aafUInt32 bufferSize = (wcslen(buffer) + 1) * sizeof(wchar_t); if (bufferSize != len) { std::wcout << "Buffer size mismatch." << std::endl; } std::wcout << buffer << std::endl; } else { std::wcout << L"AAFResultToText() failed." << std::endl; } delete [] buffer; } else { std::wcout << L"AAFResultToTextBufLen() failed." << std::endl; } } void positiveTests() { /* SESSION/FILE Error Codes */ testCode(AAFRESULT_BAD_SESSION); testCode(AAFRESULT_BADSESSIONOPEN); testCode(AAFRESULT_BADSESSIONMETA); testCode(AAFRESULT_BADSESSIONCLOSE); testCode(AAFRESULT_BADCONTAINER); testCode(AAFRESULT_FILEREV_NOT_SUPP); testCode(AAFRESULT_FILEREV_DIFF); testCode(AAFRESULT_BADOPEN); testCode(AAFRESULT_BADCLOSE); testCode(AAFRESULT_BAD_FHDL); testCode(AAFRESULT_BADHEAD); testCode(AAFRESULT_NOBYTEORDER); testCode(AAFRESULT_INVALID_BYTEORDER); testCode(AAFRESULT_NOT_AAF_FILE); testCode(AAFRESULT_WRONG_FILETYPE); testCode(AAFRESULT_WRONG_OPENMODE); testCode(AAFRESULT_CONTAINERWRITE); testCode(AAFRESULT_FILE_NOT_FOUND); testCode(AAFRESULT_CANNOT_SAVE_CLSD); testCode(AAFRESULT_CANNOT_LOAD_CLSD); testCode(AAFRESULT_FILE_REV_200); testCode(AAFRESULT_NEED_PRODUCT_IDENT); testCode(AAFRESULT_NOT_WRITEABLE); testCode(AAFRESULT_NOT_READABLE); testCode(AAFRESULT_FILE_EXISTS); testCode(AAFRESULT_NOT_OPEN); testCode(AAFRESULT_ALREADY_OPEN); testCode(AAFRESULT_BAD_FLAGS); testCode(AAFRESULT_BAD_FLAG_COMBINATION); testCode(AAFRESULT_UNSAVED_CHANGES); testCode(AAFRESULT_NOT_REVERTABLE); testCode(AAFRESULT_MEDIA_NOT_REVERTABLE); testCode(AAFRESULT_OPERATION_NOT_PERMITTED); /* Errors returned from raw storage interfaces*/ testCode(AAFRESULT_READ_FAILURE); testCode(AAFRESULT_WRITE_FAILURE); testCode(AAFRESULT_SYNCHRONIZE_FAILURE); testCode(AAFRESULT_SET_EXTENT_FAILURE); testCode(AAFRESULT_NOT_CREATABLE); testCode(AAFRESULT_NOT_MODIFIABLE); testCode(AAFRESULT_GETSIZE_FAILURE); testCode(AAFRESULT_GETEXTENT_FAILURE); testCode(AAFRESULT_SETEXTENT_FAILURE); /* Read-while-modify errors */ testCode(AAFRESULT_FILE_BEING_MODIFIED); /* MEDIA Error Codes */ testCode(AAFRESULT_DESCSAMPRATE); testCode(AAFRESULT_SOURCEMOBLIST); testCode(AAFRESULT_DESCLENGTH); testCode(AAFRESULT_INTERNAL_MDO); testCode(AAFRESULT_3COMPONENT); testCode(AAFRESULT_INVALID_PARM_SIZE); testCode(AAFRESULT_BADSAMPLEOFFSET); testCode(AAFRESULT_ONESAMPLEREAD); testCode(AAFRESULT_ONESAMPLEWRITE); testCode(AAFRESULT_DECOMPRESS); testCode(AAFRESULT_NODATA); testCode(AAFRESULT_SMALLBUF); testCode(AAFRESULT_BADCOMPR); testCode(AAFRESULT_BADPIXFORM); testCode(AAFRESULT_BADLAYOUT); testCode(AAFRESULT_COMPRLINESWR); testCode(AAFRESULT_COMPRLINESRD); testCode(AAFRESULT_BADMEDIATYPE); testCode(AAFRESULT_BADDATAADDRESS); testCode(AAFRESULT_BAD_MDHDL); testCode(AAFRESULT_MEDIA_NOT_FOUND); testCode(AAFRESULT_ILLEGAL_MEMFMT); testCode(AAFRESULT_ILLEGAL_FILEFMT); testCode(AAFRESULT_SWABBUFSIZE); testCode(AAFRESULT_MISSING_SWAP_PROC); testCode(AAFRESULT_NULL_STREAMPROC); testCode(AAFRESULT_NULLBUF); testCode(AAFRESULT_SWAP_SETUP); testCode(AAFRESULT_INVALID_FILE_MOB); testCode(AAFRESULT_SINGLE_CHANNEL_OP); testCode(AAFRESULT_INVALID_CACHE_SIZE); testCode(AAFRESULT_NOT_FILEMOB); testCode(AAFRESULT_TRANSLATE_SAMPLE_SIZE); testCode(AAFRESULT_TRANSLATE_NON_INTEGRAL_RATE); testCode(AAFRESULT_MISSING_MEDIA_REP); testCode(AAFRESULT_NOT_LONGWORD); testCode(AAFRESULT_XFER_DUPCH); testCode(AAFRESULT_MEDIA_NOT_INIT); testCode(AAFRESULT_BLOCKING_SIZE); testCode(AAFRESULT_WRONG_MEDIATYPE); testCode(AAFRESULT_MULTI_WRITELEN); testCode(AAFRESULT_STREAM_REOPEN); testCode(AAFRESULT_TOO_MANY_FMT_OPS); testCode(AAFRESULT_MEDIASTREAM_NOTALLOWED); testCode(AAFRESULT_STILLFRAME_BADLENGTH); testCode(AAFRESULT_DATA_NONCONTIG); testCode(AAFRESULT_OPLIST_OVERFLOW); testCode(AAFRESULT_STREAM_CLOSED); testCode(AAFRESULT_USE_MULTI_CREATE); testCode(AAFRESULT_MEDIA_OPENMODE); testCode(AAFRESULT_MEDIA_CANNOT_CLOSE); testCode(AAFRESULT_CODEC_INVALID); testCode(AAFRESULT_INVALID_OP_CODEC); testCode(AAFRESULT_BAD_CODEC_REV); testCode(AAFRESULT_CODEC_CHANNELS); testCode(AAFRESULT_INTERN_TOO_SMALL); testCode(AAFRESULT_INTERNAL_UNKNOWN_LOC); testCode(AAFRESULT_TRANSLATE); testCode(AAFRESULT_EOF); testCode(AAFRESULT_TIFFVERSION); testCode(AAFRESULT_BADTIFFCOUNT); testCode(AAFRESULT_24BITVIDEO); testCode(AAFRESULT_JPEGBASELINE); testCode(AAFRESULT_BADJPEGINFO); testCode(AAFRESULT_BADQTABLE); testCode(AAFRESULT_BADACTABLE); testCode(AAFRESULT_BADDCTABLE); testCode(AAFRESULT_NOFRAMEINDEX); testCode(AAFRESULT_BADFRAMEOFFSET); testCode(AAFRESULT_JPEGPCM); testCode(AAFRESULT_JPEGDISABLED); testCode(AAFRESULT_JPEGPROBLEM); testCode(AAFRESULT_BADEXPORTPIXFORM); testCode(AAFRESULT_BADEXPORTLAYOUT); testCode(AAFRESULT_BADRWLINES); testCode(AAFRESULT_BADAIFCDATA); testCode(AAFRESULT_BADWAVEDATA); testCode(AAFRESULT_NOAUDIOCONV); testCode(AAFRESULT_XFER_NOT_BYTES); testCode(AAFRESULT_CODEC_NAME_SIZE); testCode(AAFRESULT_ZERO_SAMPLESIZE); testCode(AAFRESULT_ZERO_PIXELSIZE); testCode(AAFRESULT_BAD_VARIETY); testCode(AAFRESULT_FORMAT_BOUNDS); testCode(AAFRESULT_FORMAT_NOT_FOUND); testCode(AAFRESULT_UNKNOWN_CONTAINER); testCode(AAFRESULT_NO_MORE_FLAVOURS); /* OBJECT Error Codes */ testCode(AAFRESULT_NULLOBJECT); testCode(AAFRESULT_BADINDEX); testCode(AAFRESULT_INVALID_LINKAGE); testCode(AAFRESULT_BAD_PROP); testCode(AAFRESULT_BAD_TYPE); testCode(AAFRESULT_SWAB); testCode(AAFRESULT_END_OF_DATA); testCode(AAFRESULT_PROP_NOT_PRESENT); testCode(AAFRESULT_INVALID_DATADEF); testCode(AAFRESULT_DATADEF_EXIST); testCode(AAFRESULT_TOO_MANY_TYPES); testCode(AAFRESULT_BAD_TYPE_CATEGORY); testCode(AAFRESULT_OBJECT_NOT_FOUND); testCode(AAFRESULT_IS_ROOT_CLASS); testCode(AAFRESULT_TYPE_NOT_FOUND); testCode(AAFRESULT_PROPERTY_NOT_FOUND); testCode(AAFRESULT_CLASS_NOT_FOUND); testCode(AAFRESULT_PROPERTY_DUPLICATE); testCode(AAFRESULT_ELEMENT_NOT_PRESENT); testCode(AAFRESULT_ELEMENT_NOT_OBJECT); testCode(AAFRESULT_PROP_ALREADY_PRESENT); /* MOB Error Codes */ testCode(AAFRESULT_NOT_SOURCE_CLIP); testCode(AAFRESULT_FILL_FOUND); testCode(AAFRESULT_BAD_LENGTH); testCode(AAFRESULT_BADRATE); testCode(AAFRESULT_INVALID_ROUNDING); testCode(AAFRESULT_TIMECODE_NOT_FOUND); testCode(AAFRESULT_NO_TIMECODE); testCode(AAFRESULT_INVALID_TIMECODE); testCode(AAFRESULT_SLOT_NOT_FOUND); testCode(AAFRESULT_BAD_SLOTLENGTH); testCode(AAFRESULT_MISSING_TRACKID); testCode(AAFRESULT_SLOT_EXISTS); testCode(AAFRESULT_MOB_NOT_FOUND); testCode(AAFRESULT_NO_MORE_MOBS); testCode(AAFRESULT_DUPLICATE_MOBID); testCode(AAFRESULT_MISSING_MOBID); testCode(AAFRESULT_EFFECTDEF_EXIST); testCode(AAFRESULT_INVALID_EFFECTDEF); testCode(AAFRESULT_INVALID_EFFECT); testCode(AAFRESULT_INVALID_EFFECTARG); testCode(AAFRESULT_INVALID_CVAL); testCode(AAFRESULT_RENDER_NOT_FOUND); testCode(AAFRESULT_BAD_ITHDL); testCode(AAFRESULT_NO_MORE_OBJECTS); testCode(AAFRESULT_ITER_WRONG_TYPE); testCode(AAFRESULT_INVALID_SEARCH_CRIT); testCode(AAFRESULT_INTERNAL_ITERATOR); testCode(AAFRESULT_NULL_MATCHFUNC); testCode(AAFRESULT_NULL_CALLBACKFUNC); testCode(AAFRESULT_TRAVERSAL_NOT_POSS); testCode(AAFRESULT_INVALID_TRAN_EFFECT); testCode(AAFRESULT_ADJACENT_TRAN); testCode(AAFRESULT_LEADING_TRAN); testCode(AAFRESULT_INSUFF_TRAN_MATERIAL); testCode(AAFRESULT_PULLDOWN_DIRECTION); testCode(AAFRESULT_PULLDOWN_FUNC); testCode(AAFRESULT_PULLDOWN_KIND); testCode(AAFRESULT_BAD_SRCH_ITER); testCode(AAFRESULT_NOT_COMPOSITION); testCode(AAFRESULT_NOT_A_TRACK); testCode(AAFRESULT_PARSE_EFFECT_AMBIGUOUS); testCode(AAFRESULT_NO_ESSENCE_DESC); testCode(AAFRESULT_TAPE_DESC_ONLY); testCode(AAFRESULT_FILM_DESC_ONLY); testCode(AAFRESULT_UNKNOWN_PARAMETER_CLASS); testCode(AAFRESULT_PARAMETER_NOT_FOUND); testCode(AAFRESULT_SEGMENT_NOT_FOUND); testCode(AAFRESULT_ESSENCE_NOT_FOUND); testCode(AAFRESULT_EVENT_SEMANTICS); /* SIMPLE COMPOSITION Error Codes */ testCode(AAFRESULT_BAD_STRACKHDL); testCode(AAFRESULT_STRACK_APPEND_ILLEGAL); /* Object Management Related Error Codes */ testCode(AAFRESULT_OBJECT_ALREADY_IN_FILE); testCode(AAFRESULT_OBJECT_NOT_IN_FILE); testCode(AAFRESULT_OBJECT_ALREADY_ATTACHED); testCode(AAFRESULT_OBJECT_NOT_ATTACHED); testCode(AAFRESULT_OBJECT_ALREADY_PERSISTENT); testCode(AAFRESULT_OBJECT_NOT_PERSISTENT); /* File kind/file encoding Error Codes */ testCode(AAFRESULT_FILEKIND_NOT_REGISTERED); /* GENERIC Error Codes */ testCode(AAFRESULT_NOMEMORY); testCode(AAFRESULT_OFFSET_SIZE); testCode(AAFRESULT_INTERNAL_NEG64); testCode(AAFRESULT_OVERFLOW64); testCode(AAFRESULT_NOT_IN_CURRENT_VERSION); testCode(AAFRESULT_NULL_PARAM); testCode(AAFRESULT_ZERO_DIVIDE); testCode(AAFRESULT_ALREADY_INITIALIZED); testCode(AAFRESULT_NOT_INITIALIZED); testCode(AAFRESULT_INTERNAL_ERROR); testCode(AAFRESULT_DATA_SIZE); testCode(AAFRESULT_ILLEGAL_VALUE); testCode(AAFRESULT_INVALID_TRANSPARENCY); testCode(AAFRESULT_INVALID_PARAM); testCode(AAFRESULT_INVALID_ENUM_VALUE); /* SEMANTIC CHECKING Error Codes */ testCode(AAFRESULT_REQUIRED_POSITIVE); testCode(AAFRESULT_INVALID_TRACKKIND); testCode(AAFRESULT_INVALID_EDGETYPE); testCode(AAFRESULT_INVALID_FILMTYPE); testCode(AAFRESULT_INVALID_MOBTYPE); testCode(AAFRESULT_INVALID_TAPECASETYPE); testCode(AAFRESULT_INVALID_VIDEOSIGNALTYPE); testCode(AAFRESULT_INVALID_TAPEFORMATTYPE); testCode(AAFRESULT_INVALID_EDITHINT); testCode(AAFRESULT_INVALID_INTERPKIND); testCode(AAFRESULT_INVALID_TRACK_REF); testCode(AAFRESULT_INVALID_OBJ); testCode(AAFRESULT_BAD_VIRTUAL_CREATE); testCode(AAFRESULT_INVALID_CLASS_ID); testCode(AAFRESULT_OBJECT_SEMANTIC); testCode(AAFRESULT_DATA_IN_SEMANTIC); testCode(AAFRESULT_DATA_OUT_SEMANTIC); testCode(AAFRESULT_TYPE_SEMANTIC); testCode(AAFRESULT_INVALID_ATTRIBUTEKIND); testCode(AAFRESULT_DATA_MDES_DISAGREE); testCode(AAFRESULT_CODEC_SEMANTIC_WARN); testCode(AAFRESULT_INVALID_BOOLTYPE); /* INTERNAL Error Codes */ testCode(AAFRESULT_TABLE_DUP_KEY); testCode(AAFRESULT_TABLE_MISSING_COMPARE); testCode(AAFRESULT_TABLE_BAD_HDL); testCode(AAFRESULT_TABLE_BAD_ITER); testCode(AAFRESULT_PROPID_MATCH); testCode(AAFRESULT_INTERNAL_DIVIDE); testCode(AAFRESULT_ABSTRACT_CLASS); testCode(AAFRESULT_WRONG_SIZE); testCode(AAFRESULT_INCONSISTENCY); /* INTERNAL Error Codes - programming errors */ testCode(AAFRESULT_ASSERTION_VIOLATION); testCode(AAFRESULT_UNEXPECTED_EXCEPTION); testCode(AAFRESULT_UNHANDLED_EXCEPTION); /* Testing Error Codes */ testCode(AAFRESULT_TEST_FAILED); testCode(AAFRESULT_TEST_PARTIAL_SUCCESS); /* Property access error codes */ testCode(AAFRESULT_BAD_SIZE); testCode(AAFRESULT_NOT_REGISTERED); testCode(AAFRESULT_NOT_EXTENDABLE); testCode(AAFRESULT_ALREADY_UNIQUELY_IDENTIFIED); testCode(AAFRESULT_DEFAULT_ALREADY_USED); /* Object extension error codes */ testCode(AAFRESULT_EXTENSION_NOT_FOUND); testCode(AAFRESULT_EXTENSION_ALREADY_INITIALIZED); testCode(AAFRESULT_PLUGIN_NOT_REGISTERED); testCode(AAFRESULT_PLUGIN_ALREADY_REGISTERED); testCode(AAFRESULT_PLUGIN_CIRCULAR_REFERENCE); testCode(AAFRESULT_PLUGIN_INVALID_REFERENCE_COUNT); /* DLL/Shared Library runtime error codes */ testCode(AAFRESULT_DLL_LOAD_FAILED); testCode(AAFRESULT_DLL_SYMBOL_NOT_FOUND); /* Result code -> text error codes */ testCode(AAFRESULT_RESULT_NOT_AAF); testCode(AAFRESULT_RESULT_NOT_RECOGNIZED); } void negativeTests() { AAFRESULT x = AAFRESULT_BADOPEN; HRESULT y; y = AAFResultToTextBufLen(x, 0); if (y != AAFRESULT_NULL_PARAM) { std::wcout << "*** Fail." << std::endl; } y = AAFResultToText(x, 0, 99); if (y != AAFRESULT_NULL_PARAM) { std::wcout << "*** Fail." << std::endl; } wchar_t tooSmall[1]; aafUInt32 len = sizeof(tooSmall) * sizeof(wchar_t); y = AAFResultToText(x, tooSmall, len); if (y != AAFRESULT_SMALLBUF) { std::wcout << "*** Fail." << std::endl; } /* AAFRESULT_NOT_IMPLEMENTED is not an AAF error code - it's a redefinition of E_NOTIMPL from facility ITF */ y = AAFResultToTextBufLen(AAFRESULT_NOT_IMPLEMENTED, &len); if (y != AAFRESULT_RESULT_NOT_AAF) { std::wcout << "*** Fail." << std::endl; } /* 0x8012ffff is unallocated */ y = AAFResultToTextBufLen(0x8012ffff, &len); if (y != AAFRESULT_RESULT_NOT_RECOGNIZED) { std::wcout << "*** Fail." << std::endl; } /* AAFRESULT_SUCCESS is not an AAF error code - it's a redefinition of S_OK */ y = AAFResultToTextBufLen(AAFRESULT_SUCCESS, &len); if (y != AAFRESULT_RESULT_NOT_AAF) { std::wcout << "*** Fail." << std::endl; } } int main() { positiveTests(); negativeTests(); }
35.056206
73
0.783753
[ "object" ]
1ac511d5d018f4be397ca5e911e09716043f5dec
7,951
cpp
C++
Library/src/showpage/OptionHandler.cpp
jplflyer/BeatPatterns
6d6b7e5b9bdab9c6636444f963aef324ebf03f70
[ "MIT" ]
1
2020-01-26T23:26:34.000Z
2020-01-26T23:26:34.000Z
Library/src/showpage/OptionHandler.cpp
jplflyer/BeatPatterns
6d6b7e5b9bdab9c6636444f963aef324ebf03f70
[ "MIT" ]
null
null
null
Library/src/showpage/OptionHandler.cpp
jplflyer/BeatPatterns
6d6b7e5b9bdab9c6636444f963aef324ebf03f70
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <algorithm> #include <cctype> #include "OptionHandler.h" using namespace std; /** * Parse the command line. Returns true if clean, false if bad args or help was provided. */ bool OptionHandler::handleOptions(int argc, const char * const *argv, Argument *arguments, HelpFunction helpFunction) { ArgumentVector vec; vec.addAll(arguments); return handleOptions(argc, argv, vec, helpFunction); } /** * Parse the command line. Returns true if clean, false if bad args or help was provided. */ bool OptionHandler::handleOptions(int argc, const char * const *argv, ArgumentVector & vec, HelpFunction helpFunction) { bool retVal = true; if (!helpFunction && vec.anyHaveHelpText() && (vec.searchForLongName("help") == nullptr) ) { char helpShortCode = (vec.searchForShortCode('h') == nullptr) ? '?' : 0; vec.push_back( new Argument ("help", no_argument, helpShortCode, [&](const char *) { vec.autoHelp(); retVal = false; }, "", "Provide this help" ) ); } unsigned int count = static_cast<unsigned int>(vec.size()); string shortArgs; option * options = vec.getOptions(shortArgs); int optionIndex = -1; int opt; const char *shortArgsPtr = shortArgs.c_str(); while ( (opt = getopt_long (argc, const_cast<char **>(argv), shortArgsPtr, options, &optionIndex)) != -1) { // This happens with short options. if (optionIndex < 0) { for (unsigned int index = 0; index < count; ++index) { if (vec.at(index)->val == opt) { optionIndex = static_cast<int>(index); break; } } } if (optionIndex < 0) { if (helpFunction != nullptr) { helpFunction(); } retVal = false; break; } vec.at(static_cast<unsigned int>(optionIndex))->callbackFunction(optarg); optionIndex = -1; } return retVal; } //====================================================================== // Argument. //====================================================================== /** * Constructor. */ OptionHandler::Argument::Argument() { } /** * Constructor. */ OptionHandler::Argument::Argument( const char *_name ) { if (_name != nullptr) { name = _name; } } /** * Complicated constructor. */ OptionHandler::Argument::Argument( const char *_name, int _has_arg, CallbackFunction cb, const string & argText, const string & help ) : has_arg(_has_arg), callbackFunction(cb), argumentText(argText), helpText(help) { if (_name != nullptr) { name = _name; } } /** * Complicated constructor. */ OptionHandler::Argument::Argument( const char *_name, int _has_arg, char _val, CallbackFunction cb, const string & argText, const string & help ) : has_arg(_has_arg), val(_val), callbackFunction(cb), argumentText(argText), helpText(help) { if (_name != nullptr) { name = _name; } } /** * Copy constructor. */ OptionHandler::Argument::Argument(const Argument &arg) : name ( arg.name ), has_arg ( arg.has_arg ), val ( arg.val ), callbackFunction ( arg.callbackFunction ), argumentText ( arg.argumentText ), helpText ( arg.helpText ) { } string OptionHandler::Argument::argumentForHelp() const { string retVal; if (name.length() > 0) { retVal = string("--") + name; if (isprint(val)) { retVal += string(" (-") + val + string(")"); } } else if (isprint(val)) { retVal = string("-") + val; } if (argumentText.length() > 0) { retVal += string(" ") + argumentText; } return retVal; } /** * For auto-generated help, we're going to write something like: * * --foo (-f) fooValue * * Return the string length. */ int OptionHandler::Argument::argumentLength() const { return static_cast<int>(argumentForHelp().length()); } string OptionHandler::Argument::paddedArgument(int length) const { string str = argumentForHelp(); if (str.length() < length) { str += string(length - str.length(), ' '); } return str; } //====================================================================== // Argument Vector. //====================================================================== /** * Vector constructor. */ OptionHandler::ArgumentVector::ArgumentVector() : options(nullptr), optionsCount(0) { } OptionHandler::ArgumentVector::~ArgumentVector() { if (options != nullptr) { delete[] options; options = nullptr; optionsCount = 0; } } /** * Append these. */ void OptionHandler::ArgumentVector::addAll(Argument *arguments) { unsigned long count = 0; while(arguments[count].name.length() > 0 || arguments[count].val != 0) { ++count; } for (unsigned long index = 0; index < count; ++index) { Argument &arg = arguments[index]; Argument * newArg = new Argument(arg); push_back(newArg); } } /** * Append. */ void OptionHandler::ArgumentVector::addAll(ArgumentVector &vec) { for (Argument *arg: vec) { Argument * newArg = new Argument(*arg); push_back(newArg); } } /** * We use getopt_long to actually do the parsing. He assumes an array of struct option. We produce one. * Note that if you fiddle with our contents without changing our size, we sort of screw up, so if you call * this method more than once, and you make changes between, it might be a problem. */ struct option * OptionHandler::ArgumentVector::getOptions(std::string &shortArgsReturned) { if (options == nullptr || optionsCount != size()) { optionsCount = size() + 1; options = new option[optionsCount]; shortArgs = ""; int index = 0; for (Argument *arg: *this) { option &opt = options[index++]; opt.name = arg->name.c_str(); opt.has_arg = arg->has_arg; opt.flag = nullptr; opt.val = arg->val; if (arg->val != 0) { shortArgs += arg->val; if (opt.has_arg != no_argument) { shortArgs += ":"; } } } { // Do the last one. option &opt = options[index]; opt.name = nullptr; opt.has_arg = 0; opt.flag = nullptr; opt.val = 0; } } shortArgsReturned = shortArgs; return options; } OptionHandler::Argument * OptionHandler::ArgumentVector::searchForLongName(const std::string &value) { Argument * retVal = nullptr; for (auto it = begin(); it != end(); ++it) { Argument *arg = *it; if (arg->name == value) { retVal = arg; break; } } return retVal; } OptionHandler::Argument * OptionHandler::ArgumentVector::searchForShortCode(char code) { Argument * retVal = nullptr; for (auto it = begin(); it != end(); ++it) { Argument *arg = *it; if (arg->val == code) { retVal = arg; break; } } return retVal; } bool OptionHandler::ArgumentVector::anyHaveHelpText() const { bool retVal = false; for (auto it = begin(); it != end(); ++it) { Argument *arg = *it; if (arg->argumentText.length() > 0 || arg->helpText.length() > 0) { retVal = arg; break; } } return retVal; } void OptionHandler::ArgumentVector::autoHelp() const { int longest = 0; for (auto it = cbegin(); it != cend(); ++it) { Argument * arg = *it; longest = max(longest, arg->argumentLength()); } for (auto it = cbegin(); it != cend(); ++it) { Argument * arg = *it; cout << arg->paddedArgument(longest) << " -- " << arg->helpText << endl; } }
25.082019
156
0.555528
[ "vector" ]
1ad396c5d6dcb7ff7598e8bf140a277f8c4f4750
1,542
cc
C++
smart_pointers/04-pointer.cc
aakbar5/handy-cplusplus
fd8ae187811f1ff9a6d19909202ed31564c4e384
[ "MIT" ]
null
null
null
smart_pointers/04-pointer.cc
aakbar5/handy-cplusplus
fd8ae187811f1ff9a6d19909202ed31564c4e384
[ "MIT" ]
null
null
null
smart_pointers/04-pointer.cc
aakbar5/handy-cplusplus
fd8ae187811f1ff9a6d19909202ed31564c4e384
[ "MIT" ]
null
null
null
// // Program // This program simply creates weak pointer. // - You can only create a std::weak_ptr out of a // std::shared_ptr or another std::weak_ptr. // // Compile // g++ -std=c++17 -o 04-pointer 04-pointer.cc // // Execution // ./04-pointer // #include <iostream> #include <memory> // // Entry function // int main() { std::cout << "--- std::weak_ptr ---" << "\n"; // Handling of Test object via shared pointer std::cout << "--- simple shared_pointer ---" << "\n"; { std::shared_ptr<unsigned int> sptr = std::make_shared<unsigned int>(786); std::cout << "sptr @ use_count: " << sptr.use_count() << "\n"; // Use count should be 1 std::cout << "sptr @ value: " << *sptr << "\n"; { std::weak_ptr<unsigned int> wptr(sptr); std::cout << "wptr @ use_count: " << sptr.use_count() << "\n"; // Use count should be 1 auto t = wptr.lock(); std::cout << "wptr > sptr @ value: " << *t << "\n"; std::cout << "wptr @ use_count: " << wptr.use_count() << "\n"; // Use count should be 2 std::cout << "sptr @ use_count: " << sptr.use_count() << "\n"; // Use count should be 2 *t = 100; std::cout << "wptr > sptr @ value: " << *t << "\n"; } std::cout << "sptr @ use_count: " << sptr.use_count() << "\n"; // Use count should be 1 std::cout << "sptr @ value: " << *sptr << "\n"; // dtor should be called } std::cout << "Good bye!" << "\n"; return 0; }
28.555556
99
0.503891
[ "object" ]
1ae50d701f9ae1c0079ce989f23b0d6b9563ed5c
471
cpp
C++
cppLearn/test.cpp
adammorley/cpp
ff8682843f64f808b51f45b6e9530b0755455f27
[ "Apache-2.0" ]
null
null
null
cppLearn/test.cpp
adammorley/cpp
ff8682843f64f808b51f45b6e9530b0755455f27
[ "Apache-2.0" ]
null
null
null
cppLearn/test.cpp
adammorley/cpp
ff8682843f64f808b51f45b6e9530b0755455f27
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> #include <map> int main() { std::vector<int> values = {100, 50, 33}; std::vector<int> weights = {10, 25, 10}; std::map<double, int> r_index; for (int i = 0; i < values.size(); i++) { double r = (double) values[i] / weights[i]; r_index[r] = i; } for (auto it = r_index.rbegin(); it != r_index.rend(); it++) { std::cout << it->first << " " << it->second << '\n' << std::endl; } return 0; }
22.428571
68
0.56051
[ "vector" ]
1aeb4dc481ab0c7d83e28af056d7e12d2de59115
4,903
cxx
C++
nvbench/named_values.cxx
S-o-T/nvbench
a72f248af6323915419e03c0d7d56a35c9b4819a
[ "Apache-2.0" ]
157
2021-04-14T19:35:08.000Z
2022-03-29T14:35:31.000Z
nvbench/named_values.cxx
S-o-T/nvbench
a72f248af6323915419e03c0d7d56a35c9b4819a
[ "Apache-2.0" ]
44
2021-04-21T22:54:13.000Z
2022-02-18T21:54:46.000Z
nvbench/named_values.cxx
S-o-T/nvbench
a72f248af6323915419e03c0d7d56a35c9b4819a
[ "Apache-2.0" ]
21
2021-04-14T19:36:27.000Z
2022-03-14T22:11:17.000Z
/* * Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 with the LLVM exception * (the "License"); you may not use this file except in compliance with * the License. * * You may obtain a copy of the License at * * http://llvm.org/foundation/relicensing/LICENSE.txt * * 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 <nvbench/named_values.cuh> #include <nvbench/config.cuh> #include <nvbench/detail/throw.cuh> #include <fmt/format.h> #include <algorithm> #include <iterator> #include <stdexcept> #include <type_traits> namespace nvbench { void named_values::append(const named_values &other) { m_storage.insert(m_storage.end(), other.m_storage.cbegin(), other.m_storage.cend()); } void named_values::clear() { m_storage.clear(); } std::size_t named_values::get_size() const { return m_storage.size(); } std::vector<std::string> named_values::get_names() const { std::vector<std::string> names; names.reserve(m_storage.size()); std::transform(m_storage.cbegin(), m_storage.cend(), std::back_inserter(names), [](const auto &val) { return val.name; }); return names; } bool named_values::has_value(const std::string &name) const { auto iter = std::find_if(m_storage.cbegin(), m_storage.cend(), [&name](const auto &val) { return val.name == name; }); return iter != m_storage.cend(); } const named_values::value_type & named_values::get_value(const std::string &name) const { auto iter = std::find_if(m_storage.cbegin(), m_storage.cend(), [&name](const auto &val) { return val.name == name; }); if (iter == m_storage.cend()) { NVBENCH_THROW(std::runtime_error, "No value with name '{}'.", name); } return iter->value; } named_values::type named_values::get_type(const std::string &name) const { return std::visit( [&name]([[maybe_unused]] auto &&arg) { using T = std::decay_t<decltype(arg)>; if constexpr (std::is_same_v<T, nvbench::int64_t>) { return nvbench::named_values::type::int64; } else if constexpr (std::is_same_v<T, nvbench::float64_t>) { return nvbench::named_values::type::float64; } else if constexpr (std::is_same_v<T, std::string>) { return nvbench::named_values::type::string; } // warning C4702: unreachable code // This is a future-proofing check, it'll be reachable if something breaks NVBENCH_MSVC_PUSH_DISABLE_WARNING(4702) NVBENCH_THROW(std::runtime_error, "Unknown variant type for entry '{}'.", name); }, this->get_value(name)); NVBENCH_MSVC_POP_WARNING() } nvbench::int64_t named_values::get_int64(const std::string &name) const try { return std::get<nvbench::int64_t>(this->get_value(name)); } catch (std::exception &err) { NVBENCH_THROW(std::runtime_error, "Error looking up int64 value `{}`:\n{}", name, err.what()); } nvbench::float64_t named_values::get_float64(const std::string &name) const try { return std::get<nvbench::float64_t>(this->get_value(name)); } catch (std::exception &err) { NVBENCH_THROW(std::runtime_error, "Error looking up float64 value `{}`:\n{}", name, err.what()); } const std::string &named_values::get_string(const std::string &name) const try { return std::get<std::string>(this->get_value(name)); } catch (std::exception &err) { NVBENCH_THROW(std::runtime_error, "Error looking up string value `{}`:\n{}", name, err.what()); } void named_values::set_int64(std::string name, nvbench::int64_t value) { m_storage.push_back({std::move(name), value_type{value}}); } void named_values::set_float64(std::string name, nvbench::float64_t value) { m_storage.push_back({std::move(name), value_type{value}}); } void named_values::set_string(std::string name, std::string value) { m_storage.push_back({std::move(name), value_type{std::move(value)}}); } void named_values::set_value(std::string name, named_values::value_type value) { m_storage.push_back({std::move(name), std::move(value)}); } void named_values::remove_value(const std::string &name) { auto iter = std::find_if(m_storage.begin(), m_storage.end(), [&name](const auto &val) { return val.name == name; }); if (iter != m_storage.end()) { m_storage.erase(iter); } } } // namespace nvbench
27.391061
80
0.643076
[ "vector", "transform" ]
8c1b8e4631015af708e0cf80f2a5d3e486434302
27,055
cc
C++
Agent.cc
c-trinh/wumpus-ai-agent
86145c19fb60d77eb5139b514dd1d42817ce11b5
[ "MIT" ]
null
null
null
Agent.cc
c-trinh/wumpus-ai-agent
86145c19fb60d77eb5139b514dd1d42817ce11b5
[ "MIT" ]
null
null
null
Agent.cc
c-trinh/wumpus-ai-agent
86145c19fb60d77eb5139b514dd1d42817ce11b5
[ "MIT" ]
null
null
null
/* Cong Trinh * Artificial Intelligence * 11/9/19 */ // Agent.cc #include <iostream> #include <iomanip> #include <vector> #include "Agent.h" #include "Action.h" #include "Location.h" #include "Orientation.h" #include <algorithm> using namespace std; Agent::Agent() { firstTry = true; } Agent::~Agent() { } void Agent::Initialize() { cout << setprecision(2) << fixed; // Sets decimal output by 2 places worldState.agentOrientation = RIGHT; worldState.agentHasArrow = true; worldState.agentHasGold = false; actionList.clear(); previousAction = CLIMB; // dummy action to start worldState.worldSize = 5; // Is given all maps will be 5x5 if (firstTry) { worldState.goldLocation = Location(0, 0); // unknown //worldState.worldSize = 0; // unknown pathToGold.push_back(Location(1, 1)); // path starts in (1,1) /// Initialize 5x5 Prob Locations (Default: 0.20) for (int x = 0; x < 5; x++) for (int y = 0; y < 5; y++) prob_pit[x][y] = 0.20; } else { if (worldState.goldLocation == Location(0, 0)) { // Didn't find gold on first try (should never happen, but just in case) pathToGold.clear(); pathToGold.push_back(Location(1, 1)); } else { AddActionsFromPath(true); // forward through path from (1,1) to gold location } if (worldState.agentLocation.X != 1 && worldState.agentLocation.Y != 1) { SetGoForward(worldState.agentLocation); Pit(worldState.agentLocation.X, worldState.agentLocation.Y, 1.00); cout << "DIED - MARKING (" << worldState.agentLocation.X - 1 << ", " << worldState.agentLocation.Y - 1 << ") AS A PIT." << endl; cout << "(" << worldState.agentLocation.X - 1 << ", " << worldState.agentLocation.Y - 1 << ") = " << prob_pit[worldState.agentLocation.X - 1][worldState.agentLocation.Y - 1] << endl; } } worldState.agentLocation = Location(1, 1); } Action Agent::Process(Percept &percept) { UpdateState(percept); //PrintProbPit(); // debug ComputeAllPits(percept); if (actionList.empty()) { // Reverse back to Goal if (percept.Glitter) { actionList.push_back(GRAB); AddActionsFromPath(false); // reverse path from (1,1) to gold location } else if (worldState.agentHasGold && (worldState.agentLocation == Location(1, 1))) { actionList.push_back(CLIMB); } else { actionList.push_back(ChooseAction(percept)); } } //ComputeAllPits(percept); Action action = actionList.front(); actionList.pop_front(); previousAction = action; cin.get(); // Pause return action; } void Agent::GameOver(int score) { firstTry = false; } void Agent::UpdateState(Percept &percept) { int orientationInt = (int)worldState.agentOrientation; switch (previousAction) { case GOFORWARD: if (percept.Bump) { // Check if we can determine world size if (worldState.agentOrientation == RIGHT) { worldState.worldSize = worldState.agentLocation.X; } if (worldState.agentOrientation == UP) { worldState.worldSize = worldState.agentLocation.Y; } if (worldState.worldSize > 0) FilterSafeLocations(); } else { Location forwardLocation; SetGoForward(forwardLocation); worldState.agentLocation = forwardLocation; if (worldState.goldLocation == Location(0, 0)) { // If haven't found gold yet, add this location to the pathToGold AddToPath(worldState.agentLocation); } } break; case TURNLEFT: worldState.agentOrientation = (Orientation)((orientationInt + 1) % 4); break; case TURNRIGHT: orientationInt--; if (orientationInt < 0) orientationInt = 3; worldState.agentOrientation = (Orientation)orientationInt; break; case GRAB: worldState.agentHasGold = true; // Only GRAB when there's gold worldState.goldLocation = worldState.agentLocation; break; case SHOOT: worldState.agentHasArrow = false; // The only situation where we shoot is if we start out in (1,1) // facing RIGHT, perceive a stench, and don't know the wumpus location. // In this case, a SCREAM percept means the wumpus is in (2,1) (and dead), // or if no SCREAM, then the wumpus is in (1,2) (and still alive). possibleWumpusLocations.clear(); if (percept.Scream) { possibleWumpusLocations.push_back(Location(2, 1)); } else { possibleWumpusLocations.push_back(Location(1, 2)); } case CLIMB: break; } // Update visited locations, safe locations, stench locations, clear locations, // and possible wumpus locations. AddNewLocation(visitedLocations, worldState.agentLocation); AddNewLocation(safeLocations, worldState.agentLocation); if (percept.Stench) { AddNewLocation(stenchLocations, worldState.agentLocation); } else { AddNewLocation(clearLocations, worldState.agentLocation); AddAdjacentLocations(safeLocations, worldState.agentLocation); } if (possibleWumpusLocations.size() != 1) { UpdatePossibleWumpusLocations(); } /// Precaution Removal list<Location> temp; for (Location loc : safeLocations) { bool is_wumpus = (possibleWumpusLocations.size() == 1) && (loc.X == possibleWumpusLocations.front().X) && (loc.Y == possibleWumpusLocations.front().Y); if (prob_pit[loc.X - 1][loc.Y - 1] >= 0.5 || is_wumpus) { temp.push_back(loc); } } for (Location loc : temp) { if (prob_pit[loc.X - 1][loc.Y - 1] >= 0.5) { RemoveLoc(safeLocations, loc); cout << "REMOVING [(" << loc.X << ", " << loc.Y << ") = " << prob_pit[loc.X - 1][loc.Y - 1] << "] FROM SAFE_LOC." << endl; } } Output(); } /* * Update possible wumpus locations based on the current set of stench locations * and clear locations. */ void Agent::UpdatePossibleWumpusLocations() { list<Location> tmpLocations; list<Location> adjacentLocations; possibleWumpusLocations.clear(); Location location1, location2; list<Location>::iterator itr1, itr2; // Determine possible wumpus locations consistent with available stench information for (itr1 = stenchLocations.begin(); itr1 != stenchLocations.end(); ++itr1) { location1 = *itr1; // Build list of adjacent locations to this stench location adjacentLocations.clear(); AddAdjacentLocations(adjacentLocations, location1); if (possibleWumpusLocations.empty()) { // Must be first stench location in list, so add all adjacent locations possibleWumpusLocations = adjacentLocations; } else { // Eliminate possible wumpus locations not adjacent to this stench location tmpLocations = possibleWumpusLocations; possibleWumpusLocations.clear(); for (itr2 = tmpLocations.begin(); itr2 != tmpLocations.end(); ++itr2) { location2 = *itr2; if (LocationInList(adjacentLocations, location2)) { possibleWumpusLocations.push_back(location2); } } } } // Eliminate possible wumpus locations adjacent to a clear location for (itr1 = clearLocations.begin(); itr1 != clearLocations.end(); ++itr1) { location1 = *itr1; // Build list of adjacent locations to this clear location adjacentLocations.clear(); AddAdjacentLocations(adjacentLocations, location1); tmpLocations = possibleWumpusLocations; possibleWumpusLocations.clear(); for (itr2 = tmpLocations.begin(); itr2 != tmpLocations.end(); ++itr2) { location2 = *itr2; if (!LocationInList(adjacentLocations, location2)) { possibleWumpusLocations.push_back(location2); } } } } /* * Sets the given location to the location resulting in a successful GOFORWARD. */ void Agent::SetGoLeft(Location &location) { location = worldState.agentLocation; switch (worldState.agentOrientation) { case RIGHT: location.Y++; break; case UP: location.X--; break; case LEFT: location.Y--; break; case DOWN: location.X++; break; } } void Agent::SetGoRight(Location &location) { location = worldState.agentLocation; switch (worldState.agentOrientation) { case RIGHT: location.Y--; break; case UP: location.X++; break; case LEFT: location.Y++; break; case DOWN: location.X--; break; } } void Agent::SetGoForward(Location &location) { location = worldState.agentLocation; switch (worldState.agentOrientation) { case RIGHT: location.X++; break; case UP: location.Y++; break; case LEFT: location.X--; break; case DOWN: location.Y--; break; } } /* * Add given location to agent's pathToGold. But if this location is already on the * pathToGold, then remove everything after the first occurrence of this location. */ void Agent::AddToPath(Location &location) { list<Location>::iterator itr = find(pathToGold.begin(), pathToGold.end(), location); if (itr != pathToGold.end()) { // Location already on path (i.e., a loop), so remove everything after this element ++itr; pathToGold.erase(itr, pathToGold.end()); } else { pathToGold.push_back(location); } } /* * Choose and return an action when we haven't found the gold yet. * Handle special case where we start out in (1,1), perceive a stench, and * don't know the wumpus location. In this case, SHOOT. Orientation will be * RIGHT, so if SCREAM, then wumpus in (2,1); otherwise in (1,2). This is * handled in the UpdateState method. */ Action Agent::ChooseAction(Percept &percept) { Action action; Location forwardLocation; SetGoForward(forwardLocation); if (percept.Stench && (worldState.agentLocation == Location(1, 1)) && (possibleWumpusLocations.size() != 1)) { action = SHOOT; } else if (LocationInList(safeLocations, forwardLocation) && (!LocationInList(visitedLocations, forwardLocation))) { // If happen to be facing safe unvisited location, then move there action = GOFORWARD; } else { list<Location> turn_list; Location l_loc, r_loc; SetGoLeft(l_loc); SetGoRight(r_loc); //cout << "-------- L_TURN = " << get_pit_prob(l_loc) << endl; //cout << "-------- R_TURN = " << get_pit_prob(r_loc) << endl; bool is_safe = LocationInList(possibleWumpusLocations, forwardLocation) || OutsideWorld(forwardLocation) || LocationInList(knownPitLoc, forwardLocation); if (get_pit_prob(l_loc) < get_pit_prob(r_loc) && is_safe) { actionList.push_back(TURNLEFT); actionList.push_back(GOFORWARD); //action = TURNLEFT; } else if (get_pit_prob(l_loc) > get_pit_prob(r_loc) && is_safe) { actionList.push_back(TURNRIGHT); actionList.push_back(GOFORWARD); //action = TURNRIGHT; } else { // Both values are same, turn around if (get_pit_prob(l_loc) < 0.5) { action = TURNLEFT; } else { actionList.push_back(TURNRIGHT); actionList.push_back(TURNRIGHT); actionList.push_back(GOFORWARD); } } /*else { // Choose randomly from GOFORWARD, TURNLEFT, and TURNRIGHT, but don't // GOFORWARD into a possible wumpus location or a wall if (is_safe)) { action = (Action)((rand() % 2) + 1); // TURNLEFT, TURNRIGHT } else { //action = (Action)(rand() % 3); // GOFORWARD, TURNLEFT, TURNRIGHT } }*/ } return action; } float Agent::get_pit_prob(Location &loc) { if (OutsideWorld(loc)) { return 2.00; // Error message to know if out of bounds } return prob_pit[loc.X - 1][loc.Y - 1]; } /* * Add a sequence of actions to actionList that moves the agent along the * pathToGold if forward=true, or the reverse if forward=false. Assumes at * least one location is on pathToGold. */ void Agent::AddActionsFromPath(bool forward) { list<Location> path = pathToGold; if (!forward) path.reverse(); Location currentLocation = worldState.agentLocation; Orientation currentOrientation = worldState.agentOrientation; list<Location>::iterator itr_loc = path.begin(); ++itr_loc; while (itr_loc != path.end()) { Location nextLocation = *itr_loc; Orientation nextOrientation; if (nextLocation.X > currentLocation.X) nextOrientation = RIGHT; if (nextLocation.X < currentLocation.X) nextOrientation = LEFT; if (nextLocation.Y > currentLocation.Y) nextOrientation = UP; if (nextLocation.Y < currentLocation.Y) nextOrientation = DOWN; // Find shortest turn sequence (assuming RIGHT=0, UP=1, LEFT=2, DOWN=3) int diff = ((int)currentOrientation) - ((int)nextOrientation); if ((diff == 1) || (diff == -3)) { actionList.push_back(TURNRIGHT); } else { if (diff != 0) actionList.push_back(TURNLEFT); if ((diff == 2) || (diff == -2)) actionList.push_back(TURNLEFT); } actionList.push_back(GOFORWARD); currentLocation = nextLocation; currentOrientation = nextOrientation; ++itr_loc; } } /* * Return true if given location is in given location list; otherwise, return false. */ bool Agent::LocationInList(list<Location> &locationList, const Location &location) { if (find(locationList.begin(), locationList.end(), location) != locationList.end()) { return true; } return false; } /* * Add location to given list, if not already present. */ void Agent::AddNewLocation(list<Location> &locationList, const Location &location) { if (!LocationInList(locationList, location)) { locationList.push_back(location); } } /* * Add locations that are adjacent to the given location to the given location list. * Doesn't add locations outside the left and bottom borders of the world, but might * add locations outside the top and right borders of the world, if we don't know the * world size. */ void Agent::AddAdjacentLocations(list<Location> &locationList, const Location &location) { int worldSize = worldState.worldSize; if ((worldSize == 0) || (location.Y < worldSize)) { AddNewLocation(locationList, Location(location.X, location.Y + 1)); // up } if ((worldSize == 0) || (location.X < worldSize)) { AddNewLocation(locationList, Location(location.X + 1, location.Y)); // right } if (location.X > 1) AddNewLocation(locationList, Location(location.X - 1, location.Y)); // left if (location.Y > 1) AddNewLocation(locationList, Location(location.X, location.Y - 1)); // down } /* * Return true if given location is outside known world. */ bool Agent::OutsideWorld(Location &location) { int worldSize = worldState.worldSize; if ((location.X < 1) || (location.Y < 1)) return true; if ((worldSize > 0) && ((location.X > worldSize) || (location.Y > worldSize))) return true; return false; } /* * Filters from safeLocations any locations that are outside the upper or right borders of the world. */ void Agent::FilterSafeLocations() { int worldSize = worldState.worldSize; list<Location> tmpLocations = safeLocations; safeLocations.clear(); for (list<Location>::iterator itr = tmpLocations.begin(); itr != tmpLocations.end(); ++itr) { Location location = *itr; if ((location.X < 1) || (location.Y < 1)) continue; if ((worldSize > 0) && ((location.X > worldSize) || (location.Y > worldSize))) { continue; } safeLocations.push_back(location); } } void Agent::Output() { list<Location>::iterator itr; Location location; cout << "World Size: " << worldState.worldSize << endl; cout << "Visited Locations:"; for (itr = visitedLocations.begin(); itr != visitedLocations.end(); ++itr) { location = *itr; cout << " (" << location.X << "," << location.Y << ")"; } cout << endl; cout << "Safe Locations:"; for (itr = safeLocations.begin(); itr != safeLocations.end(); ++itr) { location = *itr; cout << " (" << location.X << "," << location.Y << ")"; } cout << endl; cout << "Possible Wumpus Locations:"; for (itr = possibleWumpusLocations.begin(); itr != possibleWumpusLocations.end(); ++itr) { location = *itr; cout << " (" << location.X << "," << location.Y << ")"; } cout << endl; cout << "Gold Location: (" << worldState.goldLocation.X << "," << worldState.goldLocation.Y << ")\n"; cout << "Path To Gold:"; for (itr = pathToGold.begin(); itr != pathToGold.end(); ++itr) { location = *itr; cout << " (" << location.X << "," << location.Y << ")"; } cout << endl; cout << "Action List:"; for (list<Action>::iterator itr_a = actionList.begin(); itr_a != actionList.end(); ++itr_a) { cout << " "; PrintAction(*itr_a); } cout << endl; cout << endl; } // ---- /*foreach location (x,y) in frontier { P(Pitx,y=true) = 0.0 P(Pitx,y=false) = 0.0 frontier’ = frontier – {Pitx,y} foreach possible combination C of pit=true and pit=false in frontier’ { P(frontier’) = (0.2)T * (0.8)F, where T = number of pit=true in C, and F = number of pit=false in C if breeze is consistent with (C + Pitx,y=true) then P(Pitx,y=true) += P(frontier’) if breeze is consistent with (C + Pitx,y=false) then P(Pitx,y=false) += P(frontier’) } P(Pitx,y=true) *= 0.2 P(Pitx,y=false) *= 0.8 P(Pitx,y=true) = P(Pitx,y=true) / ( P(Pitx,y=true) + P(Pitx,y=false) ) // normalize }*/ void Agent::ComputeAllPits(Percept &percept) { // CP list<Location>::iterator itr, itr_f1, itr_f2; Location loc; /// All KNOWN Loc is 0.00 for (itr = visitedLocations.begin(); itr != visitedLocations.end(); ++itr) { loc = *itr; Pit(loc.X, loc.Y, 0.00); RemoveLoc(frontier, loc); } if (possibleWumpusLocations.size() == 1) { loc = *visitedLocations.begin(); Pit(loc.X, loc.Y, 0.00); } /// Find Frontier Nodes list<Location> adj_loc = FindFrontier(); if (knownPitLoc.size() != 0) { AdjList(knownPitLoc, worldState.agentLocation); /// TO-DO: Make } if (percept.Breeze && !AdjList(knownPitLoc, worldState.agentLocation)) { /// Adj. are possible pits for (Location loc : adj_loc) { if (!SearchListLoc(possiblePitLoc, loc) && prob_pit[loc.X - 1][loc.Y - 1] != 0 && prob_pit[loc.X - 1][loc.Y - 1] != 1) possiblePitLoc.push_back(loc); } ComputeFrontierSum(); } else if (!percept.Breeze && !AdjList(knownPitLoc, worldState.agentLocation)) { for (itr = adj_loc.begin(); itr != adj_loc.end(); ++itr) { loc = *itr; cout << "\n[~] COMPUTING Prob_Pit(" << loc.X << ", " << loc.Y << "):\n"; if (get_pit_prob(loc) != 1.00) { Pit(loc.X, loc.Y, 0.00); } cout << "\tprob_Pit(" << loc.X - 1 << ", " << loc.Y - 1 << ") = " << prob_pit[loc.X - 1][loc.Y - 1]; RemoveLoc(possiblePitLoc, loc); } cout << endl; if (possiblePitLoc.size() == 1 && !SearchListLoc(breezeList, possiblePitLoc.front())) { // Narrowed down which is Pit prob_pit[possiblePitLoc.front().X - 1][possiblePitLoc.front().Y - 1] = 1.00; pitList.push_back(possiblePitLoc.front()); possiblePitLoc.pop_back(); } } else { } list<Location> temp; for (Location loc : possiblePitLoc) { if (prob_pit[loc.X - 1][loc.Y - 1] == 0.00 || prob_pit[loc.X - 1][loc.Y - 1] == 1.00) { temp.push_back(loc); } } for (Location loc : temp) { RemoveLoc(possiblePitLoc, loc); } if (possiblePitLoc.size() == 1 && worldState.agentAlive) { loc = *possiblePitLoc.begin(); Pit(loc.X, loc.Y, 1.00); knownPitLoc.push_back(loc); possiblePitLoc.pop_back(); } /*cout << "\nPOSSIBLE PIT LOC:"; for (Location loc : possiblePitLoc) cout << "(" << loc.X << ", " << loc.Y << ") "; cout << endl;*/ /// Remove (<= 0.5) from SafeLocations for (Location loc : safeLocations) { bool is_wumpus = (possibleWumpusLocations.size() == 1) && (loc.X == possibleWumpusLocations.front().X) && (loc.Y == possibleWumpusLocations.front().Y); if (prob_pit[loc.X - 1][loc.Y - 1] >= 0.5 || is_wumpus) { temp.push_back(loc); } } for (Location loc : temp) { if (prob_pit[loc.X - 1][loc.Y - 1] >= 0.5) { RemoveLoc(safeLocations, loc); cout << "REMOVING [(" << loc.X << ", " << loc.Y << ") = " << prob_pit[loc.X - 1][loc.Y - 1] << "] FROM SAFE_LOC." << endl; } } PrintProbPit(); } float Agent::ComputeFrontierSum() { list<Location>::iterator itr, itr_f1, itr_f2; list<Location> adj_frontier; if (!SearchListLoc(breezeList, worldState.agentLocation)) breezeList.push_back(worldState.agentLocation); /// alpha P(p_x,y) SUM[Frontier] P(breeze|known, p_x,y, Frontier) P(Frontier) /// True = 0.2 / False = 0.8 list<Location> frontier_temp; float sum_frontier_t = 0.00, sum_frontier_f = 0.00; float pit_t = 0.00, pit_f = 0.00; for (itr = frontier.begin(); itr != frontier.end(); ++itr) { Location loc_f1 = *itr; cout << "[~] COMPUTING Prob_Pit(" << loc_f1.X << ", " << loc_f1.Y << "):\n"; frontier_temp.clear(); list<bool> adj_to_breeze; cout << "\tfrontier' ="; for (Location loc_f2 : frontier) { /// 1.) Creates Frontier' ["frontier_temp"] if (!(loc_f2.X == loc_f1.X && loc_f2.Y == loc_f1.Y)) { /// Exclude current Frontier node frontier_temp.push_back(loc_f2); cout << " (" << loc_f2.X << ", " << loc_f2.Y << ")"; } } cout << endl; /// 2.) Iterate Frontier' -> Compare pits TRUTH Tables int f_size = frontier_temp.size(); //list<bool> truth_table; if (!(prob_pit[loc_f1.X][loc_f1.Y] == 1.00 || prob_pit[loc_f1.X][loc_f1.Y] == 0.00)) { sum_frontier_t = FindTruthTable(f_size, frontier_temp, loc_f1, true); sum_frontier_f = FindTruthTable(f_size, frontier_temp, loc_f1, false); //cout << "-- SUM_FRONTIER_T = " << sum_frontier_t << endl; //cout << "-- SUM_FRONTIER_F = " << sum_frontier_f << endl; pit_t = (0.2) * sum_frontier_t; pit_f = (0.8) * sum_frontier_f; //cout << "-- PIT_T = " << pit_t << endl; //cout << "-- PIT_F = " << pit_f << endl; /// Normalize float normalize = 1 / (pit_t + pit_f); pit_t *= normalize; pit_f *= normalize; //cout << "[%]possiblePitLoc SIZE = " << possiblePitLoc.size() << endl; list<Location> adj_loc; bool visited_pit = false; AddAdjacentLocations(adj_loc, worldState.agentLocation); for (Location loc : adj_loc) { if (prob_pit[loc.X - 1][loc.Y - 1] == 1.00) { //possiblePitLoc.pop_back(); visited_pit = true; possiblePitLoc.clear(); } } bool is_pit = possiblePitLoc.size() == 1 && loc_f1.X == possiblePitLoc.front().X && loc_f1.Y == possiblePitLoc.front().Y; if (is_pit && !visited_pit && !SearchListLoc(breezeList, possiblePitLoc.front())) { // Narrowed down which is Pit prob_pit[loc_f1.X - 1][loc_f1.Y - 1] = 1.00; possiblePitLoc.pop_back(); } else if ((prob_pit[loc_f1.X - 1][loc_f1.Y - 1] != 0) && (prob_pit[loc_f1.X - 1][loc_f1.Y - 1] != 1) && !visited_pit) { if (get_pit_prob(loc_f1) == 0.00 || get_pit_prob(loc_f1) == 1.00) { pit_t = 0.00; } prob_pit[loc_f1.X - 1][loc_f1.Y - 1] = pit_t; } } cout << "\tprob_Pit(" << loc_f1.X << ", " << loc_f1.Y << "): " << pit_t << endl; } /// 3.) Normalize /// NEXT STEP: Make Agent move to areas with smallest percentage } float Agent::FindTruthTable(int n, list<Location> &L, Location &pit_x_y, bool is_xy_pit) { /// Note: 0 = T, 1 = F list<Location>::iterator itr; vector<vector<int>> output(n, vector<int>(1 << n)); float prob[2] = {0.2, 0.8}; float f_product, f_sum = 0; bool B_FLAG; unsigned result = 1U << (n - 1); /// Creates Truth Table for (unsigned col = 0; col < n; ++col, result >>= 1U) { for (unsigned row = result; row < (1U << n); row += (result * 2)) { fill_n(&output[col][row], result, 1); } } // These loops just print out the results, nothing more. for (unsigned x = 0; x < (1 << n); ++x) { //cout << endl; if (is_xy_pit == true) { B_FLAG = AdjBreeze(pit_x_y); //cout << "[!!!!!!!!] AdjBreeze(" << pit_x_y.X << ", " << pit_x_y.Y << "): "<< B_FLAG << " -- \n"; } else { B_FLAG = false; } itr = L.begin(); f_product = 1; for (unsigned y = 0; y < n; ++y) { /// Respective Location Location loc_f1 = *itr; //cout << "(" << loc_f1.X << ", " << loc_f1.Y << "):"; // debug (To view Truth Tables) // cout << " " << output[y][x] << " | "; /// Location Truth Value f_product *= prob[output[y][x]]; /// 1.) Compare all nodes with 0 to B, if any are ADJ -> Breeze Flag == TRUE if ((output[y][x] == 0) && AdjBreeze(loc_f1)) { B_FLAG = true; } //cout << B_FLAG; //cout << "[RESULT: " << (B_FLAG == true) << "" << is_xy_pit << "] "; /// 2.) if Breeze Flag is on, MULT all values together. Else, return 0 if ((y == n - 1) && (B_FLAG == true)) { f_sum += f_product; //cout << "... B_FLAG = " << B_FLAG << ", F_SUM = " << f_sum; // debug } ++itr; } //cout << "--------- SUM OF ALL: " << f_sum; //cout << endl; } return f_sum; /// TO-DO: Assign Y1 -> F1, Y2 -> F2 } bool Agent::AdjBreeze(Location &loc) { for (Location b : breezeList) if (Adjacent(b, loc)) return true; return false; } bool Agent::AdjList(list<Location> &L, Location &loc) { for (Location l : L) if (Adjacent(l, loc)) return true; return false; } list<Location> Agent::FindFrontier() { list<Location>::iterator itr; Location loc; /// Calculate Frontier Nodes (is in safeLocations) list<Location> adj_loc; adj_loc.clear(); AddAdjacentLocations(adj_loc, worldState.agentLocation); /*cout << "---- FRONTIER (Before): "; for (Location loc : adj_loc) cout << "(" << loc.X << ", " << loc.Y << ") "; cout << endl;*/ /// Find Frontier for (itr = adj_loc.begin(); itr != adj_loc.end(); ++itr) { loc = *itr; /// Add to Frontier if (prob_pit[loc.X - 1][loc.Y - 1] != 0.00 && !SearchListLoc(frontier, loc) && !SearchListLoc(visitedLocations, loc)) { frontier.push_back(loc); } } cout << "[%] FRONTIER: "; for (Location loc : frontier) cout << "(" << loc.X << ", " << loc.Y << ") "; cout << "\n"; return adj_loc; } bool Agent::RemoveLoc(list<Location> &list_loc, Location &loc) { list<Location>::iterator itr; for (itr = list_loc.begin(); itr != list_loc.end(); ++itr) { Location L = *itr; if ((L.X == loc.X) && (L.Y == loc.Y)) { //cout << "[!] - RemoveLoc() = TRUE / Removed (" << loc.X << ", " << loc.Y << ").\n"; // debug list_loc.erase(itr); return true; } } //cout << "[!] - RemoveLoc() = FALSE\n"; // debug return false; } void Agent::PrintProbPit() { cout << "\nP(Pit):\n"; for (int y = 4; y >= 0; --y) { for (int x = 0; x < 5; x++) { if (x + 1 == worldState.agentLocation.X && y + 1 == worldState.agentLocation.Y) // debug (To see current location) cout << "*"; else if ((possibleWumpusLocations.size() == 1) && (x == possibleWumpusLocations.front().X - 1) && (y == possibleWumpusLocations.front().Y - 1)) cout << "w"; else cout << " "; cout << prob_pit[x][y] << " "; //cout << "PROB:PIT(" << x << ", " << y << ") = " << prob_pit[x ][y ] << endl; //debug } cout << endl; } cout << endl; } void Agent::Pit(int x, int y, float v) { prob_pit[x - 1][y - 1] = v; //cout << "PROB:PIT(" << x - 1 << ", " << y - 1 << ") = " << prob_pit[x - 1][y - 1] << endl; } bool Agent::SearchListLoc(list<Location> &list_loc, Location &loc) { list<Location>::iterator itr; for (itr = list_loc.begin(); itr != list_loc.end(); ++itr) { Location L = *itr; if ((L.X == loc.X) && (L.Y == loc.Y)) { //cout << "[!] - SearchListLoc() = TRUE / (" << loc.X << "," << loc.Y << ")\n"; // debug return true; } } //cout << "[!] - SearchListLoc() = FALSE / (" << loc.X << "," << loc.Y << ")\n"; // debug return false; } void Agent::CheckFrontier(int x, int y) { float y_true = 0.0, y_false = 0.0; float new_frontier; // P(Pitx,y=true) = 0.0 // P(Pitx,y=false) = 0.0 // frontier’ = frontier – {Pitx,y} }
26.039461
185
0.637923
[ "vector" ]
8c2b0a5524bf1c7efb17a057b9e5f850d5ff2c51
3,229
cpp
C++
intuit/12.cpp
19yetnoob/-6Companies30days
93f8dc6370cae7a8907d02b3ac8de610b73b8d9f
[ "MIT" ]
null
null
null
intuit/12.cpp
19yetnoob/-6Companies30days
93f8dc6370cae7a8907d02b3ac8de610b73b8d9f
[ "MIT" ]
null
null
null
intuit/12.cpp
19yetnoob/-6Companies30days
93f8dc6370cae7a8907d02b3ac8de610b73b8d9f
[ "MIT" ]
null
null
null
// class Solution { // public: // void dfs(vector<vector<int>>adj,int node,int par,vector<int>done,vector<int>visit,int &c,vector<int>&curr){ // visit[node]=1; // for(auto a:adj[node]){ // if(c!=0) // break; // if(visit[a]==-1){ // if(done[a]==1) // { // c=1; // visit[a]=1; // break; // } // else // { // dfs(adj,a,node,done,visit,c,curr); // } // } // else // { // if(a!=par) // { // c=-1; // break; // } // } // } // if(c==1){ // done[node]=1;curr.push_back(node);} // } // vector<int> findOrder(int n, vector<vector<int>>& p) { // vector<vector<int>>adj(n); // for(auto a:p){ // adj[a[0]].push_back(a[1]); // } // vector<int>ans; // vector<int>done(n,-1); // vector<int>visit(n,-1); // for(int i=0;i<n;i++) // if(adj[i].size()==0) // done[i]=1; // for(int i=0;i<n;i++){ // // vector<int>visit(n,-1); // if(visit[i]!=1){ // vector<int>curr; // int c=0; // dfs(adj,i,-1,done,visit,c,curr); // if(c==-1) // return {}; // for(auto a:curr) // ans.push_back(a); // } // } // return ans; // } // }; class Solution { public: bool topoSort(vector<int> adj[], int V, vector<int> &res) { vector<int> indegree(V, 0); // count indegree of every vertex for (int i = 0; i < V; i++) { for (auto u : adj[i]) { indegree[u]++; } } queue<int> q; // push vertices having indegrees 0 for (int i = 0; i < V; i++) { if (indegree[i] == 0) { q.push(i); } } while (!q.empty()) { int u = q.front(); q.pop(); for (auto v : adj[u]) { // reducing its indegree by 1 indegree[v]--; // if indegree = 0 then push it to queue if (indegree[v] == 0) q.push(v); } res.emplace_back(u); } return res.size() != V; } vector<int> findOrder(int n, vector<vector<int>> &pre) { vector<int> adj[n]; int count = 0; for (int i = 0; i < pre.size(); i++) { int u = pre[i][0]; int v = pre[i][1]; adj[v].push_back(u); } vector<int> res; if (topoSort(adj, n, res)) { res.clear(); } return res; } };
27.836207
115
0.315268
[ "vector" ]
8c42322675eb7c00874d8b8bc1fa4e26300edb85
387
cpp
C++
e_pascal_triangle2.cpp
skyera/myleetcode
c3524e73b320afb863d0c04d40b1b660ff9fec8c
[ "MIT" ]
null
null
null
e_pascal_triangle2.cpp
skyera/myleetcode
c3524e73b320afb863d0c04d40b1b660ff9fec8c
[ "MIT" ]
null
null
null
e_pascal_triangle2.cpp
skyera/myleetcode
c3524e73b320afb863d0c04d40b1b660ff9fec8c
[ "MIT" ]
null
null
null
// Pascal triangle II // 9/4/2017 // Easy #include <iostream> #include <vector> using namespace std; vector<int> getrow(int rowindex) { vector<int> array; for (int i = 0; i <= rowindex; i++) { for (int j = i - 1; j > 0; j--) { array[j] = array[j-1] + array[j]; } array.push_back(1); } return array; } int main() { return 0; }
14.884615
45
0.516796
[ "vector" ]
8c48a16a40040ebc2b50103b852497b61543de8c
8,835
cpp
C++
SimpleMesh/XML.cpp
plisdku/trogdor6
d77eb137dd0c03635c0016801ada54117697e521
[ "MIT" ]
null
null
null
SimpleMesh/XML.cpp
plisdku/trogdor6
d77eb137dd0c03635c0016801ada54117697e521
[ "MIT" ]
null
null
null
SimpleMesh/XML.cpp
plisdku/trogdor6
d77eb137dd0c03635c0016801ada54117697e521
[ "MIT" ]
null
null
null
// // XML.cpp // Trogdor6 // // Created by Paul Hansen on 3/4/18. // Copyright 2018 Stanford University. // // * This file is covered by the MIT license. See LICENSE.txt. #include "XML.h" #include <string> #include <sstream> #include <stdexcept> #include "XMLExtras.h" #include "tinyxml.h" namespace SimpleMesh { void loadControlVertices(std::vector<SimpleMesh::ControlVertex> & controlVertices, const TiXmlElement* verticesXML) { const TiXmlElement* vertexXML = verticesXML->FirstChildElement("Vertex"); while (vertexXML) { SimpleMesh::ControlVertex controlVertex; SimpleMesh::loadControlVertex(controlVertex, vertexXML, controlVertices.size()); controlVertices.push_back(controlVertex); vertexXML = vertexXML->NextSiblingElement("Vertex"); } } void loadControlVertex(SimpleMesh::ControlVertex & controlVertex, const TiXmlElement* vertexXML, int newIndex) { Vector3d point; Vector3b freeDirections; sGetMandatoryAttribute(vertexXML, "position", point); sGetOptionalAttribute(vertexXML, "freeDirections", freeDirections, Vector3b(0,0,0)); controlVertex = SimpleMesh::ControlVertex(point, freeDirections, newIndex); } void loadMeshes(std::vector<std::vector<SimpleMesh::Triangle> > & allMeshes, const TiXmlElement* meshXML, const std::vector<SimpleMesh::ControlVertex> & controlVertices) { const TiXmlElement* solidXML = meshXML->FirstChildElement("Solid"); while (solidXML) { std::vector<SimpleMesh::Triangle> meshFaces; SimpleMesh::loadMesh(meshFaces, solidXML, controlVertices); allMeshes.push_back(meshFaces); solidXML = solidXML->NextSiblingElement("Solid"); } } void loadMesh(std::vector<SimpleMesh::Triangle> & meshFaces, const TiXmlElement* solidXML, const std::vector<SimpleMesh::ControlVertex> & controlVertices) { const TiXmlElement* faceXML = solidXML->FirstChildElement("Face"); while (faceXML) { SimpleMesh::Triangle meshTri; loadFace(meshTri, faceXML, controlVertices); meshFaces.push_back(meshTri); faceXML = faceXML->NextSiblingElement("Face"); } } void loadFace(SimpleMesh::Triangle & meshTri, const TiXmlElement* faceXML, const std::vector<SimpleMesh::ControlVertex> & controlVertices) { Vector3i idxFaceVertices; Vector3i idxFaceControlVertices; sGetMandatoryAttribute(faceXML, "vertices", idxFaceVertices); sGetOptionalAttribute(faceXML, "controlVertices", idxFaceControlVertices, idxFaceVertices); std::vector<std::vector<int> > edgeControlVertices; loadEdgeControlVertices(edgeControlVertices, faceXML, controlVertices); Triangle3d tri(controlVertices.at(idxFaceVertices[0]).point(), controlVertices.at(idxFaceVertices[1]).point(), controlVertices.at(idxFaceVertices[2]).point()); meshTri.triangle(tri); meshTri.controlVertices(controlVertices.at(idxFaceControlVertices[0]), controlVertices.at(idxFaceControlVertices[1]), controlVertices.at(idxFaceControlVertices[2])); if (edgeControlVertices.empty()) { meshTri.edgeControlVertices(controlVertices.at(idxFaceControlVertices[0]), controlVertices.at(idxFaceControlVertices[1]), controlVertices.at(idxFaceControlVertices[2])); } else { for (int ee = 0; ee < 3; ee++) { std::vector<SimpleMesh::ControlVertex> tmpControlVertices; for (int vv = 0; vv < edgeControlVertices[ee].size(); vv++) { tmpControlVertices.push_back(controlVertices.at(edgeControlVertices[ee][vv])); } meshTri.edgeControlVertices(ee, tmpControlVertices); } } meshTri.cacheSensitivity(); } void loadEdgeControlVertices(std::vector<std::vector<int> > & edgeControlVertices, const TiXmlElement* faceXML, const std::vector<SimpleMesh::ControlVertex> & controlVertices) { const TiXmlElement* edgeXML = faceXML->FirstChildElement("Edge"); while (edgeXML) { std::string cvString = edgeXML->Attribute("controlVertices"); std::istringstream str(cvString); int idxControlVert; std::vector<int> edgeCVs; while (str >> idxControlVert) { edgeCVs.push_back(idxControlVert); } if (edgeCVs.size() != 2 && edgeCVs.size() != 6) { std::ostringstream err; err << "Edge must have 2 or 6 control vertices (possible location: row " << edgeXML->Row() << ")"; throw std::runtime_error(err.str().c_str()); } edgeControlVertices.push_back(edgeCVs); edgeXML = edgeXML->NextSiblingElement("Edge"); } if (edgeControlVertices.size() != 0 && edgeControlVertices.size() != 3) { std::ostringstream err; err << "Face must have 0 or 3 Edge elements (possible location: row " << faceXML->Row() << ")"; throw std::runtime_error(err.str().c_str()); } } void createMeshesXML(const std::vector<std::vector<SimpleMesh::Triangle> > & meshes, const std::vector<SimpleMesh::ControlVertex> & controlVertices, TiXmlElement & outMeshesXML) { std::vector<SimpleMesh::ControlVertex> allVerts(controlVertices); // Build vertex ID map. // This is necessary because I haven't got a true face-vertex data structure. // First put in the control vertices. std::map<Vector3d, int> vertexIds; for (int vv = 0; vv < controlVertices.size(); vv++) { vertexIds[controlVertices[vv].point()] = controlVertices[vv].id(); } // Then put in the other (non-control) vertices. int nextVertId = vertexIds.size(); for (int mm = 0; mm < meshes.size(); mm++) { const std::vector<SimpleMesh::Triangle> & tris = meshes.at(mm); for (int tt = 0; tt < tris.size(); tt++) { const Triangle3d & tri = tris[tt].triangle(); for (int ii = 0; ii < 3; ii++) { if (vertexIds.count(tri[ii]) == 0) { vertexIds[tri[ii]] = nextVertId; allVerts.push_back(SimpleMesh::ControlVertex(tri[ii], Vector3b(false, false, false), nextVertId)); nextVertId++; } } } } TiXmlElement verticesXML("Vertices"); createControlVerticesXML(allVerts, verticesXML); outMeshesXML.InsertEndChild(verticesXML); for (int mm = 0; mm < meshes.size(); mm++) { const std::vector<SimpleMesh::Triangle> & meshTriangles = meshes.at(mm); TiXmlElement meshXML("Solid"); meshXML.SetAttribute("id", std::to_string(mm).c_str()); createMeshXML(meshTriangles, vertexIds, meshXML); outMeshesXML.InsertEndChild(meshXML); } } void createControlVerticesXML(const std::vector<SimpleMesh::ControlVertex> & controlVertices, TiXmlElement & outVerticesXML) { for (int vv = 0; vv < controlVertices.size(); vv++) { const SimpleMesh::ControlVertex & cv = controlVertices.at(vv); TiXmlElement vertexXML("Vertex"); std::ostringstream pointStream; pointStream.precision(20); pointStream << cv.point()[0] << " " << cv.point()[1] << " " << cv.point()[2]; vertexXML.SetAttribute("position", pointStream.str().c_str()); std::ostringstream freeDirStream; freeDirStream.precision(20); freeDirStream << cv.freeDirections()[0] << " " << cv.freeDirections()[1] << " " << cv.freeDirections()[2]; vertexXML.SetAttribute("freeDirections", freeDirStream.str().c_str()); outVerticesXML.InsertEndChild(vertexXML); } } void createMeshXML(const std::vector<SimpleMesh::Triangle> & meshFaces, const std::map<Vector3d, int> & vertexIds, TiXmlElement & outMeshXML) { for (int ff = 0; ff < meshFaces.size(); ff++) { const SimpleMesh::Triangle & tri = meshFaces.at(ff); TiXmlElement faceXML("Face"); std::ostringstream verticesStream; verticesStream << vertexIds.find(tri.triangle()[0])->second << " " << vertexIds.find(tri.triangle()[1])->second << " " << vertexIds.find(tri.triangle()[2])->second; faceXML.SetAttribute("vertices", verticesStream.str().c_str()); std::ostringstream cvStream; cvStream << tri.controlVertices()[0].id() << " " << tri.controlVertices()[1].id() << " " << tri.controlVertices()[2].id(); faceXML.SetAttribute("controlVertices", cvStream.str().c_str()); outMeshXML.InsertEndChild(faceXML); } } }; // namespace SimpleMesh
33.850575
118
0.63339
[ "vector", "solid" ]
8c49cff07425a8bba94fade4369cd3856d099113
4,960
cpp
C++
momentumopt/demos/demo_momentumopt.cpp
ferdinand-wood/kino_dynamic_opt
ba6bef170819c55d1d26e40af835a744d1ae663f
[ "BSD-3-Clause" ]
26
2019-11-18T17:39:43.000Z
2021-12-18T00:38:22.000Z
momentumopt/demos/demo_momentumopt.cpp
ferdinand-wood/kino_dynamic_opt
ba6bef170819c55d1d26e40af835a744d1ae663f
[ "BSD-3-Clause" ]
25
2019-11-11T19:54:51.000Z
2021-04-07T13:41:47.000Z
momentumopt/demos/demo_momentumopt.cpp
ferdinand-wood/kino_dynamic_opt
ba6bef170819c55d1d26e40af835a744d1ae663f
[ "BSD-3-Clause" ]
10
2019-12-15T14:36:51.000Z
2021-09-29T10:42:19.000Z
/* * Copyright [2017] Max Planck Society. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * This demo shows how to use the dynamics optimization routine given * an appropriate configuration file. It requires an initial robot state * and a reference momentum trajectory. The optimized motion plan is available * to the user under a DynamicsSequence object (dyn_optimizer.dynamicsSequence()), * which is a collection of dynamic states, each of which contains information * about all variables, and all end-effectors of the motion plan for one time step. * * If the variable store_data within the configuration file has been set * to True, then a file of results will also be written. It can be found * next to the configuration file with the keyword "_results" appended. * It can be visualized with the available python script as indicated in * the Readme file. */ #include <iomanip> #include <yaml-cpp/yaml.h> #include <momentumopt/dynopt/DynamicsOptimizer.hpp> #include <momentumopt/cntopt/ContactPlanFromFile.hpp> using namespace momentumopt; int main( int argc, char *argv[] ) { // load configuration file std::string cfg_file = CFG_SRC_PATH; if (argc==3) { if (std::strcmp(argv[1], "i")) cfg_file += argv[2]; } else { std::cout << "Usage: ./demo -i <name of config file within config folder>" << std::endl; return 1; } // define problem configuration PlannerSetting planner_setting; planner_setting.initialize(cfg_file); // define robot initial state DynamicsState ini_state; ini_state.fillInitialRobotState(cfg_file); // define reference kinematic sequence momentumopt::KinematicsSequence kin_sequence; kin_sequence.resize(planner_setting.get(PlannerIntParam_NumTimesteps), planner_setting.get(PlannerIntParam_NumDofs)); // define terrain description momentumopt::TerrainDescription terrain_description; terrain_description.loadFromFile(cfg_file); // define contact plan ContactPlanFromFile contact_plan; contact_plan.initialize(planner_setting); contact_plan.optimize(ini_state, terrain_description); // optimize motion DynamicsOptimizer dyn_optimizer; dyn_optimizer.initialize(planner_setting); dyn_optimizer.optimize(ini_state, &contact_plan, kin_sequence); /* optimized variables can be retrieved as (remember that forces are normalized by mass times gravity) * * for (int time_id=0; time_id<dyn_optimizer.dynamicsSequence().size(); time_id++) { * std::cout << dyn_optimizer.dynamicsSequence().dynamicsState(time_id).centerOfMass().transpose() << std::endl; * std::cout << dyn_optimizer.dynamicsSequence().dynamicsState(time_id).linearMomentum().transpose() << std::endl; * std::cout << dyn_optimizer.dynamicsSequence().dynamicsState(time_id).angularMomentum().transpose() << std::endl; * for (int eff_id=0; eff_id<Problem::n_endeffs_; eff_id++) { * std::cout << dyn_optimizer.dynamicsSequence().dynamicsState(time_id).endeffectorForce(eff_id).transpose() << std::endl; * std::cout << dyn_optimizer.dynamicsSequence().dynamicsState(time_id).endeffectorTorque(eff_id).transpose() << std::endl; * std::cout << dyn_optimizer.dynamicsSequence().dynamicsState(time_id).endeffectorCoP(eff_id).transpose() << std::endl; * } * } */ /* An iterative optimization between kinematics and dynamics could be done as follows. * Instead of only running once the optimize function from dynamics_optimizer, it is possible to iterate * * dyn_optimizer.optimize(kin_optimizer_.kinematicsSequence()); * for (int iter_id=0; iter_id<NumKinDynIterations; iter_id++) { * kin_optimizer_.optimize(dyn_optimizer_.dynamicsSequence()); * dyn_optimizer_.optimize(kin_optimizer_.kinematicsSequence(), true); * } * * where dynamicsSequence() and kinematicsSequence() are instances of the class DynamicsSequence. * The dynamics_optimizer will try to track the momentum values contained within kinematicsSequence(), * and the kinematics_optimizer will try to track the momentum values contained within dynamicsSequence(). * The kinematics_optimizer is not provided. * * The "true" flag passed to the dynamics_optimizer signals that it should switch from * regularization weights to tracking weights. */ }
44.285714
130
0.742944
[ "object" ]
8c5b6f851eddbd956fe1ba2cc873c7c5fe96a7cd
16,213
cpp
C++
oi/ceoi/2016/icc/graderlib.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
3
2018-08-30T09:43:20.000Z
2019-12-03T04:53:43.000Z
oi/ceoi/2016/icc/graderlib.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
oi/ceoi/2016/icc/graderlib.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
#ifndef INTERACTION_IMLP #define INTERACTION_IMLP #include "icc.h" #include <cstdio> #include <cmath> #include <array> #include <fstream> #include <iostream> #include <vector> using namespace std; #define DEBUG(...) if (0) { __VA_ARGS__; } namespace ceoi_2016 { const bool PRINT_SCORE_TO_STDERR = false; void Fail(const string&); // If condition is not true, sets score to 0 because reasons. void Expect(bool condition, const string& message) { if (not condition) { Fail(message); } }; class Solver { public: // query provided by the problem virtual bool Query(int n, int m, int* a, int* b) = 0; // checks whatever or not that is the edge. order does not matter. // does not crash if it's false. just returnes true. virtual bool SetEdge(int a, int b) = 0; // returns true if threre're no more edges left to add. virtual bool IsOver() = 0; virtual int NumVertices() = 0; }; struct BasicSolver : public Solver { BasicSolver(istream& fin) { fin >> n; edges_order.resize(n - 1); for (int i = 0; i < n; i += 1) { fin >> edges_order[i].first >> edges_order[i].second; } current_edge = 0; } bool Query(int a, int b, int* A, int *B); bool SetEdge(int a, int b); bool IsOver() { return current_edge == n - 1; } int NumVertices() { return n; } private: vector<pair<int, int> > edges_order; int n, current_edge; }; bool BasicSolver::Query(int a, int b, int A[], int B[]) { DEBUG({ fprintf(stderr, "[Query]\n{"); for (int i = 0; i < a; i += 1) { fprintf(stderr, "%d%s", A[i], ((i + 1 != a) ? (",\t") : (""))); } fprintf(stderr, "}\n{"); for (int i = 0; i < b; i += 1) { fprintf(stderr, "%d%s", B[i], ((i + 1 != b) ? (",\t") : (""))); } fprintf(stderr, "}\n\n"); }); vector<int> left(n + 1, 0), right(n + 1, 0); for (int i = 0; i < a; i += 1) { // sanity check Expect(1 <= A[i] and A[i] <= n, "Query cities not in range [1, n]"); left[A[i]] = 1; } for (int i = 0; i < b; i += 1) { // sanity check Expect(1 <= B[i] and B[i] <= n, "Query cities not in range [1, n]"); right[B[i]] = 2; Expect(left[B[i]] == 0, "The query sets must be disjoint"); } bool ok = false; for (int i = 0; i <= current_edge; i += 1) { ok |= (left[edges_order[i].first] + right[edges_order[i].second] == 3); ok |= (left[edges_order[i].second] + right[edges_order[i].first] == 3); } return ok; } bool BasicSolver::SetEdge(int a, int b) { int x = edges_order[current_edge].first; int y = edges_order[current_edge].second; if (x > y) { swap(x, y); } if (a > b) { swap(a, b); } DEBUG({ fprintf(stderr, "[SetRoad]\nGiven Road\t%d\t%d\nActual Road\t%d\t%d\n\n\n\n", a, b, x, y); }); if ((a == x and b == y) or (a == y and b == x)) { current_edge += 1; return true; } else { current_edge += 1; return false; } } // ********************************************************************************************************************************** // // Interactive Solver // // ********************************************************************************************************************************** static const int kMaxN = 101; typedef array<array<int, kMaxN>, kMaxN> IntArr; struct AdjacencyMatrixInformation { int num_ctc_pairs; int num_edges; int max_edges_2_ctcs; AdjacencyMatrixInformation() : num_ctc_pairs(0), num_edges(0), max_edges_2_ctcs(0) { } }; AdjacencyMatrixInformation GetAMInformation(const IntArr& valid_edge, const vector<int>& component) { IntArr component_count; AdjacencyMatrixInformation result; int n = kMaxN - 1; for (int i = 1; i <= n; i += 1) { for (int j = 1; j <= n; j += 1) { component_count[i][j] = 0; } } for (int i = 1; i <= n; i += 1) { for (int j = 1; j <= n; j += 1) { if (valid_edge[i][j] == 1) { component_count[component[i]][component[j]] += 1; } } } for (int i = 1; i <= n; i += 1) { for (int j = i + 1; j <= n; j += 1) { if (component_count[i][j] != 0) { result.num_ctc_pairs += 1; result.max_edges_2_ctcs = max(result.max_edges_2_ctcs, component_count[i][j]); result.num_edges += component_count[i][j]; } } } return result; } struct BasicInteractiveSolver : public Solver { double full_num_edges, log_num_edges; double full_max_edges_2_ctc, log_max_edges_2_ctc; double full_num_ctc_pairs, log_num_ctc_pairs; double max_rand; double false_coef, true_coef; // constructor from istream from file BasicInteractiveSolver(istream& fin) : step(0) { fin >> n; fin >> full_num_edges; fin >> log_num_edges; fin >> full_max_edges_2_ctc; fin >> log_max_edges_2_ctc; fin >> full_num_ctc_pairs; fin >> log_num_ctc_pairs; fin >> max_rand; fin >> false_coef >> true_coef; component.resize(n + 1); for (int i = 0; i <= n; i += 1) { component[i] = i; } ResetValidEdges(); } // api virtual bool Query(int a, int b, int* A, int* B); virtual bool SetEdge(int a, int b); // interaction bool IsOver() { return step == n - 1; } int NumVertices() { return n; } // checks whenever of not the query is true by the selected edges up to this point bool IsAlreadyGood(int a, int b, int* A, int *B); // based on a query, returns the adjency matrix for both answers pair<IntArr, IntArr> GetIncludedExcluded(int a, int b, int* A, int *B); // to next edge void ResetValidEdges(); void UniteVertices(int a, int b); // given a adjency matrix estimates the required time to finish virtual int MaxScoreFromAMInfo(AdjacencyMatrixInformation); // step - num of selected edges up to this point, n - num of vertices int step, n; vector<pair<int, int> > selected_edges; // in which component is the node X vector<int> component; IntArr valid_edge; public: // DEBUG ONLY void Print(const IntArr& arr) { fprintf(stderr, "~~~~~~|||~~~~~~\n"); for (int i = 1; i <= n; i += 1) { for (int j = 1; j <= n; j += 1) { fprintf(stderr, "%d ", arr[i][j]); } fprintf(stderr, "\n"); } } }; // ********************************************************************************************************************************** // // Good overall things // // ********************************************************************************************************************************** // Checks if the API query is already ok. Else, we should chose if it's true or not bool BasicInteractiveSolver::IsAlreadyGood(int a, int b, int* A, int *B) { DEBUG({ fprintf(stderr, "[Query]\n{"); for (int i = 0; i < a; i += 1) { fprintf(stderr, "%d%s", A[i], ((i + 1 != a) ? (",\t") : (""))); } fprintf(stderr, "}\n{"); for (int i = 0; i < b; i += 1) { fprintf(stderr, "%d%s", B[i], ((i + 1 != b) ? (",\t") : (""))); } fprintf(stderr, "}\n\n"); }); vector<int> left(n + 1, 0), right(n + 1, 0); for (int i = 0; i < a; i += 1) { // sanity check Expect(1 <= A[i] and A[i] <= n, "Query cities not in range [1, n]"); left[A[i]] = 1; } for (int i = 0; i < b; i += 1) { // sanity check Expect(1 <= B[i] and B[i] <= n, "Query cities not in range [1, n]"); right[B[i]] = 2; Expect(left[B[i]] == 0, "The query sets must be disjoint"); } bool ok = false; for (int i = 0; i < step; i += 1) { ok |= (left[selected_edges[i].first] + right[selected_edges[i].second] == 3); ok |= (left[selected_edges[i].second] + right[selected_edges[i].first] == 3); } return ok; } // method exposed throw API bool BasicInteractiveSolver::SetEdge(int a, int b) { pair<int, int> answer; int count = 0; for (int i = 1; i <= n; i += 1) { for (int j = i + 1; j <= n; j += 1) { if (valid_edge[i][j] != 0) { count += 1; answer = {i, j}; } } } if (count == 0) { Fail("Bug in interaction! Err #1"); } if (count != 1) { return false; } if (answer == make_pair(a, b) or answer == make_pair(b, a)) { UniteVertices(a, b); ResetValidEdges(); step += 1; return true; } else { return false; } } void BasicInteractiveSolver::UniteVertices(int a, int b) { a = component[a]; b = component[b]; for (auto& itr : component) { if (itr == a) { itr = b; } } selected_edges.push_back({a, b}); } // Just guessed a edge. Need to reset all meta-data void BasicInteractiveSolver::ResetValidEdges() { for (int i = 1; i <= n; i += 1) { for (int j = 1; j <= n; j += 1) { valid_edge[i][j] = (component[i] != component[j]); } } } // exclude all edges from the query or include only them :) pair<IntArr, IntArr> BasicInteractiveSolver::GetIncludedExcluded(int a, int b, int* A, int *B) { IntArr exclude = valid_edge; // answer false -> all current edges in the query are invalid IntArr include = valid_edge; // include only the query edges. the others are invalid -> answer = true for (int i = 0; i < a; i += 1) { for (int j = 0; j < b; j += 1) { exclude[A[i]][B[j]] = false; exclude[B[j]][A[i]] = false; } } for (int i = 0; i < a; i += 1) { for (int j = 0; j < b ; j += 1) { if (include[A[i]][B[j]] == 1) { include[A[i]][B[j]] = 2; include[B[j]][A[i]] = 2; } } } for (int i = 1; i <= n; i += 1) { for (int j = 1; j <= n; j += 1) { if (include[i][j] == 1) { include[i][j] = 0; } else if (include[i][j] == 2) { include[i][j] = 1; } } } return {include, exclude}; } // ********************************************************************************************************************************** // // Default Query // // ********************************************************************************************************************************** bool BasicInteractiveSolver::Query(int a, int b, int* A, int *B) { if (IsAlreadyGood(a, b, A, B)) { return true; } if (a == 0 or b == 0) { return false; } auto incexc = GetIncludedExcluded(a, b, A, B); auto& include = incexc.first; auto& exclude = incexc.second; auto inf_inc = GetAMInformation(include, component); auto inf_exc = GetAMInformation(exclude, component); double inc = true_coef * MaxScoreFromAMInfo(inf_inc); double exc = false_coef * MaxScoreFromAMInfo(inf_exc); Expect(!(exc < -1 and inc < -1), "Bug in interaction! Err #2"); if (exc < inc) { valid_edge = include; return true; } else { valid_edge = exclude; return false; } } // ********************************************************************************************************************************** // // Default Cost Estimator // // ********************************************************************************************************************************** int BasicInteractiveSolver::MaxScoreFromAMInfo(AdjacencyMatrixInformation am_info) { if (am_info.num_edges == 0) { return -2.0; } return 1.0 * full_num_edges * am_info.num_edges + 1.0 * log_num_edges * log2(am_info.num_edges) + 1.0 * full_max_edges_2_ctc * am_info.max_edges_2_ctcs + 1.0 * log_max_edges_2_ctc * log2(am_info.max_edges_2_ctcs) + 1.0 * full_num_ctc_pairs * am_info.num_ctc_pairs + 1.0 * log_num_ctc_pairs * log2(am_info.num_ctc_pairs) + 1.0 * max_rand * (1.0 * rand() / RAND_MAX); } // ********************************************************************************************************************************** // // User Interaction // // ********************************************************************************************************************************** class Interaction { public: bool Query(int n, int m, int* a, int *b); void SetEdge(int a, int b); Interaction(Solver* solver, int max_steps, int max_score) : num_steps(0), solver(solver), max_steps(max_steps), max_score(max_score) { } void Fail(const string&); int NumVertices() { return solver->NumVertices(); } private: void SetScore(int score, const string& message); void DecideScore(); int num_steps; Solver* solver; int max_steps, max_score; }; Interaction* interaction; void Interaction::SetScore(int score, const string& message) { Expect(0 <= score and score <= 10, "Error in interaction, invalid score"); if (PRINT_SCORE_TO_STDERR) { fprintf(stderr, "%d %s\n", score, message.c_str()); } ofstream fout("icc.out"); fout << score << ' '; fout << message << '\n'; fout.close(); exit(0); }; // returnes score by the grader based on the number of void Interaction::DecideScore() { if (num_steps <= max_steps) { SetScore(max_score, "Ok! " + to_string(num_steps) + " queries used."); } else { SetScore(0, "Too many queries! " + to_string(num_steps) + " out of " + to_string(max_steps)); } } bool Interaction::Query(int n, int m, int* a, int *b) { num_steps += 1; Expect(num_steps <= 2 * max_steps, "Number of queries more than " + to_string(2 * max_steps) + " out of " + to_string(max_steps)); return solver->Query(n, m, a, b); } void Interaction::SetEdge(int a, int b) { Expect(solver->SetEdge(a, b), "Wrong road!"); if (solver->IsOver()) { DecideScore(); } } // Called by various methods because reasons. void Fail(const string& message) { interaction->Fail(message); } void Interaction::Fail(const string& message) { SetScore(0, message); } } // namespace ceoi_2016 // ********************************************************************************************************************************** // // Main // // ********************************************************************************************************************************** extern "C" { // Implementation of API's SetRoad(int, int) void setRoad(int a, int b) { using namespace ceoi_2016; interaction->SetEdge(a, b); } // Implementation of API's Query(int, int, int*, int*) int query(int n, int m, int* a, int* b) { using namespace ceoi_2016; return interaction->Query(n, m, a, b); } void InitGrader() { using namespace ceoi_2016; /* * fin should have * - solver type * max_steps * points if ok */ ofstream fout("icc.out"); fout << "0 illegal exit!\n"; fout.close(); ifstream fin("icc.in"); int solver_type; fin >> solver_type; int max_steps, max_points; fin >> max_steps >> max_points; Solver* solver; if (solver_type == 0) { /* * fin should have * n * n - 1 edges */ solver = new BasicSolver(fin); } else if (solver_type == 1) { /* * fin should have n * full_num_edges * log_num_edges * full_max_edges_2_ctc * log_max_edges_2_ctc * full_num_ctc_pairs * log_num_ctc_pairs * max_rand * * false_coef * true_coef */ solver = new BasicInteractiveSolver(fin); } else { Fail("Bug in interaction! Err #3"); solver = nullptr; } interaction = new Interaction(solver, max_steps, max_points); } void GraderExitFail() { using namespace ceoi_2016; Fail("Not all edges were guessed!"); } int NumVertices() { using namespace ceoi_2016; return interaction->NumVertices(); } } #endif
27.386824
134
0.498489
[ "vector" ]
8c5bb685970469739716fa1756945d5d47f547a8
1,482
cpp
C++
allocation.cpp
TavaresJoao/TSPDL-using-a-Greedy-Algorithm
3b997c4d4ba0dfd95477540fb74d0e63e082a46e
[ "MIT" ]
null
null
null
allocation.cpp
TavaresJoao/TSPDL-using-a-Greedy-Algorithm
3b997c4d4ba0dfd95477540fb74d0e63e082a46e
[ "MIT" ]
2
2018-09-02T05:32:42.000Z
2018-09-02T05:38:34.000Z
allocation.cpp
TavaresJoao/TSPDL-using-a-Greedy-Algorithm
3b997c4d4ba0dfd95477540fb74d0e63e082a46e
[ "MIT" ]
null
null
null
#include "headers.h" // Cria uma matriz n x n int** create_Matrix(int n) { int **matrix; matrix = (int**) malloc(n*sizeof(int*)); for(int i=0; i<n; i++) matrix[i] = (int*) malloc(n*sizeof(int)); return matrix; } // Cria um vetor de tamnho n int* create_Vector(int n) { int *vector; vector = (int*) malloc(n*sizeof(int)); return vector; } // Seta as variáveis de porto em 0 void initialize_Port(Port porto) { porto.demand=0; porto.draft=0; porto.was_visited=0; } // Cria um conjunto de portos Port* create_PortSet(int n) { Port *port_set; port_set = (Port*) malloc(n*sizeof(Port)); for(int i=0; i<n; i++) initialize_Port(port_set[i]); return port_set; } // Aloca espaço para a estrutura TSPDL TSPDL* create_TSPDL() { TSPDL *tspdl; tspdl = (TSPDL*) malloc(sizeof(TSPDL)); return tspdl; } // Aloca as variáveis de TSPDL com n portos void initialize_TSPDL(TSPDL *tspdl, int n) { // setar a quantidade de portos tspdl->N = n; // alocar os portos tspdl->setPorts = create_PortSet(n); // alocar a matriz de custos tspdl->c = create_Matrix(n); } // Funções para desalocar memória void free_Vector(int *vector) { free(vector); } void free_Matrix(int **matrix, int n) { for(int i=0; i<n; i++) free_Vector(matrix[i]); free(matrix); } void free_PortSet(Port *portSet) { free(portSet); } void free_TSPDL(TSPDL *tspdl) { free_PortSet(tspdl->setPorts); free_Matrix(tspdl->c, tspdl->N); free(tspdl); }
15.4375
45
0.654521
[ "vector" ]
8c6a1c13d1f816f92e50f8de5f57b1302b4cd1f0
504
cpp
C++
Cplus/NumberofGoodWaystoSplitaString.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
1
2018-01-22T12:06:28.000Z
2018-01-22T12:06:28.000Z
Cplus/NumberofGoodWaystoSplitaString.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
Cplus/NumberofGoodWaystoSplitaString.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
#include <string> #include <vector> using namespace std; class Solution { public: int numSplits(string s) { vector<int> left(26), right(26); for (auto c : s) ++right[c - 'a']; int res = 0, leftcount = 0, rightcount = 0; for (int i = 0; i < 26; ++i) rightcount += right[i] > 0 ? 1 : 0; for (auto c : s) { if (--right[c - 'a'] == 0) --rightcount; if (left[c - 'a'] == 0) ++leftcount; ++left[c - 'a']; if (rightcount == leftcount) ++res; } return res; } };
17.37931
45
0.52381
[ "vector" ]
8c78fc24c3403c5444d3d26d36f72c87f6d9ffd4
7,184
cpp
C++
src/FusionEKF.cpp
bifrost/CarND-Extended-Kalman-Filter-Project
0223960d39a6aa69a4080196e5c1e6ef91627b7d
[ "MIT" ]
null
null
null
src/FusionEKF.cpp
bifrost/CarND-Extended-Kalman-Filter-Project
0223960d39a6aa69a4080196e5c1e6ef91627b7d
[ "MIT" ]
null
null
null
src/FusionEKF.cpp
bifrost/CarND-Extended-Kalman-Filter-Project
0223960d39a6aa69a4080196e5c1e6ef91627b7d
[ "MIT" ]
null
null
null
#include "FusionEKF.h" #include "tools.h" #include "Eigen/Dense" #include <iostream> using namespace std; using Eigen::MatrixXd; using Eigen::VectorXd; using std::vector; /* * Constructor. */ FusionEKF::FusionEKF() { is_initialized_ = false; previous_timestamp_ = 0; // initializing matrices R_laser_ = MatrixXd(2, 2); R_radar_ = MatrixXd(3, 3); H_laser_ = MatrixXd(2, 4); Hj_ = MatrixXd(3, 4); //measurement covariance matrix - laser R_laser_ << 0.0225, 0, 0, 0.0225; //measurement covariance matrix - radar R_radar_ << 0.09, 0, 0, 0, 0.0009, 0, 0, 0, 0.09; /** TODO: * Finish initializing the FusionEKF. * Set the process and measurement noises */ H_laser_ << 1, 0, 0, 0, 0, 1, 0, 0; //create a 4D state vector, we don't know yet the values of the x state ekf_.x_ = VectorXd(4); ekf_.x_ << 1, 1, 1, 1; //state covariance matrix P ekf_.P_ = MatrixXd(4, 4); //the initial transition matrix F_ ekf_.F_ = MatrixXd(4, 4); ekf_.F_ << 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1; //measurement matrix ekf_.H_ = MatrixXd(2, 4); //measurement covariance ekf_.R_ = MatrixXd(2, 2); //the process covariance matrix Q ekf_.Q_ = MatrixXd(4, 4); //set the acceleration noise components noise_ax = 30; noise_ay = 20; Tools tools; } // Experiment radar and laser measurements, for noise_ax=9, noise_ay=9 // RMSE // x y vx vy sum (x+y) // 0.0973, 0.0855, 0.4513, 0.4399 - 0.1828 // Experiment disable radar measurements, for noise_ax=9, noise_ay=9 // RMSE // x y vx vy sum (x+y) // 0.1838, 0.1542, 0.6051, 0.4858 - 0.3380 // Experiment disable laser measurements, for noise_ax=9, noise_ay=9 // RMSE // x y vx vy sum (x+y) // 0.2248, 0.3357, 0.6006, 0.7483 - 0.5605 // Conclusion: // The RMSE has improved at least a factor two by using both laser and radar measurements. // One reason could be that we have twice as much data to calculate the position. // The result might be improved if we were able to collect twice as much laser data instead of radar data. // Experiments for different noise_ax, noise_ay values, * indicate optimal parameter pairs. // // RMSE noise // x y ax,ay sum (x+y) // 0.0973, 0.0855 - 9, 9 - 0.1828 // 0.0942, 0.0836 - 12,12 - 0.1778 // 0.0929, 0.0832 - 14,14 - 0.1761 // 0.0912, 0.0832 - 18,18 - 0.1744 // 0.0904, 0.0830 - 28,20 - 0.1734 * // 0.0909, 0.0825 - 30,18 - 0.1734 * // 0.0907, 0.0827 - 30,19 - 0.1734 * // 0.0905, 0.0829 - 30,20 - 0.1734 * // 0.0907, 0.0827 - 31,19 - 0.1734 * // 0.0910, 0.0825 - 31,18 - 0.1735 // 0.0905, 0.0830 - 29,20 - 0.1735 // 0.0906, 0.0830 - 31,20 - 0.1736 // 0.0909, 0.0826 - 28,18 - 0.1735 // 0.0915, 0.0822 - 30,16 - 0.1737 // 0.0902, 0.0836 - 26,22 - 0.1738 // 0.0909, 0.0829 - 22,18 - 0.1738 // 0.0909, 0.0828 - 23,18 - 0.1737 // 0.0910, 0.0829 - 21,18 - 0.1739 // 0.0899, 0.0841 - 24,24 - 0.1740 // 0.0901, 0.0836 - 24,22 - 0.1737 // 0.0905, 0.0831 - 24,20 - 0.1736 // 0.0908, 0.0830 - 24,19 - 0.1738 // 0.0909, 0.0827 - 24,18 - 0.1736 // 0.0914, 0.0824 - 24,16 - 0.1738 // 0.0905, 0.0832 - 25,20 - 0.1737 // 0.0905, 0.0832 - 23,20 - 0.1737 // Conclusion: // The noise_ax, noise_ay was not set to optimal values and RMSE has been improved by // 0.0068 for x and 0.0029 for y, by setting noise_ax = 30 and noise_ay = 20. /** * Destructor. */ FusionEKF::~FusionEKF() {} void FusionEKF::ProcessMeasurement(const MeasurementPackage &measurement_pack) { //compute the time elapsed between the current and previous measurements float dt = (measurement_pack.timestamp_ - previous_timestamp_) / 1000000.0; //dt - expressed in seconds previous_timestamp_ = measurement_pack.timestamp_; // do not trust the process if dt > 3 seconds, even if dt is part of the process covariance matrix Q // this is needed to switch between the two datasets on the fly if (abs(dt) > 3) { is_initialized_ = false; } /***************************************************************************** * Initialization ****************************************************************************/ if (!is_initialized_) { /** TODO: * Initialize the state ekf_.x_ with the first measurement. * Create the covariance matrix. * Remember: you'll need to convert radar from polar to cartesian coordinates. */ // first measurement if (measurement_pack.sensor_type_ == MeasurementPackage::RADAR) { /** Convert radar from polar to cartesian coordinates and initialize state. */ float ro = measurement_pack.raw_measurements_[0]; float theta = measurement_pack.raw_measurements_[1]; float ro_dot = measurement_pack.raw_measurements_[2]; float x = sin(theta) * ro; float y = cos(theta) * ro; float x_dot = sin(theta) * ro_dot; float y_dot = cos(theta) * ro_dot; ekf_.x_ << x, y, x_dot, y_dot; } else if (measurement_pack.sensor_type_ == MeasurementPackage::LASER) { /** Initialize state. */ ekf_.x_ << measurement_pack.raw_measurements_[0], measurement_pack.raw_measurements_[1], 0, 0; } //init state covariance matrix P ekf_.P_ << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1000, 0, 0, 0, 0, 1000; previous_timestamp_ = measurement_pack.timestamp_; // done initializing, no need to predict or update is_initialized_ = true; return; } /***************************************************************************** * Prediction ****************************************************************************/ /** TODO: * Update the state transition matrix F according to the new elapsed time. - Time is measured in seconds. * Update the process noise covariance matrix. * Use noise_ax = 9 and noise_ay = 9 for your Q matrix. */ float dt_2 = dt * dt; float dt_3 = dt_2 * dt; float dt_4 = dt_3 * dt; //Modify the F matrix so that the time is integrated ekf_.F_(0, 2) = dt; ekf_.F_(1, 3) = dt; //set the process covariance matrix Q ekf_.Q_ = MatrixXd(4, 4); ekf_.Q_ << dt_4 / 4 * noise_ax, 0, dt_3 / 2 * noise_ax, 0, 0, dt_4 / 4 * noise_ay, 0, dt_3 / 2 * noise_ay, dt_3 / 2 * noise_ax, 0, dt_2 * noise_ax, 0, 0, dt_3 / 2 * noise_ay, 0, dt_2 * noise_ay; ekf_.Predict(); /***************************************************************************** * Update ****************************************************************************/ /** TODO: * Use the sensor type to perform the update step. * Update the state and covariance matrices. */ if (measurement_pack.sensor_type_ == MeasurementPackage::RADAR) { // Radar updates ekf_.H_ = tools.CalculateJacobian(ekf_.x_); ekf_.R_ = R_radar_; ekf_.UpdateEKF(measurement_pack.raw_measurements_); } else { // Laser updates ekf_.H_ = H_laser_; ekf_.R_ = R_laser_; ekf_.Update(measurement_pack.raw_measurements_); } // print the output cout << "x_ = " << ekf_.x_ << endl; cout << "P_ = " << ekf_.P_ << endl; }
28.0625
106
0.579204
[ "vector" ]
8c7a090b8d3c9968b726637edc5a8e732f9cd7de
440
cpp
C++
Level_6_HW/Section 4.2a/Exercise 1/Exercise 1/main.cpp
ZhehaoLi9705/QuantNet_CPP
a889f4656e757842f4163b0cda7e098cc6ad1193
[ "MIT" ]
null
null
null
Level_6_HW/Section 4.2a/Exercise 1/Exercise 1/main.cpp
ZhehaoLi9705/QuantNet_CPP
a889f4656e757842f4163b0cda7e098cc6ad1193
[ "MIT" ]
null
null
null
Level_6_HW/Section 4.2a/Exercise 1/Exercise 1/main.cpp
ZhehaoLi9705/QuantNet_CPP
a889f4656e757842f4163b0cda7e098cc6ad1193
[ "MIT" ]
null
null
null
// // main.cpp // Exercise 1 // // Created by Zhehao Li on 2020/3/26. // Copyright © 2020 Zhehao Li. All rights reserved. // // Exercise 1: Templated Array Class #include "Shape.hpp" #include "Point.hpp" #include "Array.hpp" #include <iostream> int main(int argc, const char * argv[]) { namespace CTD = ZhehaoLi::Containers; namespace CAD = ZhehaoLi::CAD; CTD::Array<CAD::Point> points(3); return 0; }
18.333333
52
0.631818
[ "cad", "shape" ]
8c7c5db0919b02ffe5e5a68f325817cb5984941d
3,591
hpp
C++
src/common/StateFieldRegistry.hpp
Pathfinder-for-Pitch-Momentum-Bias/FlightSoftware
7256f52f7c5887af7fc8679b163629d1235fa1bb
[ "MIT" ]
6
2020-02-24T07:46:22.000Z
2021-09-26T22:57:05.000Z
src/common/StateFieldRegistry.hpp
pathfinder-for-autonomous-navigation/FlightSoftware
a3c30b10e2a28d17a2de0180c996bcc5f9ada7c7
[ "MIT" ]
537
2019-05-29T04:31:30.000Z
2022-03-06T17:18:56.000Z
src/common/StateFieldRegistry.hpp
Pathfinder-for-Pitch-Momentum-Bias/FlightSoftware
7256f52f7c5887af7fc8679b163629d1235fa1bb
[ "MIT" ]
5
2020-04-01T17:29:37.000Z
2022-02-25T22:26:14.000Z
#ifndef STATE_FIELD_REGISTRY_HPP_ #define STATE_FIELD_REGISTRY_HPP_ #include <memory> #include <set> #include "StateField.hpp" #include "Event.hpp" #include "Fault.hpp" /** * @brief Registry of state fields and which tasks have read/write access to * the fields. StateField objects use this registry to verify valid access to * their values. Essentially, this class is a lightweight wrapper around * multimap. */ class StateFieldRegistry { public: std::vector<InternalStateFieldBase*> internal_fields; std::vector<ReadableStateFieldBase*> readable_fields; std::vector<WritableStateFieldBase*> writable_fields; std::vector<ReadableStateFieldBase*> eeprom_saved_fields; std::vector<Event*> events; std::vector<Fault*> faults; StateFieldRegistry(); /** * @brief Find a field of a given name within the state registry and return a pointer to it. * * @param[in] name Name of state field. * @return Pointer to field, or null pointer if field doesn't exist. */ InternalStateFieldBase* find_internal_field(const std::string &name) const; /** * @brief Find a readable field of a given name within the state registry and return a pointer * to it. * * @param[in] name Name of state field. * @return Pointer to field, or null pointer if field doesn't exist. */ ReadableStateFieldBase* find_readable_field(const std::string &name) const; /** * @brief Find a writable field of a given name within the state registry * and return a pointer to it. * * @param[in] name Name of state field. * @return Pointer to field, or null pointer if field doesn't exist. */ WritableStateFieldBase* find_writable_field(const std::string &name) const; /** * @brief Find an EEPROM-saveable field of a given name within the state registry * and return a pointer to it. * * @param[in] name Name of state field. * @return Pointer to field, or null pointer if field doesn't exist. */ SerializableStateFieldBase* find_eeprom_saved_field(const std::string &name) const; /** * @brief Find an event of a given name within the state registry and return a pointer * to it. * * @param[in] name Name of event. * @return Pointer to event, or null pointer if event doesn't exist. */ Event* find_event(const std::string &name) const; /** * @brief Find a fault of a given name within the state registry and return a pointer * to it. * * @param[in] name Name of fault. * @return Pointer to fault, or null pointer if field doesn't exist. */ Fault* find_fault(const std::string &name) const; /** * @brief Adds a field to the registry. * * @param field State field */ bool add_internal_field(InternalStateFieldBase* field); /** * @brief Marks a field as being downloadable by ground. * * @param field State field */ bool add_readable_field(ReadableStateFieldBase* field); /** * @brief Marks a field as being uploadable by ground. * * @param r ControlTaskBase * @param field Data field */ bool add_writable_field(WritableStateFieldBase* field); /** * @brief Marks an event as being uploadable by ground. * * @param event Data event */ bool add_event(Event* event); /** * @brief Marks a fault as being uploadable by ground. * * @param r ControlTaskBase * @param fault Data fault */ bool add_fault(Fault* fault); }; #endif
29.925
98
0.662768
[ "vector" ]
8c83358be1ff922ca7785a2026d7b732a252d2c7
2,142
cpp
C++
Numerical methods/Linear algebra methods/src/test/CholeskyTests.cpp
ShkalikovOleh/Labs
04161ee96c729d1a8b84906b453c5f0e386aaa8b
[ "MIT" ]
null
null
null
Numerical methods/Linear algebra methods/src/test/CholeskyTests.cpp
ShkalikovOleh/Labs
04161ee96c729d1a8b84906b453c5f0e386aaa8b
[ "MIT" ]
null
null
null
Numerical methods/Linear algebra methods/src/test/CholeskyTests.cpp
ShkalikovOleh/Labs
04161ee96c729d1a8b84906b453c5f0e386aaa8b
[ "MIT" ]
1
2020-11-22T16:21:14.000Z
2020-11-22T16:21:14.000Z
#include <gtest/gtest.h> #include "Matrix.h" #include "Vector.h" #include "Cholesky.h" using namespace LinAlg; Matrix<int> testMatrix() { //Example from: https://en.wikipedia.org/wiki/cholesky_decomposition Matrix<int> matrix(3, 3); matrix(0, 0) = 4; matrix(0, 1) = matrix(1, 0) = 12; matrix(0, 2) = matrix(2, 0) = -16; matrix(1, 1) = 37; matrix(1, 2) = matrix(2, 1) = -43; matrix(2, 2) = 98; return matrix; } TEST(choleskyTests, cholesky) { auto matrix = testMatrix(); auto l = cholesky(matrix); EXPECT_EQ(l.nrow(), matrix.nrow()); EXPECT_EQ(l.ncol(), l.nrow()); EXPECT_EQ(l(0, 0), 2); EXPECT_EQ(l(1, 0), 6); EXPECT_EQ(l(1, 1), 1); EXPECT_EQ(l(2, 0), -8); EXPECT_EQ(l(2, 1), 5); EXPECT_EQ(l(2, 2), 3); for (int i = 0; i < l.nrow(); i++) { for (int j = i + 1; j < l.ncol(); j++) { EXPECT_EQ(l(i, j), 0); } } } TEST(choleskyTests, choleskyThrowIfNonQuadratic) { Matrix<int> matrix(2, 3); ASSERT_THROW(cholesky(matrix), std::invalid_argument); } TEST(choleskyTests, choleskyThrowIfNonSymmetric) { Matrix<int> matrix(2, 2); matrix(0,1) = 1; ASSERT_THROW(cholesky(matrix), std::invalid_argument); } TEST(choleskyTests, ldl) { auto matrix = testMatrix(); auto [l, d] = ldl(matrix); EXPECT_EQ(l.nrow(), matrix.nrow()); EXPECT_EQ(l.ncol(), l.nrow()); EXPECT_EQ(d.nval(), matrix.nrow()); EXPECT_EQ(d(0), 4); EXPECT_EQ(d(1), 1); EXPECT_EQ(d(2), 9); EXPECT_EQ(l(0, 0), 1); EXPECT_EQ(l(1, 0), 3); EXPECT_EQ(l(1, 1), 1); EXPECT_EQ(l(2, 0), -4); EXPECT_EQ(l(2, 1), 5); EXPECT_EQ(l(2, 2), 1); for (int i = 0; i < l.nrow(); i++) { for (int j = i + 1; j < l.ncol(); j++) { EXPECT_EQ(l(i, j), 0); } } } TEST(choleskyTests, ldlThrowIfNonQuadratic) { Matrix<int> matrix(2, 3); ASSERT_THROW(ldl(matrix), std::invalid_argument); } TEST(choleskyTests, ldlThrowIfNonSymmetric) { Matrix<int> matrix(2, 2); matrix(0,1) = 1; ASSERT_THROW(ldl(matrix), std::invalid_argument); }
20.018692
72
0.560224
[ "vector" ]
8c83d7a775591c7118ac3768e7eae4356dc2745f
4,276
cpp
C++
src/objReader.cpp
jmlien/mesh_unfolder
3f1ed2f4b906a57bebf7b35ed75c7c3fa976de58
[ "MIT" ]
1
2021-06-18T16:05:54.000Z
2021-06-18T16:05:54.000Z
src/objReader.cpp
jmlien/mesh_unfolder
3f1ed2f4b906a57bebf7b35ed75c7c3fa976de58
[ "MIT" ]
null
null
null
src/objReader.cpp
jmlien/mesh_unfolder
3f1ed2f4b906a57bebf7b35ed75c7c3fa976de58
[ "MIT" ]
null
null
null
/* * objReader.cpp * */ #include "objReader.h" #include "util/Path.h" namespace masc{ namespace obj{ //convert a string to a list of tokens inline list<string> tokenize(char * tmp, const char * ignore) { list<string> tokens; char * tok = strtok(tmp, ignore); while (tok != NULL) { tokens.push_back(tok); tok = strtok(NULL, ignore); } return tokens; } inline void getAllLabels(istream& in, list<list<string> >& tokens) { const int size = 1024; char * tmp = new char[size]; while (!in.eof()) { in.getline(tmp, size); //check for termination if (string(tmp).find("}") != string::npos) //found "}" break; list<string> tok = tokenize(tmp, " \t[]()<>,={"); if (tok.empty()) continue; string label = tok.front(); if (label[0] == '#') continue; //comment tokens.push_back(tok); } //end while delete[] tmp; } istream& operator>>(istream& in, V& v) { in >> v.x >> v.y >> v.z; return in; } ostream& operator<<(ostream& out, const V& v) { out << v.x << " " << v.y << " " << v.z; return out; } bool objReader::Read(istream& in) { list<list<string> > tokens; getAllLabels(in, tokens); //read pts for( list<string> & token : tokens) { string label=token.front(); token.pop_front(); if (label == "v"){ vector<double> values; for(string& tmp : token) values.push_back(atof(tmp.c_str())); Vpt pt; pt.x=values[0]; pt.y=values[1]; pt.z=values[2]; m_data.pts.push_back(pt); if(values.size()>3) { Vpt pt; pt.x=values[3]; pt.y=values[4]; pt.z=values[5]; m_data.colors.push_back(pt); } } else if (label == "vn"){ vector<double> values; for(string& tmp : token) values.push_back(atof(tmp.c_str())); V pt; pt.x=values[0]; pt.y=values[1]; pt.z=values[2]; m_data.normals.push_back(pt); } else if (label == "vt"){ vector<double> values; for(string& tmp : token) values.push_back(atof(tmp.c_str())); V pt; pt.x=values[0]; pt.y=values[1]; m_data.textures.push_back(pt); } else if(label == "usemtl") { //TODO } else if (label == "mtllib") { this->m_mtl_path=token.front(); //cout << "mtllib " << mtl_path << std::endl; //this->m_mtl_path = mtl_path; // assuming obj and mtl are in the same dir. string full_path = masc::path::DirPath(this->m_filename) + "/" + this->m_mtl_path; this->m_mtl_reader.Read(full_path); } else if (label == "f") { polygon poly; for(string& tmp : token) //each token value { int pos1 = (int)tmp.find('/'); int pos2 = (int)tmp.rfind('/'); int id_v = std::atoi(tmp.substr(0, pos1).c_str()) - 1; int id_t = std::atoi(tmp.substr(pos1 + 1, pos2).c_str()) - 1; int id_n = std::atoi(tmp.substr(pos2 + 1).c_str()) - 1; poly.pts.push_back(id_v); poly.normals.push_back(id_n); poly.textures.push_back(id_t); // string field1 = tmp.substr(0, pos1); // string field2 = tmp.substr(pos1 + 1, pos2 - pos1 - 1); // string field3 = tmp.substr(pos2 + 1); // // if (pos1 < 0 || pos2 < 0) //has no "/" // { // field2.clear(); // field3.clear(); // } // else if (pos1 == pos2 && pos1 >= 0) //has only on "/" // { // field3.clear(); // } // // int id_v = atoi(field1.c_str()) - 1; // poly.pts.push_back(id_v); // // // if (field2.empty() == false) // { // int id_t = atoi(field2.c_str()) - 1; // if (id_t >= 0) poly.textures.push_back(id_t); // } // // if (field3.empty() == false) // { // int id_n = atoi(field3.c_str()) - 1; // if (id_n >= 0) poly.normals.push_back(id_n); // } }//end parsing face if (!poly.pts.empty()) m_data.polys.push_back(poly); } else{} } m_data.compute_v_normal(); return true; } }}//end namespaced
24.434286
91
0.502806
[ "vector" ]
8c8432236b2df2d050adb9e87e425eee4cd5c4b7
1,605
cpp
C++
src/base/RenderStageSequence.cpp
kostrykin/Carna
099783bb7f8a6f52fcc8ccd4666e491cf0aa864c
[ "BSD-3-Clause" ]
null
null
null
src/base/RenderStageSequence.cpp
kostrykin/Carna
099783bb7f8a6f52fcc8ccd4666e491cf0aa864c
[ "BSD-3-Clause" ]
null
null
null
src/base/RenderStageSequence.cpp
kostrykin/Carna
099783bb7f8a6f52fcc8ccd4666e491cf0aa864c
[ "BSD-3-Clause" ]
3
2015-07-23T12:10:14.000Z
2021-06-08T16:07:05.000Z
/* * Copyright (C) 2010 - 2015 Leonid Kostrykin * * Chair of Medical Engineering (mediTEC) * RWTH Aachen University * Pauwelsstr. 20 * 52074 Aachen * Germany * */ #include <Carna/base/RenderStageSequence.h> #include <Carna/base/RenderStage.h> #include <vector> namespace Carna { namespace base { // ---------------------------------------------------------------------------------- // RenderStageSequence :: Details // ---------------------------------------------------------------------------------- struct RenderStageSequence::Details { std::vector< RenderStage* > stages; }; // ---------------------------------------------------------------------------------- // RenderStageSequence // ---------------------------------------------------------------------------------- RenderStageSequence::RenderStageSequence() : pimpl( new Details() ) { } RenderStageSequence::~RenderStageSequence() { clearStages(); } std::size_t RenderStageSequence::stages() const { return pimpl->stages.size(); } void RenderStageSequence::appendStage( RenderStage* stage ) { pimpl->stages.push_back( stage ); } void RenderStageSequence::clearStages() { std::for_each( pimpl->stages.begin(), pimpl->stages.end(), std::default_delete< RenderStage >() ); pimpl->stages.clear(); } RenderStage& RenderStageSequence::stageAt( std::size_t position ) const { CARNA_ASSERT( position < stages() ); return *pimpl->stages[ position ]; } void RenderStageSequence::releaseStages() { pimpl->stages.clear(); } } // namespace Carna :: base } // namespace Carna
18.448276
102
0.543302
[ "vector" ]
8c90b73107e79c4ad2c2d2b76e6ce5e3be9e130f
9,708
hpp
C++
include/Polylidar/Types.hpp
JeremyBYU/polylidar
81390535887644aa5492d85d4768b5f797098531
[ "MIT" ]
149
2020-02-05T14:51:22.000Z
2022-03-29T12:43:53.000Z
include/Polylidar/Types.hpp
JeremyBYU/polylidar
81390535887644aa5492d85d4768b5f797098531
[ "MIT" ]
10
2020-04-29T04:38:41.000Z
2022-02-21T12:48:52.000Z
include/Polylidar/Types.hpp
JeremyBYU/polylidar
81390535887644aa5492d85d4768b5f797098531
[ "MIT" ]
22
2020-02-28T11:39:27.000Z
2022-03-29T02:39:42.000Z
#ifndef POLYLIDAR_TYPES #define POLYLIDAR_TYPES #define _USE_MATH_DEFINES #include <limits> #include <vector> #include <cstdint> #include <array> #include <unordered_map> #include <deque> #include <memory> // include a fast parallel hash map implementation #ifdef PL_USE_STD_UNORDERED_MAP #include <parallel_hashmap/phmap.h> #endif #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #define PL_DEFAULT_ALPHA 0.0 #define PL_DEFAULT_LMAX 1.0 #define PL_DEFAULT_MINTRIANGLES 20 #define PL_DEFAULT_MINHOLEVERTICES 3 #define PL_DEFAULT_MINBBOX 100.0 #define PL_DEFAULT_ZTHRESH 0.0 #define PL_DEFAULT_NORMTHRESH 0.90 #define PL_DEFAULT_NORMTHRESH_MIN 0.90 #define PL_DEFAULT_STRIDE 2 #define PL_DEFAULT_CALC_NORMALS true #define PL_DEFAULT_TASK_THREADS 4 #define PL_EPS_RADIAN 0.001 namespace Polylidar { /** @brief Vector of unsigned integers. Often used to represent a set of triangle indices all spatially connected, aka a plane. */ using VUI = std::vector<size_t>; /** @brief Vector of vector of unsigned integers */ using VVUI = std::vector<VUI>; /** @brief Each plane (planar triangle set) is a collection of unsigned integers. Planes is just a vector of this. */ using Planes = VVUI; /** @brief Each group is a collection of planes with the same dominant plane normal. This hold multiple groups. */ using PlanesGroup = std::vector<Planes>; // Use Parallel Hash Map unless asked not to #ifdef PL_USE_STD_UNORDERED_MAP template <typename T, typename G> using unordered_map = std::unordered_map<T, G>; #else // template <typename T, typename G> // using unordered_map = phmap::flat_hash_map<T, G>; template <typename T, typename G> using unordered_map = std::unordered_map<T, G>; #endif using PointHash = unordered_map<size_t, std::vector<size_t>>; // TODO Change to unordered_set using EdgeSet = unordered_map<size_t, size_t>; /** @brief Planes by default should be aligned with the XY Plane */ static constexpr std::array<double, 3> PL_DEFAULT_DESIRED_VECTOR{0, 0, 1}; /** @brief y-axis on XY Plane */ static constexpr std::array<double, 2> UP_VECTOR = {0.0, 1.0}; /** @brief negative y-axis on XY Plane */ static constexpr std::array<double, 2> DOWN_VECTOR = {0.0, -1.0}; /** @brief 3X3 identity rotation matrix*/ static constexpr std::array<double, 9> PL_DEFAULT_IDENTITY_RM{1, 0, 0, 0, 1, 0, 0, 0, 1}; /** @brief Will be used to indicate an invalid triangle */ static constexpr uint8_t ZERO_UINT8 = static_cast<uint8_t>(0); /** @brief Default valid group */ static constexpr uint8_t ONE_UINT8 = static_cast<uint8_t>(1); /** @brief Will be used to indicate an invalid triangle */ static constexpr uint8_t MAX_UINT8 = static_cast<uint8_t>(255); /** * This class hold a generic matrix datastructure used to hold much of the data in our meshes (vertices, triangles, etc.). * It can own the data or it may not. It can also take ownserhip of a memory buffer. * Over time I have become concerned with this datastructure because of this flexibility which can bring bugs if one is not careful. * */ template <class T> class Matrix { public: /** @brief Does the matrix own the data pointed to by `ptr`. If yes then ptr == data.data(). */ bool own_data; /** @brief Buffer of memory that may/may-not be used based upon own_data flag */ std::vector<T> data; /** @brief This is raw pointer that never needs to be freed. * It either point to memory in `data` which will be automatically freed during object destruction (`own_data` = true). * Or it points some other managed memory controlled by the user (`own_data` = false) */ T* ptr; /** @brief Rows in the matrix */ size_t rows; /** @brief Columns in the matrix */ size_t cols; /** * @brief Construct a new Matrix< T> object * * @param ptr_ Raw pointer to underlying data we DON'T own * @param rows_ * @param cols_ */ Matrix<T>(T* ptr_, size_t rows_, size_t cols_) : own_data(false), data(), ptr(ptr_), rows(rows_), cols(cols_) {} /** * @brief Construct a new Matrix< T> object, everything is empty but is owned * */ Matrix<T>() : own_data(true), data(), ptr(data.data()), rows(0), cols(0) {} /** * @brief Construct a new Matrix< T> object. * We will take ownership of this data buffer * * @param old_vector Old vector that will moved and managed by this new Matrix Object * @param rows_ * @param cols_ */ Matrix<T>(std::vector<T>&& old_vector, size_t rows_, size_t cols_) : own_data(true), data(), ptr(nullptr), rows(rows_), cols(cols_) { data = std::move(old_vector); ptr = data.data(); } ~Matrix<T>() = default; /** * @brief Construct a new Matrix< T> object, Copy Constructor. * Will take an existing matrix and will perform a copy. * If the data is owned it will be copied, if not it wont be copied. * @param a */ Matrix<T>(Matrix<T>& a) : own_data(a.own_data), data(a.data), ptr(a.ptr), rows(a.rows), cols(a.cols) { if (own_data) { ptr = data.data(); } } /** * @brief Construct a new Matrix< T> object, Copy Constructor. * Will take an existing matrix and will perform a copy. * If the data is owned it will be copied, if not it wont be copied. * @param a */ Matrix<T>(const Matrix<T>& a) : own_data(a.own_data), data(a.data), ptr(a.ptr), rows(a.rows), cols(a.cols) { if (own_data) { ptr = data.data(); } } /** * @brief Default move constructor, take ownership of all the data of `other` * * @param other */ Matrix<T>(Matrix<T>&& other) = default; /** * @brief Copy assignment operator * This one is a little tricky. We make a copy of every element in the data. * However if we own the data we reassign `ptr` to belong to our new copied buffer * @param a * @return Matrix<T>& */ Matrix<T>& operator=(const Matrix<T>& a) { own_data = a.own_data; data = a.data; ptr = a.ptr; rows = a.rows; cols = a.cols; if (a.own_data) { ptr = data.data(); } return *this; }; /** * @brief Simple helper function to change our `ptr` to point to our own buffer * */ void UpdatePtrFromData() { ptr = data.data(); } /** * @brief Simply updates our rows and columns and data * * @param rows_ * @param cols_ */ void UpdatePtrFromData(const size_t rows_, const size_t cols_) { rows = rows_; cols = cols_; ptr = data.data(); own_data = true; } /** * @brief Acces an element of the Matrix using 2D indices * * @param i * @param j * @return const T& */ const T& operator()(size_t i, size_t j) const { // assert(i >= 0 && i < rows); // assert(j >= 0 && j < cols); return ptr[i * cols + j]; } /** * @brief Access an element in the matrix using its underlying buffer 1D index * * @param index * @return const T& */ const T& operator()(size_t index) const { // assert(i >= 0 && i < rows); // assert(j >= 0 && j < cols); return ptr[index]; } /** * @brief This actually performs a memory copy from an unknown buffer of one type (G) * to *our* buffer of a different type (T). We own this new copied data. * * @tparam G * @param ptr_from * @param rows * @param cols * @return Matrix<T> */ template <class G> static Matrix<T> CopyFromDifferentType(G* ptr_from, size_t rows, size_t cols) { Matrix<T> matrix; auto& matrix_data = matrix.data; auto total_elements = rows * cols; matrix_data.resize(total_elements); for (size_t i = 0; i < total_elements; ++i) { matrix_data[i] = static_cast<T>(ptr_from[i]); } matrix.UpdatePtrFromData(rows, cols); return std::move(matrix); } }; /** * Contains the linear rings of a polygon * */ struct Polygon { /** @brief Linear ring of our exterior shell. The elements are point indices into a point cloud*/ std::vector<size_t> shell; /** @brief Set of linear rings of interior holes in our polygon*/ VVUI holes; Polygon() : shell(), holes() {} VVUI getHoles() const { return holes; } void setHoles(VVUI x) { holes = x; } }; /** * Represents point on the far right (x-axis) of hull of a mesh * TODO remove the far left x-axis information that I dont use/need * */ struct ExtremePoint { size_t xr_he = 0; size_t xr_pi = 0; double xr_val = -1 * std::numeric_limits<double>::infinity(); size_t xl_he = 0; size_t xl_pi = 0; double xl_val = std::numeric_limits<double>::infinity(); }; /** * Represents information about a dominant plane normal * Contains the surface unit normal and rotation matrix to align this normal to [0,0,1] * Needs rotation is false if plane normal is already close to [0,0,1] * Each dominant plane normal also has a unique id to represent it */ struct PlaneData { std::array<double, 3> plane_normal = PL_DEFAULT_DESIRED_VECTOR; std::array<double, 9> rotation_matrix = PL_DEFAULT_IDENTITY_RM; bool need_rotation = false; uint8_t normal_id = ONE_UINT8; }; /** @brief Vector of polygons */ using Polygons = std::vector<Polygon>; /** @brief A group holds polygons for one dominant plane normal. This holds multiple groups. */ using PolygonsGroup = std::vector<Polygons>; } // namespace Polylidar #endif
32.145695
132
0.639782
[ "mesh", "object", "vector" ]
8c90bbaa952dd0f46badca801513808c3c84382a
2,177
cc
C++
app/demo-rasterizer/RDemoRunner.cc
stognini/celeritas
6c6d72fece6d9e9c6eb6b43f926941137a1b9517
[ "Apache-2.0", "MIT" ]
22
2020-03-31T14:18:22.000Z
2022-01-10T09:43:06.000Z
app/demo-rasterizer/RDemoRunner.cc
mrguilima/celeritas
e61879ee24665664dabe6d12d5dc1cbc529343ae
[ "Apache-2.0", "MIT" ]
261
2020-04-29T15:14:29.000Z
2022-03-31T19:07:14.000Z
app/demo-rasterizer/RDemoRunner.cc
mrguilima/celeritas
e61879ee24665664dabe6d12d5dc1cbc529343ae
[ "Apache-2.0", "MIT" ]
15
2020-05-01T19:47:19.000Z
2021-12-25T06:12:09.000Z
//----------------------------------*-C++-*----------------------------------// // Copyright 2020 UT-Battelle, LLC, and other Celeritas developers. // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: (Apache-2.0 OR MIT) //---------------------------------------------------------------------------// //! \file RDemoRunner.cc //---------------------------------------------------------------------------// #include "RDemoRunner.hh" #include "base/CollectionStateStore.hh" #include "base/Range.hh" #include "base/Stopwatch.hh" #include "base/ColorUtils.hh" #include "comm/Logger.hh" #include "geometry/GeoParams.hh" #include "ImageTrackView.hh" #include "RDemoKernel.hh" using namespace celeritas; namespace demo_rasterizer { //---------------------------------------------------------------------------// /*! * Construct with image parameters */ RDemoRunner::RDemoRunner(SPConstGeo geometry) : geo_params_(std::move(geometry)) { CELER_EXPECT(geo_params_); } //---------------------------------------------------------------------------// /*! * Trace an image. */ void RDemoRunner::operator()(ImageStore* image, int ntimes) const { CELER_EXPECT(image); CollectionStateStore<GeoStateData, MemSpace::device> geo_state( *geo_params_, image->dims()[0]); CELER_LOG(status) << "Tracing geometry"; // do it ntimes+1 as first one tends to be a warm-up run (slightly longer) double sum = 0, time = 0; for (int i = 0; i <= ntimes; ++i) { Stopwatch get_time; trace(geo_params_->device_ref(), geo_state.ref(), image->device_interface()); time = get_time(); CELER_LOG(info) << color_code('x') << "Elapsed " << i << ": " << time << " s" << color_code(' '); if (i > 0) { sum += time; } } if (ntimes > 0) { CELER_LOG(info) << color_code('x') << "\tAverage time: " << sum / ntimes << " s" << color_code(' '); } } //---------------------------------------------------------------------------// } // namespace demo_rasterizer
30.661972
79
0.467157
[ "geometry" ]
8c929f317fa32a940a98aefec275559ca9f27df9
1,082
cpp
C++
hackerrank/practice/mathematics/number_theory/find_the_operations__mb.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
4
2018-06-05T14:15:52.000Z
2022-02-08T05:14:23.000Z
hackerrank/practice/mathematics/number_theory/find_the_operations__mb.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
null
null
null
hackerrank/practice/mathematics/number_theory/find_the_operations__mb.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
1
2018-10-21T11:01:35.000Z
2018-10-21T11:01:35.000Z
// https://www.hackerrank.com/challenges/flip #include "common/linear_algebra/bool/matrix.h" #include "common/linear_algebra/bool/read.h" #include "common/linear_algebra/bool/solve.h" #include "common/linear_algebra/bool/vector.h" #include "common/stl/base.h" using TModular = ModularBool; using TVector = la::VectorBool; using TMatrix = la::MatrixBool; int main_find_the_operations__mb() { unsigned N, D; cin >> N >> D; unsigned NN = N * N; TVector v = la::ReadVectorBool(NN), x(NN); TMatrix M(NN); for (unsigned i = 0; i < NN; ++i) { int i1 = int(i / N), i2 = int(i % N); for (unsigned j = 0; j < NN; ++j) { int j1 = int(j / N), j2 = int(j % N); if (abs(i1 - j1) + abs(i2 - j2) <= int(D)) M.Set(i, j, 1); } } if (la::Solve(M, v, x)) { cout << "Possible" << endl; uint64_t s = 0; for (unsigned i = 0; i < NN; ++i) s += x.GetBit(i); cout << s << endl; for (unsigned i = 0; i < NN; ++i) { if (x.GetBit(i)) cout << i / N << " " << i % N << endl; } } else { cout << "Impossible" << endl; } return 0; }
27.74359
64
0.563771
[ "vector" ]
8c958fb431d1a1401b9cbdbedfaa05bc73ec880d
2,973
cpp
C++
Pi/envelope.cpp
FundCompXbee/XBeeMessenger
f3210077cb82e1597980b33bc6e2f8f9cf7bc042
[ "MIT" ]
1
2016-04-29T22:30:58.000Z
2016-04-29T22:30:58.000Z
Pi/envelope.cpp
FundCompXbee/XBeeMessenger
f3210077cb82e1597980b33bc6e2f8f9cf7bc042
[ "MIT" ]
null
null
null
Pi/envelope.cpp
FundCompXbee/XBeeMessenger
f3210077cb82e1597980b33bc6e2f8f9cf7bc042
[ "MIT" ]
null
null
null
// Team: XBeeMessenger // Course: Fundamentals of Computing II // Assignment: Final Project // Purpose: Implementation of the Envelope class #include "envelope.hpp" #ifdef LOG1 #include "../loggerTesting/log1.h" #else #include "../loggerTesting/log.h" #endif // Private inheritance is utilised to provide a custom // Envelope-specific interface, with the implementation benefits of // jsoncpp's robust library for string inflation and deflation, // construction, deconstruction, and [] operations Envelope::Envelope() { FILELog::ReportingLevel() = FILELog::FromString(/*argv[1] ? argv[1] : */"DEBUG1"); // initializing logger } Envelope::Envelope(std::string str) { FILELog::ReportingLevel() = FILELog::FromString(/*argv[1] ? argv[1] : */"DEBUG1"); // initializing logger FILE_LOG(logDEBUG) << "Attempting to convert '" << str << "' to an envelope."; std::stringstream s(str); Json::operator>>(s,*this); FILE_LOG(logDEBUG) << "Envelope Conversion Complete."; } Envelope::Envelope(std::string server, std::string destination, std::string sender, std::string expression) { setServer(server); setDestination(destination); setSender(sender); setExpression(expression); } // Relies on jsoncpp Envelope::Envelope(const Envelope& src) : Json::Value(src) { } // Efficient move constructors are necessary due to the frequency of // manipulation done to these objects, so the copy & swap idiom is // implemented here and for operator= Envelope::Envelope(Envelope&& temp) : Envelope() { swap(temp); } Envelope& Envelope::operator=(Envelope temp) { swap(temp); return *this; } std::string Envelope::toString() { return this->toStyledString(); } // [] operator overload, which lets you access an key's corresponding value Json::Value& Envelope::operator[](const char* str) { return Json::Value::operator[](str); } // overloading Json:Value:swap fuction void Envelope::swap(Envelope& src) { // catch corrupted data try { FILE_LOG(logDEBUG) << "Trying to swap envelope '"+src.toString()+"'."; if (!src.isObject()) { FILE_LOG(logDEBUG) << "Env is not object, returning"; return; } Json::Value::swap(src); } catch (...) { FILE_LOG(logDEBUG) << "Failed swap envelope, throwing" << std::endl; throw; } } std::string Envelope::getServer() { return (*this)["Server"].asString(); } std::string Envelope::getDestination() { return (*this)["Destination"].asString(); } std::string Envelope::getSender() { return (*this)["Sender"].asString(); } std::string Envelope::getExpression() { return (*this)["Expression"].asString(); } void Envelope::setServer(std::string str) { (*this)["Server"] = str; } void Envelope::setDestination(std::string str) { (*this)["Destination"] = str; } void Envelope::setSender(std::string str) { (*this)["Sender"] = str; } void Envelope::setExpression(std::string str) { (*this)["Expression"] = str; }
24.983193
107
0.674067
[ "object" ]
8c9bebc1cc33ba368dd51922934834b95e9c6669
10,996
hpp
C++
mtvmtl/core/manifold_spd.hpp
pdebus/MTVMTL
65a7754b34d1f6a1e86d15e3c2d4346b9418414f
[ "MIT" ]
3
2017-05-08T12:40:46.000Z
2019-06-02T05:11:01.000Z
mtvmtl/core/manifold_spd.hpp
pdebus/MTVMTL
65a7754b34d1f6a1e86d15e3c2d4346b9418414f
[ "MIT" ]
null
null
null
mtvmtl/core/manifold_spd.hpp
pdebus/MTVMTL
65a7754b34d1f6a1e86d15e3c2d4346b9418414f
[ "MIT" ]
null
null
null
#ifndef TVMTL_MANIFOLD_SPD_HPP #define TVMTL_MANIFOLD_SPD_HPP #include <cmath> #include <complex> #include <iostream> #include <Eigen/Core> #include <Eigen/Sparse> #include <Eigen/SVD> #include <unsupported/Eigen/MatrixFunctions> #include <unsupported/Eigen/KroneckerProduct> //own includes #include "enumerators.hpp" #include "matrix_utils.hpp" namespace tvmtl { // Specialization SPD template <int N> struct Manifold< SPD, N> { public: static const MANIFOLD_TYPE MyType; static const int manifold_dim ; static const int value_dim; // TODO: maybe rename to embedding_dim static const bool non_isometric_embedding; // Scalar type of manifold typedef double scalar_type; typedef double dist_type; typedef std::complex<double> complex_type; typedef std::vector<double> weight_list; // Value Typedef typedef Eigen::Matrix< scalar_type, N, N> value_type; typedef value_type& ref_type; typedef const value_type& cref_type; typedef std::vector<value_type, Eigen::aligned_allocator<value_type> > value_list; // Tangent space typedefs typedef Eigen::Matrix <scalar_type, N * N, N * (N + 1) / 2> tm_base_type; typedef tm_base_type& tm_base_ref_type; // Derivative Typedefs typedef value_type deriv1_type; typedef deriv1_type& deriv1_ref_type; typedef Eigen::Matrix<scalar_type, N*N, N*N> deriv2_type; typedef deriv2_type& deriv2_ref_type; typedef Eigen::Matrix<scalar_type, N * (N + 1) / 2, N * (N + 1) / 2> restricted_deriv2_type; // Manifold distance functions (for IRLS) inline static dist_type dist_squared(cref_type x, cref_type y); inline static void deriv1x_dist_squared(cref_type x, cref_type y, deriv1_ref_type result); inline static void deriv1y_dist_squared(cref_type x, cref_type y, deriv1_ref_type result); inline static void deriv2xx_dist_squared(cref_type x, cref_type y, deriv2_ref_type result); inline static void deriv2xy_dist_squared(cref_type x, cref_type y, deriv2_ref_type result); inline static void deriv2yy_dist_squared(cref_type x, cref_type y, deriv2_ref_type result); // Manifold exponentials und logarithms ( for Proximal point) template <typename DerivedX, typename DerivedY> inline static void exp(const Eigen::MatrixBase<DerivedX>& x, const Eigen::MatrixBase<DerivedY>& y, Eigen::MatrixBase<DerivedX>& result); inline static void log(cref_type x, cref_type y, ref_type result); inline static void convex_combination(cref_type x, cref_type y, double t, ref_type result); // Implementations of the Karcher mean // Slow list version inline static void karcher_mean(ref_type x, const value_list& v, double tol=1e-10, int maxit=15); inline static void weighted_karcher_mean(ref_type x, const weight_list& w, const value_list& v, double tol=1e-10, int maxit=15); // Variadic templated version template <typename V, class... Args> inline static void karcher_mean(V& x, const Args&... args); template <typename V> inline static void variadic_karcher_mean_gradient(V& x, const V& y); template <typename V, class... Args> inline static void variadic_karcher_mean_gradient(V& x, const V& y1, const Args&... args); // Basis transformation for restriction to tangent space inline static void tangent_plane_base(cref_type x, tm_base_ref_type result); // Projection inline static void projector(ref_type x); // Interpolation pre- and postprocessing inline static void interpolation_preprocessing(ref_type x); inline static void interpolation_postprocessing(ref_type x); }; /*-----IMPLEMENTATION SPD----------*/ // Static constants, Outside definition to avoid linker error template <int N> const MANIFOLD_TYPE Manifold < SPD, N>::MyType = SPD; template <int N> const int Manifold < SPD, N>::manifold_dim = N * (N + 1) / 2; template <int N> const int Manifold < SPD, N>::value_dim = N * N; template <int N> const bool Manifold < SPD, N>::non_isometric_embedding = true; // Squared SPD distance function template <int N> inline typename Manifold < SPD, N>::dist_type Manifold < SPD, N>::dist_squared( cref_type x, cref_type y ){ #ifdef TV_SPD_DIST_DEBUG std::cout << "\nDist2 function with x=\n" << x << "\nand y=\n" << y << std::endl; #endif // NOTE: If x is not strictly spd, using LDLT completely halts the algorithm /* value_type sqrtX = x.sqrt(); Eigen::LDLT<value_type> ldlt; ldlt.compute(sqrtX); value_type Z = ldlt.solve(y).transpose(); return ldlt.solve(Z).transpose().log().squaredNorm(); */ value_type invsqrt = x.sqrt().inverse(); return (invsqrt * y * invsqrt).log().squaredNorm(); } // Derivative of Squared SPD distance w.r.t. first argument // TODO: Switch to solve() for N>4? template <int N> inline void Manifold < SPD, N>::deriv1x_dist_squared( cref_type x, cref_type y, deriv1_ref_type result){ value_type invsqrt = x.sqrt().inverse(); result = -2.0 * invsqrt * (invsqrt * y * invsqrt).log() * invsqrt; } // Derivative of Squared SPD distance w.r.t. second argument template <int N> inline void Manifold < SPD, N>::deriv1y_dist_squared( cref_type x, cref_type y, deriv1_ref_type result){ deriv1x_dist_squared(y, x, result); } // Second Derivative of Squared SPD distance w.r.t first argument template <int N> inline void Manifold < SPD, N>::deriv2xx_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){ value_type T2, T3, T4; T2 = x.sqrt().inverse(); T3 = T2 * y * T2; T4 = T3.log(); deriv2_type dlog, dsqrt; KroneckerDLog(T3, dlog); KroneckerDSqrt(x, dsqrt); deriv2_type T2T4tId, IdT2T4, T2T2, T2yId, IdT2y; T2T4tId = Eigen::kroneckerProduct(T2 * T4.transpose(), value_type::Identity()); IdT2T4 = Eigen::kroneckerProduct(value_type::Identity(), T2 * T4); T2T2 = Eigen::kroneckerProduct(T2, T2); T2yId = Eigen::kroneckerProduct(T2 * y, value_type::Identity()); IdT2y = Eigen::kroneckerProduct(value_type::Identity(), T2 * y); result = 2 * (T2T4tId + IdT2T4 + T2T2 * dlog * (T2yId + IdT2y) ) * T2T2 * dsqrt; } // Second Derivative of Squared SPD distance w.r.t first and second argument template <int N> inline void Manifold < SPD, N>::deriv2xy_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){ value_type isqrtX, T1; isqrtX = x.sqrt().eval().inverse(); T1 = isqrtX * y * isqrtX; deriv2_type kp_isqrtX, dlog; kp_isqrtX = Eigen::kroneckerProduct(isqrtX, isqrtX); KroneckerDLog(T1, dlog); result = -2 * kp_isqrtX * dlog * kp_isqrtX; } // Second Derivative of Squared SPD distance w.r.t second argument template <int N> inline void Manifold < SPD, N>::deriv2yy_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){ deriv2xx_dist_squared(y, x, result); } // Exponential and Logarithm Map template <int N> template <typename DerivedX, typename DerivedY> inline void Manifold <SPD, N>::exp(const Eigen::MatrixBase<DerivedX>& x, const Eigen::MatrixBase<DerivedY>& y, Eigen::MatrixBase<DerivedX>& result){ #ifdef TV_SPD_EXP_DEBUG std::cout << "\nEXP function with x=\n" << x << "\nand y=\n" << y << std::endl; #endif value_type sqrtX = x.sqrt(); value_type Z = sqrtX.ldlt().solve(y).transpose(); result = sqrtX * sqrtX.transpose().ldlt().solve(Z).exp() * sqrtX; } template <int N> inline void Manifold <SPD, N>::log(cref_type x, cref_type y, ref_type result){ #ifdef TV_SPD_LOG_DEBUG std::cout << "\nLOG function with x=\n" << x << "\nand y=\n" << y << std::endl; #endif value_type sqrtX = x.sqrt(); value_type Z = sqrtX.ldlt().solve(y).transpose(); result = sqrtX * sqrtX.transpose().ldlt().solve(Z).log() * sqrtX; } // Tangent Plane restriction template <int N> inline void Manifold <SPD, N>::tangent_plane_base(cref_type x, tm_base_ref_type result){ int d = value_type::RowsAtCompileTime; int k = 0; value_type S, T; S = x.sqrt(); for(int i=0; i<d; i++){ T.setZero(); T.col(i) = S.col(i); T = T * S; result.col(k) = Eigen::Map<Eigen::VectorXd>(T.data(), T.size()); ++k; } for(int i=0; i<d-1; i++) for(int j=i+1; j<d; j++){ T.setZero(); T.col(i) = S.col(j); T.col(j) = S.col(i); T = T * S; result.col(k) = Eigen::Map<Eigen::VectorXd>(T.data(), T.size()); ++k; } } template <int N> inline void Manifold <SPD, N>::projector(ref_type x){ // does not exist since SPD is an open set // TODO: Eventually implement projection to semi positive definite matrices } // Convex geodesic combinations template <int N> inline void Manifold <SPD, N>::convex_combination(cref_type x, cref_type y, double t, ref_type result){ value_type l; log(x, y, l); exp(x, l * t, result); } // Karcher mean implementations template <int N> inline void Manifold<SPD, N>::karcher_mean(ref_type x, const value_list& v, double tol, int maxit){ value_type L, temp; int k = 0; double error = 0.0; do{ scalar_type m1 = x.sum(); L = value_type::Zero(); for(int i = 0; i < v.size(); ++i){ log(x, v[i], temp); L += temp; } exp(x, 0.5 / v.size() * (L + L.transpose()), temp); x = temp; error = std::abs(x.sum() - m1); ++k; } while(error > tol && k < maxit); } template <int N> inline void Manifold<SPD, N>::weighted_karcher_mean(ref_type x, const weight_list& w, const value_list& v, double tol, int maxit){ value_type L, temp; int k = 0; double error = 0.0; do{ scalar_type m1 = x.sum(); L = value_type::Zero(); for(int i = 0; i < v.size(); ++i){ log(x, v[i], temp); L += w[i] * temp; } exp(x, 0.5 / v.size() * (L + L.transpose()), temp); x = temp; error = std::abs(x.sum() - m1); ++k; } while(error > tol && k < maxit); } template <int N> template <typename V, class... Args> inline void Manifold<SPD, N>::karcher_mean(V& x, const Args&... args){ V temp, sum; int numArgs = sizeof...(args); int k = 0; double error = 0.0; double tol = 1e-10; int maxit = 15; do{ scalar_type m1 = x.sum(); sum = x; variadic_karcher_mean_gradient(sum, args...); exp(x, 0.5 / numArgs * (sum + sum.transpose()), temp); x = temp; error = std::abs(x.sum() - m1); ++k; } while(error > tol && k < maxit); } template <int N> template <typename V> inline void Manifold<SPD, N>::variadic_karcher_mean_gradient(V& x, const V& y){ V temp; log(x, y, temp); x = temp; } template <int N> template <typename V, class... Args> inline void Manifold<SPD, N>::variadic_karcher_mean_gradient(V& x, const V& y1, const Args& ... args){ V temp1, temp2; temp2 = x; log(x, y1, temp1); variadic_karcher_mean_gradient(temp2, args...); temp1 += temp2; x = temp1; } template <int N> inline void Manifold<SPD, N>::interpolation_preprocessing(ref_type x){ value_type t = x.log(); x = t; } template <int N> inline void Manifold<SPD, N>::interpolation_postprocessing(ref_type x){ value_type t = ( 0.5 * (x + x.transpose()) ).exp(); x = t; } } // end namespace tvmtl #endif
30.208791
148
0.677701
[ "vector" ]
8ca14daee00d319dd86b8f13fcbf19a7febaf4d4
2,262
cpp
C++
CodeForces-Contest/620/E.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
1
2022-01-23T07:18:07.000Z
2022-01-23T07:18:07.000Z
CodeForces-Contest/620/E.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
null
null
null
CodeForces-Contest/620/E.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
1
2022-02-05T11:53:04.000Z
2022-02-05T11:53:04.000Z
#include<bits/stdc++.h> using namespace std; const int N = 4e5 + 9; int a[N]; int st[N], en[N], T, f[N]; struct ST { #define lc (n << 1) #define rc ((n << 1) | 1) long long t[4 * N], lazy[4 * N]; ST() { memset(t, 0, sizeof t); memset(lazy, 0, sizeof lazy); } inline void push(int n, int b, int e) { if (lazy[n] == 0) return; t[n] = 1LL << lazy[n]; if (b != e) { lazy[lc] = lazy[n]; lazy[rc] = lazy[n]; } lazy[n] = 0; } inline long long combine(long long a,long long b) { return a | b; } inline void pull(int n) { t[n] = t[lc] | t[rc]; } void build(int n, int b, int e) { lazy[n] = 0; if (b == e) { t[n] = 1LL << a[f[b]]; return; } int mid = (b + e) >> 1; build(lc, b, mid); build(rc, mid + 1, e); pull(n); } void upd(int n, int b, int e, int i, int j, long long v) { push(n, b, e); if (j < b || e < i) return; if (i <= b && e <= j) { lazy[n] = v; //set lazy push(n, b, e); return; } int mid = (b + e) >> 1; upd(lc, b, mid, i, j, v); upd(rc, mid + 1, e, i, j, v); pull(n); } long long query(int n, int b, int e, int i, int j) { push(n, b, e); if (i > e || b > j) return 0; //return null if (i <= b && e <= j) return t[n]; int mid = (b + e) >> 1; return combine(query(lc, b, mid, i, j), query(rc, mid + 1, e, i, j)); } }t; vector<int> g[N]; void dfs(int u, int p = 0) { st[u] = ++T; f[T] = u; for (auto v: g[u]) { if (v ^ p) { dfs(v, u); } } en[u] = T; } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, m; cin >> n >> m; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i < n; i++) { int u, v; cin >> u >> v; g[u].push_back(v); g[v].push_back(u); } dfs(1); t.build(1, 1, T); while (m--) { int ty, u; cin >> ty >> u; if (ty == 1) { int k; cin >> k; t.upd(1, 1, T, st[u], en[u], k); } else { auto x = t.query(1, 1, T, st[u], en[u]); cout << __builtin_popcountll(x) << '\n'; } } return 0; }
22.848485
77
0.407604
[ "vector" ]
8cae88091cf5f7eadc48e37b6ea0934da3bd0e37
1,198
cpp
C++
list/300-longest-increasing-subsequence/300-longest-increasing-subsequence-path1.cpp
ZonePG/my-leetcode-solution
9efa4c19e4c9be9f47b5f5d4e9a47fceae26e0bb
[ "MIT" ]
null
null
null
list/300-longest-increasing-subsequence/300-longest-increasing-subsequence-path1.cpp
ZonePG/my-leetcode-solution
9efa4c19e4c9be9f47b5f5d4e9a47fceae26e0bb
[ "MIT" ]
null
null
null
list/300-longest-increasing-subsequence/300-longest-increasing-subsequence-path1.cpp
ZonePG/my-leetcode-solution
9efa4c19e4c9be9f47b5f5d4e9a47fceae26e0bb
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> lengthOfLIS(vector<int> &nums) { int max_length_id = 0; vector<vector<int>> path(nums.size(), vector<int>()); for (int i = 0; i < nums.size(); i++) { path[i].push_back(nums[i]); } for (int i = 1; i < nums.size(); i++) { for (int j = 0; j < i; j++) { if (nums[i] > nums[j]) { if (path[i].size() < path[j].size() + 1) { path[i].clear(); path[i].insert(path[i].begin(), path[j].begin(), path[j].end()); path[i].push_back(nums[i]); if (path[i].size() > path[max_length_id].size()) { max_length_id = i; } } } } } for (int i = 0; i < nums.size(); i++) { for (int j = 0; j < path[i].size(); j++) { cout << path[i][j] << " "; } cout << endl; } return path[max_length_id]; } }; int main() { vector<int> nums{10, 9, 2, 5, 3, 7, 101, 18}; Solution solution; auto res = solution.lengthOfLIS(nums); for (int i = 0; i < res.size(); i++) { cout << res[i] << " "; } cout << endl; }
23.96
76
0.474124
[ "vector" ]
8cb7f4c92acab348e2720e6d4f808cbde6e809d9
1,311
cpp
C++
hard/0042trappingRainWater.cpp
wanghengg/LeetCode
4f73d7e176c8de5d2d9b87ab2812f7aa80c20a79
[ "Apache-2.0" ]
null
null
null
hard/0042trappingRainWater.cpp
wanghengg/LeetCode
4f73d7e176c8de5d2d9b87ab2812f7aa80c20a79
[ "Apache-2.0" ]
null
null
null
hard/0042trappingRainWater.cpp
wanghengg/LeetCode
4f73d7e176c8de5d2d9b87ab2812f7aa80c20a79
[ "Apache-2.0" ]
null
null
null
// // Created by wangheng on 2021/9/7. // #include <bits/stdc++.h> using namespace std; class Solution{ public: int trap(vector<int>& height) { stack<int> stk; int ans = 0; int n = height.size(); for(int i = 0; i < n; ++i) { while (!stk.empty() && height[i] > height[stk.top()]) { int top = stk.top(); stk.pop(); if (stk.empty()) break; int left = stk.top(); int curWidth = i - left - 1; int curHeight = min(height[left], height[i]) - height[top]; ans += curWidth * curHeight; } stk.push(i); } return ans; } }; class Solution1{ public: int trap(vector<int>& height) { stack<int> stk; int ans = 0; int leftMax = 0, rightMax = 0; int left = 0, right = height.size() - 1; while(left < right) { leftMax = max(height[left], leftMax); rightMax = max(height[right], rightMax); if (height[left] < height[right]) { ans += leftMax - height[left]; ++left; } else { ans += rightMax - height[right]; --right; } } return ans; } };
26.22
75
0.440122
[ "vector" ]
8cbc574656ce7c6f79030d952d0dfb20e2886f64
1,973
hh
C++
hackt_docker/hackt/src/Object/unroll/instance_attribute_registry.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/unroll/instance_attribute_registry.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/unroll/instance_attribute_registry.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
/** \file "Object/unroll/instance_attribute_registry.hh" The home of instance attribute registries, a tcc file. By putting these definitions separate from "instance_attribute.tcc" we can control where these static map members are instantiated. $Id: instance_attribute_registry.hh,v 1.1 2008/10/07 03:22:32 fang Exp $ */ #include <iostream> #include "Object/unroll/instance_attribute.hh" // #include "Object/expr/const_param_expr_list.hh" // #include "Object/inst/instance_alias_info.hh" namespace HAC { namespace entity { #include "util/using_ostream.hh" /** Macro to instantiate attribute registry map. */ #define INSTANTIATE_INSTANCE_ATTRIBUTE_REGISTRY(Tag) \ template instance_attribute<Tag>::attribute_registry_type \ instance_attribute<Tag>::attribute_registry; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - INSTANCE_ATTRIBUTE_TEMPLATE_SIGNATURE typename INSTANCE_ATTRIBUTE_CLASS::attribute_registry_type INSTANCE_ATTRIBUTE_CLASS::attribute_registry; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - INSTANCE_ATTRIBUTE_TEMPLATE_SIGNATURE template <class T> size_t INSTANCE_ATTRIBUTE_CLASS::register_attribute_functions(void) { // typedef typename attribute_registry_type::iterator iterator; typedef typename attribute_registry_type::mapped_type mapped_type; const string k(T::name); mapped_type& m(attribute_registry[k]); if (m) { cerr << "Error: " << traits_type::tag_name << " instance attribute by the name \'" << k << "\' has already been registered!" << endl; THROW_EXIT; } m = attribute_funcs_type(k, &T::main, &T::check_vals); // oddly, this is needed to force instantiation of the [] const operator const mapped_type& n __ATTRIBUTE_UNUSED_CTOR__((attribute_registry[k])); INVARIANT(n); return attribute_registry.size(); } //============================================================================= } // end namespace entity } // end namespace HAC
34.614035
79
0.682717
[ "object" ]
8cbcf4598fd3423fa163c0ebfed5d9b88a55bc21
8,067
cpp
C++
src/linux_parser.cpp
mehmetalici/LinuxSystemMonitor
b6f34e1b549b52f02efd9442dfb577637c69faba
[ "MIT" ]
null
null
null
src/linux_parser.cpp
mehmetalici/LinuxSystemMonitor
b6f34e1b549b52f02efd9442dfb577637c69faba
[ "MIT" ]
null
null
null
src/linux_parser.cpp
mehmetalici/LinuxSystemMonitor
b6f34e1b549b52f02efd9442dfb577637c69faba
[ "MIT" ]
null
null
null
#include <dirent.h> #include <unistd.h> #include <sstream> #include <string> #include <vector> #include <iostream> #include <map> #include <experimental/filesystem> #include "linux_parser.h" using std::stof; using std::string; using std::to_string; using std::vector; namespace fs = std::experimental::filesystem; // An example of how to read data from the filesystem string LinuxParser::OperatingSystem() { string line; string key; string value; std::ifstream filestream(kOSPath); if (filestream.is_open()) { while (std::getline(filestream, line)) { std::replace(line.begin(), line.end(), ' ', '_'); std::replace(line.begin(), line.end(), '=', ' '); std::replace(line.begin(), line.end(), '"', ' '); std::istringstream linestream(line); while (linestream >> key >> value) { if (key == "PRETTY_NAME") { std::replace(value.begin(), value.end(), '_', ' '); return value; } } } } return value; } // DONE: An example of how to read data from the filesystem string LinuxParser::Kernel() { string os, kernel, version; string line; std::ifstream stream(kProcDirectory + kVersionFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); linestream >> os >> version >> kernel; } return kernel; } // BONUS: Update this to use std::filesystem vector<int> LinuxParser::Pids() { vector<int> pids; DIR* directory = opendir(kProcDirectory.c_str()); struct dirent* file; while ((file = readdir(directory)) != nullptr) { // Is this a directory? if (file->d_type == DT_DIR) { // Is every character of the name a digit? string filename(file->d_name); if (std::all_of(filename.begin(), filename.end(), isdigit)) { int pid = stoi(filename); pids.push_back(pid); } } } closedir(directory); return pids; } // Read and return the system memory utilization float LinuxParser::MemoryUtilization() { vector<int> mem_elts(4); string line; std::ifstream stream(kProcDirectory + kMeminfoFilename); if (stream.is_open()) { for (auto& elt : mem_elts) { std::getline(stream, line); std::istringstream linestream(line); linestream.ignore(256, ' '); linestream >> elt; } } // For readibility: int mem_total = mem_elts[0]; // int mem_free = mem_elts[1]; int mem_available = mem_elts[2]; // int buffers = mem_elts[3]; int mem_used = mem_total - mem_available; return mem_used / (float) mem_total; } // Read and return the system uptime long LinuxParser::UpTime() { string line, uptime; std::ifstream stream(kProcDirectory + kUptimeFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); linestream >> uptime; } return (long) std::stoi(uptime); } // Read and return the number of jiffies for the system long LinuxParser::Jiffies() { return ActiveJiffies() + IdleJiffies(); } // Read and return the number of active jiffies for a PID // REMOVE: [[maybe_unused]] once you define the function long LinuxParser::ActiveJiffies(int pid) { string line, token; string utime, stime, cutime, cstime, starttime; std::ifstream stream(kProcDirectory + std::to_string(pid) + kStatFilename); constexpr int UNTIL_JIFFIES = 13; if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); for(int i = 0; i < UNTIL_JIFFIES; i++) linestream >> token; linestream >> utime >> stime >> cutime >> cstime; } return std::stoi(utime) + std::stoi(stime) + std::stoi(cutime) + std::stoi(cstime); } // Read and return the number of active jiffies for the system long LinuxParser::ActiveJiffies() { vector<string> cpu_utilization_as_str = CpuUtilization(); vector<int> cpu_utilization; for (auto const& u : cpu_utilization_as_str) { cpu_utilization.push_back(std::stoi(u)); } return cpu_utilization[kUser_] + cpu_utilization[kNice_] + cpu_utilization[kSystem_] + cpu_utilization[kIRQ_] + cpu_utilization[kSoftIRQ_] + cpu_utilization[kSteal_]; } // Read and return the number of idle jiffies for the system long LinuxParser::IdleJiffies() { vector<string> cpu_utilization = CpuUtilization(); return std::stoi(cpu_utilization[kIdle_]) + std::stoi(cpu_utilization[kIOwait_]); } // Read and return CPU utilization vector<string> LinuxParser::CpuUtilization() { vector<string> cpu_utilizations(10); string line, cpu; std::ifstream stream(kProcDirectory + kStatFilename); std::getline(stream, line); std::istringstream linestream(line); linestream >> cpu; for (auto& utilization : cpu_utilizations){ linestream >> utilization; } return cpu_utilizations; } // Read and return the total number of processes int LinuxParser::TotalProcesses() { string line, first_word; int total_processes{0}; std::ifstream stream(kProcDirectory + kStatFilename); if (stream.is_open()){ while (std::getline(stream, line)){ std::istringstream linestream(line); linestream >> first_word; if (first_word == "processes"){ linestream >> total_processes; break; } } } return total_processes; } // Read and return the number of running processes int LinuxParser::RunningProcesses() { string line, key; int procs_running{0}; std::ifstream stream(kProcDirectory + kStatFilename); if (stream.is_open()){ while(std::getline(stream, line)) { std::istringstream linestream(line); linestream >> key; if (key == "procs_running"){ linestream >> procs_running; } } } return procs_running; } // Read and return the command associated with a process string LinuxParser::Command(int pid) { std::ifstream stream(kProcDirectory + std::to_string(pid) + kCmdlineFilename); string line; if (stream.is_open()) { std::getline(stream, line); } return line; } // Read and return the memory used by a process string LinuxParser::Ram(int pid) { std::ifstream stream(kProcDirectory + std::to_string(pid) + kStatusFilename); string line, first_word, mem_util{"0"}; int mem_usg_in_mb{0}; if (stream.is_open()) { while (std::getline(stream, line)){ std::istringstream linestream(line); linestream >> first_word; if (first_word == "VmData:") { linestream >> mem_util; } } } mem_usg_in_mb = std::stoi(mem_util) / (float) 1024; return std::to_string(mem_usg_in_mb); } // Read and return the user ID associated with a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::Uid(int pid) { std::ifstream stream(kProcDirectory + std::to_string(pid) + kStatusFilename); string line, key, uid; if (stream.is_open()) { while (std::getline(stream, line)) { std::istringstream linestream(line); linestream >> key; if (key == "Uid:") { linestream >> uid; break; } } } return uid; } // Read and return the user associated with a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::User(int pid) { std::ifstream stream(kPasswordPath); string uid_desired = Uid(pid); string line, uname, passwd, uid; if (stream.is_open()) { while (std::getline(stream, line)){ std::replace(line.begin(), line.end(), ':', ' '); std::istringstream linestream(line); linestream >> uname >> passwd >> uid; if (uid == uid_desired) { break; } } } return uname; } // Read and return the uptime of a process long LinuxParser::UpTime(int pid) { std::ifstream stream(kProcDirectory + std::to_string(pid) + kStatFilename); string line, token, uptime; constexpr int UNTIL_UPTIME = 21; if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); for (int i = 0; i < UNTIL_UPTIME; i++) linestream >> token; linestream >> uptime; } int upTimePid = UpTime() - stol(uptime)/sysconf(_SC_CLK_TCK); return upTimePid; }
28.305263
89
0.66394
[ "vector" ]
8cbd9bf6ed15fd6fe6a92499a0064bcc138b56a9
505
cc
C++
pascalsTriangleII.cc
zxylvlp/MyLeetCode
7b2fe7a5f6515c365b903511d87e6879c0b62734
[ "MIT" ]
1
2015-11-16T05:06:10.000Z
2015-11-16T05:06:10.000Z
pascalsTriangleII.cc
zxylvlp/MyLeetCode
7b2fe7a5f6515c365b903511d87e6879c0b62734
[ "MIT" ]
null
null
null
pascalsTriangleII.cc
zxylvlp/MyLeetCode
7b2fe7a5f6515c365b903511d87e6879c0b62734
[ "MIT" ]
null
null
null
#include <vector> #include "printHelper.hh" using namespace std; class Solution { public: vector<int> getRow(int rowIndex) { vector<int> res(rowIndex+1, 1); for (int i=2; i<=rowIndex; i++) { for (int j=(rowIndex-i+1); j<rowIndex; j++) { res[j] = res[j] + res[j+1]; } } return res; } }; int main(void) { Solution sl; auto res = sl.getRow(3); printVec(res); }
21.041667
61
0.459406
[ "vector" ]
8cc5c291bd984a35b070eec3389d705e50577056
16,420
cxx
C++
smtk/mesh/MeshSet.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
smtk/mesh/MeshSet.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
4
2016-11-10T15:49:51.000Z
2017-02-06T23:24:16.000Z
smtk/mesh/MeshSet.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #include "smtk/mesh/MeshSet.h" #include "smtk/mesh/Collection.h" #include "smtk/mesh/Interface.h" namespace smtk { namespace mesh { //---------------------------------------------------------------------------- MeshSet::MeshSet(): m_parent(), m_handle(), m_range() { //Trying to make Shitbroken happy } //---------------------------------------------------------------------------- MeshSet::MeshSet(const smtk::mesh::CollectionPtr& parent, smtk::mesh::Handle handle) { this->m_parent = parent; this->m_handle = handle; const smtk::mesh::InterfacePtr& iface = parent->interface(); //range of moab entity sets this->m_range = iface->getMeshsets( handle ); } //---------------------------------------------------------------------------- MeshSet::MeshSet(const smtk::mesh::CollectionPtr& parent, smtk::mesh::Handle handle, const smtk::mesh::HandleRange& range): m_parent(parent), m_handle(handle), m_range(range) //range of moab entity sets { } //---------------------------------------------------------------------------- MeshSet::MeshSet(const smtk::mesh::MeshSet& other): m_parent(other.m_parent), m_handle(other.m_handle), m_range(other.m_range) { } //---------------------------------------------------------------------------- MeshSet::~MeshSet() { } //---------------------------------------------------------------------------- MeshSet& MeshSet::operator=(const MeshSet& other) { this->m_parent = other.m_parent; this->m_handle = other.m_handle; this->m_range = other.m_range; return *this; } //---------------------------------------------------------------------------- bool MeshSet::operator==(const MeshSet& other) const { return this->m_parent == other.m_parent && this->m_handle == other.m_handle && //empty is a fast way to check for easy mismatching ranges this->m_range.empty() == other.m_range.empty() && this->m_range == other.m_range; } //---------------------------------------------------------------------------- bool MeshSet::operator!=(const MeshSet& other) const { return !(*this == other); } //---------------------------------------------------------------------------- bool MeshSet::operator<(const MeshSet& other) const { const std::size_t myLen = this->m_range.size(); const std::size_t otherLen = other.size(); //only when the number of elements in the two meshsets are equal do //we need to do a complex less than comparison if(myLen == otherLen) { //next we look at psize which is the number of pairs inside the range const std::size_t myPLen = this->m_range.psize(); const std::size_t otherPLen = other.m_range.psize(); if(myPLen == otherPLen) { //we now have two handle ranges with same number of values, and //the same number of pairs. Now we need smtk::mesh::HandleRange::const_pair_iterator i, j; i = this->m_range.const_pair_begin(); j = other.m_range.const_pair_begin(); for ( ; i != this->m_range.const_pair_end(); ++i, ++j) { if (i->first != j->first) { return i->first < j->first; } else if(i->second != j->second) { return i->second < j->second; } } //we looped over the entire set and everything was equal, so therefore //the two ranges must be equal return false; } //prefer less pair sets over more pair sets for less than operator return myPLen < otherPLen; } //prefer smaller lengths over larger for less than operator return myLen < otherLen; } //---------------------------------------------------------------------------- bool MeshSet::append( const MeshSet& other) { const bool can_append = this->m_parent == other.m_parent && this->m_handle == other.m_handle; if(can_append) { this->m_range.insert(other.m_range.begin(), other.m_range.end()); } return can_append; } //---------------------------------------------------------------------------- bool MeshSet::is_empty( ) const { return this->m_range.empty(); } //---------------------------------------------------------------------------- std::size_t MeshSet::size( ) const { return this->m_range.size(); } //---------------------------------------------------------------------------- std::vector< smtk::mesh::Domain > MeshSet::domains( ) const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); return iface->computeDomainValues( this->m_range ); } //---------------------------------------------------------------------------- std::vector< smtk::mesh::Dirichlet > MeshSet::dirichlets( ) const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); return iface->computeDirichletValues( this->m_range ); } //---------------------------------------------------------------------------- std::vector< smtk::mesh::Neumann > MeshSet::neumanns( ) const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); return iface->computeNeumannValues( this->m_range ); } //---------------------------------------------------------------------------- bool MeshSet::setDomain(const smtk::mesh::Domain& d) { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); return iface->setDomain( this->m_range, d); } //---------------------------------------------------------------------------- bool MeshSet::setDirichlet(const smtk::mesh::Dirichlet& d) { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); return iface->setDirichlet( this->m_range, d ); } //---------------------------------------------------------------------------- bool MeshSet::setNeumann(const smtk::mesh::Neumann& n) { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); return iface->setNeumann( this->m_range, n ); } /**\brief Return an array of model entity UUIDs associated with meshset members. * */ smtk::common::UUIDArray MeshSet::modelEntityIds() const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); return iface->computeModelEntities(this->m_range); } /**\brief Return the model entities associated with meshset members. * * warning Note that the parent collection of this meshset must have * its model manager set to a valid value or the result will * be an array of invalid entries. */ smtk::model::EntityRefArray MeshSet::modelEntities() const { smtk::common::UUIDArray uids = this->modelEntityIds(); smtk::model::EntityRefArray result; smtk::model::ManagerPtr mgr = this->m_parent->modelManager(); for (smtk::common::UUIDArray::const_iterator it = uids.begin(); it != uids.end(); ++it) result.push_back(smtk::model::EntityRef(mgr, *it)); return result; } /**\brief Set the model entity for each meshset member to \a ent. * */ bool MeshSet::setModelEntity(const smtk::model::EntityRef& ent) { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); return iface->setAssociation(ent.entity(), this->m_range); } /**\brief Get the parent collection that this meshset belongs to. * */ const smtk::mesh::CollectionPtr& MeshSet::collection() const { return this->m_parent; } //---------------------------------------------------------------------------- std::vector< std::string > MeshSet::names( ) const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); return iface->computeNames( this->m_range ); } //---------------------------------------------------------------------------- smtk::mesh::TypeSet MeshSet::types() const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); return iface->computeTypes( this->m_range ); } //---------------------------------------------------------------------------- smtk::mesh::CellSet MeshSet::cells( ) const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); smtk::mesh::HandleRange range = iface->getCells( this->m_range ); return smtk::mesh::CellSet(this->m_parent, range); } //---------------------------------------------------------------------------- smtk::mesh::PointSet MeshSet::points( ) const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); smtk::mesh::HandleRange cells = iface->getCells( this->m_range ); smtk::mesh::HandleRange range = iface->getPoints( cells ); return smtk::mesh::PointSet(this->m_parent, range); } //---------------------------------------------------------------------------- smtk::mesh::PointConnectivity MeshSet::pointConnectivity( ) const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); smtk::mesh::HandleRange range = iface->getCells( this->m_range ); return smtk::mesh::PointConnectivity(this->m_parent, range); } //---------------------------------------------------------------------------- smtk::mesh::CellSet MeshSet::cells( smtk::mesh::CellType cellType ) const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); smtk::mesh::HandleRange range = iface->getCells( this->m_range, cellType ); return smtk::mesh::CellSet(this->m_parent, range); } //---------------------------------------------------------------------------- smtk::mesh::CellSet MeshSet::cells( smtk::mesh::CellTypes cellTypes ) const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); smtk::mesh::HandleRange range = iface->getCells( this->m_range, cellTypes ); return smtk::mesh::CellSet(this->m_parent, range); } //---------------------------------------------------------------------------- smtk::mesh::CellSet MeshSet::cells( smtk::mesh::DimensionType dim ) const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); smtk::mesh::HandleRange range = iface->getCells( this->m_range, dim ); return smtk::mesh::CellSet(this->m_parent, range); } //---------------------------------------------------------------------------- smtk::mesh::MeshSet MeshSet::subset( smtk::mesh::DimensionType dim ) const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); smtk::mesh::HandleRange dimMeshes = iface->getMeshsets(this->m_handle, dim); //intersect our mesh id with those of a given dimension to find the subset return smtk::mesh::MeshSet(this->m_parent, this->m_handle, iface->rangeIntersect(dimMeshes,this->m_range)); } //---------------------------------------------------------------------------- smtk::mesh::MeshSet MeshSet::subset( const smtk::mesh::Domain& d ) const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); smtk::mesh::HandleRange dMeshes = iface->getMeshsets(this->m_handle, d); //intersect our mesh id with those of a given dimension to find the subset return smtk::mesh::MeshSet(this->m_parent, this->m_handle, iface->rangeIntersect(dMeshes,this->m_range)); } //---------------------------------------------------------------------------- smtk::mesh::MeshSet MeshSet::subset( const smtk::mesh::Dirichlet& d ) const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); smtk::mesh::HandleRange dMeshes = iface->getMeshsets(this->m_handle, d); //intersect our mesh id with those of a given dimension to find the subset return smtk::mesh::MeshSet(this->m_parent, this->m_handle, iface->rangeIntersect(dMeshes,this->m_range)); } //---------------------------------------------------------------------------- smtk::mesh::MeshSet MeshSet::subset( const smtk::mesh::Neumann& n ) const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); smtk::mesh::HandleRange nMeshes = iface->getMeshsets(this->m_handle, n); //intersect our mesh id with those of a given dimension to find the subset return smtk::mesh::MeshSet(this->m_parent, this->m_handle, iface->rangeIntersect(nMeshes,this->m_range)); } //---------------------------------------------------------------------------- smtk::mesh::MeshSet MeshSet::subset( std::size_t ith ) const { smtk::mesh::HandleRange singlHandleRange; if(!this->m_range.empty() && ith < this->m_range.size()) { smtk::mesh::HandleRange::const_iterator cit = this->m_range.begin(); cit += ith; singlHandleRange.insert(*cit); } smtk::mesh::MeshSet singleMesh(this->m_parent,this->m_handle,singlHandleRange); return singleMesh; } //---------------------------------------------------------------------------- smtk::mesh::MeshSet MeshSet::extractShell() const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); smtk::mesh::HandleRange entities; smtk::mesh::HandleRange cells; const bool shellExtracted = iface->computeShell( this->m_range, cells ); if(shellExtracted) { smtk::mesh::Handle meshSetHandle; //create a mesh for these cells since they don't have a meshset currently const bool meshCreated = iface->createMesh(cells, meshSetHandle); if(meshCreated) { entities.insert(meshSetHandle); } } return smtk::mesh::MeshSet( this->m_parent, this->m_handle, entities ); } //---------------------------------------------------------------------------- bool MeshSet::mergeCoincidentContactPoints( double tolerance ) const { const smtk::mesh::InterfacePtr& iface = this->m_parent->interface(); return iface->mergeCoincidentContactPoints(this->m_range, tolerance); } //---------------------------------------------------------------------------- //intersect two mesh sets, placing the results in the return mesh set MeshSet set_intersect( const MeshSet& a, const MeshSet& b) { if( a.m_parent != b.m_parent ) { //return an empty MeshSet if the collections don't match return smtk::mesh::MeshSet(a.m_parent, a.m_handle, smtk::mesh::HandleRange()); } const smtk::mesh::InterfacePtr& iface = a.m_parent->interface(); smtk::mesh::HandleRange result = iface->rangeIntersect(a.m_range, b.m_range); return smtk::mesh::MeshSet(a.m_parent, a.m_handle, result); } //---------------------------------------------------------------------------- //subtract mesh b from a, placing the results in the return mesh set MeshSet set_difference( const MeshSet& a, const MeshSet& b) { if( a.m_parent != b.m_parent ) { //return an empty MeshSet if the collections don't match return smtk::mesh::MeshSet(a.m_parent, a.m_handle, smtk::mesh::HandleRange()); } const smtk::mesh::InterfacePtr& iface = a.m_parent->interface(); smtk::mesh::HandleRange result = iface->rangeDifference(a.m_range, b.m_range); return smtk::mesh::MeshSet(a.m_parent, a.m_handle, result); } //---------------------------------------------------------------------------- //union two mesh sets, placing the results in the return mesh set MeshSet set_union( const MeshSet& a, const MeshSet& b ) { if( a.m_parent != b.m_parent ) { //return an empty MeshSet if the collections don't match return smtk::mesh::MeshSet(a.m_parent, a.m_handle, smtk::mesh::HandleRange()); } const smtk::mesh::InterfacePtr& iface = a.m_parent->interface(); smtk::mesh::HandleRange result = iface->rangeUnion(a.m_range, b.m_range); return smtk::mesh::MeshSet(a.m_parent, a.m_handle, result); } //---------------------------------------------------------------------------- SMTKCORE_EXPORT void for_each(const MeshSet& a, MeshForEach &filter) { const smtk::mesh::InterfacePtr& iface = a.m_parent->interface(); filter.m_collection=a.m_parent; iface->meshForEach(a.m_range, filter); } } }
35.929978
89
0.544884
[ "mesh", "vector", "model" ]
8cc60fec69f17f9d09025c53f556bd5a3b37dc08
3,288
cpp
C++
platform/windows/Corona.Native.Library.Win32/Rtt/Rtt_WinScreenSurface.cpp
pouwelsjochem/corona
86ffe9002e42721b4bb2c386024111d995e7b27c
[ "MIT" ]
null
null
null
platform/windows/Corona.Native.Library.Win32/Rtt/Rtt_WinScreenSurface.cpp
pouwelsjochem/corona
86ffe9002e42721b4bb2c386024111d995e7b27c
[ "MIT" ]
null
null
null
platform/windows/Corona.Native.Library.Win32/Rtt/Rtt_WinScreenSurface.cpp
pouwelsjochem/corona
86ffe9002e42721b4bb2c386024111d995e7b27c
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: support@coronalabs.com // ////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Rtt_WinScreenSurface.h" #include "Core\Rtt_Build.h" #include "Interop\UI\RenderSurfaceControl.h" #include "Interop\UI\Window.h" #include "Interop\MDeviceSimulatorServices.h" #include "Interop\RuntimeEnvironment.h" #include "Rtt_NativeWindowMode.h" namespace Rtt { WinScreenSurface::WinScreenSurface(Interop::RuntimeEnvironment& environment) : Super(), fEnvironment(environment), fPreviousClientWidth(0), fPreviousClientHeight(0) { } WinScreenSurface::~WinScreenSurface() { } void WinScreenSurface::SetCurrent() const { auto surfaceControlPointer = fEnvironment.GetRenderSurface(); if (surfaceControlPointer) { surfaceControlPointer->SelectRenderingContext(); } } void WinScreenSurface::Flush() const { auto surfaceControlPointer = fEnvironment.GetRenderSurface(); if (surfaceControlPointer) { surfaceControlPointer->SwapBuffers(); } } S32 WinScreenSurface::Width() const { // Return zero if we do not have a surface to render to. auto renderSurfacePointer = fEnvironment.GetRenderSurface(); if (!renderSurfacePointer) { return 0; } // Fetch the surface's client width in pixels. int width = 0; auto windowPointer = fEnvironment.GetMainWindow(); if (windowPointer && windowPointer->GetWindowMode().Equals(Rtt::NativeWindowMode::kMinimized)) { // The window hosting the surface has been minimized, causing the client area to have a zero width/height. // Use the client length before it was minimized to avoid triggering an unnecessary "resize" event in Corona. width = fPreviousClientWidth; } else { // Fetch the requested length and store it in case the window gets minimized later. width = renderSurfacePointer->GetClientWidth(); fPreviousClientWidth = width; } // Corona's rendering system will assert if given a zero length. So, floor it to 1. if (width <= 0) { width = 1; } return width; } S32 WinScreenSurface::Height() const { // Return zero if we do not have a surface to render to. auto renderSurfacePointer = fEnvironment.GetRenderSurface(); if (!renderSurfacePointer) { return 0; } // Fetch the surface's client height in pixels. int height = 0; auto windowPointer = fEnvironment.GetMainWindow(); if (windowPointer && windowPointer->GetWindowMode().Equals(Rtt::NativeWindowMode::kMinimized)) { // The window hosting the surface has been minimized, causing the client area to have a zero width/height. // Use the client length before it was minimized to avoid triggering an unnecessary "resize" event in Corona. height = fPreviousClientHeight; } else { // Fetch the requested length and store it in case the window gets minimized later. height = renderSurfacePointer->GetClientHeight(); fPreviousClientHeight = height; } // Corona's rendering system will assert if given a zero length. So, floor it to 1. if (height <= 0) { height = 1; } return height; } } // namespace Rtt
26.95082
111
0.712591
[ "render" ]
8cc7e98dfc99a60d8be4e4e3a8f28644bc291255
13,012
cpp
C++
Scheduler/CoinOR/examplesMakefiles/CbcBranchUser.cpp
enyquist/Concordia_Scheduling
5eb96ed585e7f2002983159b8ee0837b791753fa
[ "MIT" ]
null
null
null
Scheduler/CoinOR/examplesMakefiles/CbcBranchUser.cpp
enyquist/Concordia_Scheduling
5eb96ed585e7f2002983159b8ee0837b791753fa
[ "MIT" ]
null
null
null
Scheduler/CoinOR/examplesMakefiles/CbcBranchUser.cpp
enyquist/Concordia_Scheduling
5eb96ed585e7f2002983159b8ee0837b791753fa
[ "MIT" ]
null
null
null
// $Id: CbcBranchUser.cpp 1574 2011-01-05 01:13:55Z lou $ // Copyright (C) 2002, International Business Machines // Corporation and others. All Rights Reserved. // This code is licensed under the terms of the Eclipse Public License (EPL). #if defined(_MSC_VER) // Turn off compiler warning about long names # pragma warning(disable:4786) #endif #include <cassert> #include <cmath> #include <cfloat> #include "OsiSolverInterface.hpp" #include "CbcModel.hpp" #include "CbcMessage.hpp" #include "CbcBranchUser.hpp" #include "CoinSort.hpp" // Default Constructor // Default Constructor CbcBranchUserDecision::CbcBranchUserDecision() :CbcBranchDecision() { } // Copy constructor CbcBranchUserDecision::CbcBranchUserDecision ( const CbcBranchUserDecision & rhs) :CbcBranchDecision(rhs) { } CbcBranchUserDecision::~CbcBranchUserDecision() { } // Clone CbcBranchDecision * CbcBranchUserDecision::clone() const { return new CbcBranchUserDecision(*this); } // Initialize i.e. before start of choosing at a node void CbcBranchUserDecision::initialize(CbcModel * model) { } /* Returns nonzero if branching on first object is "better" than on second (if second NULL first wins). User can play with decision object. This is only used after strong branching. The initial selection is done by infeasibility() for each CbcObject return code +1 for up branch preferred, -1 for down */ int CbcBranchUserDecision::betterBranch(CbcBranchingObject * thisOne, CbcBranchingObject * bestSoFar, double changeUp, int numberInfeasibilitiesUp, double changeDown, int numberInfeasibilitiesDown) { printf("Now obsolete CbcBranchUserDecision::betterBranch\n"); abort(); return 0; } /* Compare N branching objects. Return index of best and sets way of branching in chosen object. This routine is used only after strong branching. This is reccommended version as it can be more sophisticated */ int CbcBranchUserDecision::bestBranch (CbcBranchingObject ** objects, int numberObjects, int numberUnsatisfied, double * changeUp, int * numberInfeasibilitiesUp, double * changeDown, int * numberInfeasibilitiesDown, double objectiveValue) { int bestWay=0; int whichObject = -1; if (numberObjects) { CbcModel * model = objects[0]->model(); // at continuous //double continuousObjective = model->getContinuousObjective(); //int continuousInfeasibilities = model->getContinuousInfeasibilities(); // average cost to get rid of infeasibility //double averageCostPerInfeasibility = //(objectiveValue-continuousObjective)/ //(double) (abs(continuousInfeasibilities-numberUnsatisfied)+1); /* beforeSolution is : 0 - before any solution n - n heuristic solutions but no branched one -1 - branched solution found */ int numberSolutions = model->getSolutionCount(); double cutoff = model->getCutoff(); int method=0; int i; if (numberSolutions) { int numberHeuristic = model->getNumberHeuristicSolutions(); if (numberHeuristic<numberSolutions) { method = 1; } else { method = 2; // look further for ( i = 0 ; i < numberObjects ; i++) { int numberNext = numberInfeasibilitiesUp[i]; if (numberNext<numberUnsatisfied) { int numberUp = numberUnsatisfied - numberInfeasibilitiesUp[i]; double perUnsatisfied = changeUp[i]/(double) numberUp; double estimatedObjective = objectiveValue + numberUnsatisfied * perUnsatisfied; if (estimatedObjective<cutoff) method=3; } numberNext = numberInfeasibilitiesDown[i]; if (numberNext<numberUnsatisfied) { int numberDown = numberUnsatisfied - numberInfeasibilitiesDown[i]; double perUnsatisfied = changeDown[i]/(double) numberDown; double estimatedObjective = objectiveValue + numberUnsatisfied * perUnsatisfied; if (estimatedObjective<cutoff) method=3; } } } method=2; } else { method = 0; } // Uncomment next to force method 4 //method=4; /* Methods : 0 - fewest infeasibilities 1 - largest min change in objective 2 - as 1 but use sum of changes if min close 3 - predicted best solution 4 - take cheapest up branch if infeasibilities same */ int bestNumber=COIN_INT_MAX; double bestCriterion=-1.0e50; double alternativeCriterion = -1.0; double bestEstimate = 1.0e100; switch (method) { case 0: // could add in depth as well for ( i = 0 ; i < numberObjects ; i++) { int thisNumber = CoinMin(numberInfeasibilitiesUp[i],numberInfeasibilitiesDown[i]); if (thisNumber<=bestNumber) { int betterWay=0; if (numberInfeasibilitiesUp[i]<numberInfeasibilitiesDown[i]) { if (numberInfeasibilitiesUp[i]<bestNumber) { betterWay = 1; } else { if (changeUp[i]<bestCriterion) betterWay=1; } } else if (numberInfeasibilitiesUp[i]>numberInfeasibilitiesDown[i]) { if (numberInfeasibilitiesDown[i]<bestNumber) { betterWay = -1; } else { if (changeDown[i]<bestCriterion) betterWay=-1; } } else { // up and down have same number bool better=false; if (numberInfeasibilitiesUp[i]<bestNumber) { better=true; } else if (numberInfeasibilitiesUp[i]==bestNumber) { if (CoinMin(changeUp[i],changeDown[i])<bestCriterion) better=true;; } if (better) { // see which way if (changeUp[i]<=changeDown[i]) betterWay=1; else betterWay=-1; } } if (betterWay) { bestCriterion = CoinMin(changeUp[i],changeDown[i]); bestNumber = thisNumber; whichObject = i; bestWay = betterWay; } } } break; case 1: for ( i = 0 ; i < numberObjects ; i++) { int betterWay=0; if (changeUp[i]<=changeDown[i]) { if (changeUp[i]>bestCriterion) betterWay=1; } else { if (changeDown[i]>bestCriterion) betterWay=-1; } if (betterWay) { bestCriterion = CoinMin(changeUp[i],changeDown[i]); whichObject = i; bestWay = betterWay; } } break; case 2: for ( i = 0 ; i < numberObjects ; i++) { double change = CoinMin(changeUp[i],changeDown[i]); double sum = changeUp[i] + changeDown[i]; bool take=false; if (change>1.1*bestCriterion) take=true; else if (change>0.9*bestCriterion&&sum+change>bestCriterion+alternativeCriterion) take=true; if (take) { if (changeUp[i]<=changeDown[i]) { if (changeUp[i]>bestCriterion) bestWay=1; } else { if (changeDown[i]>bestCriterion) bestWay=-1; } bestCriterion = change; alternativeCriterion = sum; whichObject = i; } } break; case 3: for ( i = 0 ; i < numberObjects ; i++) { int numberNext = numberInfeasibilitiesUp[i]; if (numberNext<numberUnsatisfied) { int numberUp = numberUnsatisfied - numberInfeasibilitiesUp[i]; double perUnsatisfied = changeUp[i]/(double) numberUp; double estimatedObjective = objectiveValue + numberUnsatisfied * perUnsatisfied; if (estimatedObjective<bestEstimate) { bestEstimate = estimatedObjective; bestWay=1; whichObject=i; } } numberNext = numberInfeasibilitiesDown[i]; if (numberNext<numberUnsatisfied) { int numberDown = numberUnsatisfied - numberInfeasibilitiesDown[i]; double perUnsatisfied = changeDown[i]/(double) numberDown; double estimatedObjective = objectiveValue + numberUnsatisfied * perUnsatisfied; if (estimatedObjective<bestEstimate) { bestEstimate = estimatedObjective; bestWay=-1; whichObject=i; } } } break; case 4: // if number infeas same then cheapest up // first get best number or when going down // now choose smallest change up amongst equal number infeas for ( i = 0 ; i < numberObjects ; i++) { int thisNumber = CoinMin(numberInfeasibilitiesUp[i],numberInfeasibilitiesDown[i]); if (thisNumber<=bestNumber) { int betterWay=0; if (numberInfeasibilitiesUp[i]<numberInfeasibilitiesDown[i]) { if (numberInfeasibilitiesUp[i]<bestNumber) { betterWay = 1; } else { if (changeUp[i]<bestCriterion) betterWay=1; } } else if (numberInfeasibilitiesUp[i]>numberInfeasibilitiesDown[i]) { if (numberInfeasibilitiesDown[i]<bestNumber) { betterWay = -1; } else { if (changeDown[i]<bestCriterion) betterWay=-1; } } else { // up and down have same number bool better=false; if (numberInfeasibilitiesUp[i]<bestNumber) { better=true; } else if (numberInfeasibilitiesUp[i]==bestNumber) { if (CoinMin(changeUp[i],changeDown[i])<bestCriterion) better=true;; } if (better) { // see which way if (changeUp[i]<=changeDown[i]) betterWay=1; else betterWay=-1; } } if (betterWay) { bestCriterion = CoinMin(changeUp[i],changeDown[i]); bestNumber = thisNumber; whichObject = i; bestWay = betterWay; } } } bestCriterion=1.0e50; for ( i = 0 ; i < numberObjects ; i++) { int thisNumber = numberInfeasibilitiesUp[i]; if (thisNumber==bestNumber&&changeUp) { if (changeUp[i]<bestCriterion) { bestCriterion = changeUp[i]; whichObject = i; bestWay = 1; } } } break; } // set way in best if (whichObject>=0) objects[whichObject]->way(bestWay); } return whichObject; } /** Default Constructor Equivalent to an unspecified binary variable. */ CbcSimpleIntegerFixed::CbcSimpleIntegerFixed () : CbcSimpleInteger() { } /** Useful constructor Loads actual upper & lower bounds for the specified variable. */ CbcSimpleIntegerFixed::CbcSimpleIntegerFixed (CbcModel * model, int iColumn, double breakEven) : CbcSimpleInteger(model,iColumn,breakEven) { } // Constructor from simple CbcSimpleIntegerFixed::CbcSimpleIntegerFixed (const CbcSimpleInteger & rhs) : CbcSimpleInteger(rhs) { } // Copy constructor CbcSimpleIntegerFixed::CbcSimpleIntegerFixed ( const CbcSimpleIntegerFixed & rhs) :CbcSimpleInteger(rhs) { } // Clone CbcObject * CbcSimpleIntegerFixed::clone() const { return new CbcSimpleIntegerFixed(*this); } // Assignment operator CbcSimpleIntegerFixed & CbcSimpleIntegerFixed::operator=( const CbcSimpleIntegerFixed& rhs) { if (this!=&rhs) { CbcSimpleInteger::operator=(rhs); } return *this; } // Destructor CbcSimpleIntegerFixed::~CbcSimpleIntegerFixed () { } // Infeasibility - large is 0.5 double CbcSimpleIntegerFixed::infeasibility(int & preferredWay) const { OsiSolverInterface * solver = model_->solver(); const double * solution = model_->testSolution(); const double * lower = solver->getColLower(); const double * upper = solver->getColUpper(); double value = solution[columnNumber_]; value = CoinMax(value, lower[columnNumber_]); value = CoinMin(value, upper[columnNumber_]); /*printf("%d %g %g %g %g\n",columnNumber_,value,lower[columnNumber_], solution[columnNumber_],upper[columnNumber_]);*/ double nearest = floor(value+(1.0-breakEven_)); assert (breakEven_>0.0&&breakEven_<1.0); double integerTolerance = model_->getDblParam(CbcModel::CbcIntegerTolerance); if (nearest>value) preferredWay=1; else preferredWay=-1; if (preferredWay_) preferredWay=preferredWay_; double weight = fabs(value-nearest); // normalize so weight is 0.5 at break even if (nearest<value) weight = (0.5/breakEven_)*weight; else weight = (0.5/(1.0-breakEven_))*weight; if (fabs(value-nearest)<=integerTolerance) { if (upper[columnNumber_]==lower[columnNumber_]) return 0.0; else return 1.0e-5; } else { return weight; } } // Creates a branching object CbcBranchingObject * CbcSimpleIntegerFixed::createBranch(OsiSolverInterface * solver, const OsiBranchingInformation * info, int way) { const double * solution = model_->testSolution(); const double * lower = solver->getColLower(); const double * upper = solver->getColUpper(); double value = solution[columnNumber_]; value = CoinMax(value, lower[columnNumber_]); value = CoinMin(value, upper[columnNumber_]); assert (upper[columnNumber_]>lower[columnNumber_]); if (!model_->hotstartSolution()) { double nearest = floor(value+0.5); double integerTolerance = model_->getDblParam(CbcModel::CbcIntegerTolerance); if (fabs(value-nearest)<integerTolerance) { // adjust value if (nearest!=upper[columnNumber_]) value = nearest+2.0*integerTolerance; else value = nearest-2.0*integerTolerance; } } else { const double * hotstartSolution = model_->hotstartSolution(); double targetValue = hotstartSolution[columnNumber_]; if (way>0) value = targetValue-0.1; else value = targetValue+0.1; } CbcBranchingObject * branch = new CbcIntegerBranchingObject(model_,columnNumber_,way, value); branch->setOriginalObject(this); return branch; }
28.597802
87
0.681448
[ "object", "model" ]
bc514e33a93c77a10804506e09199bcd1de33e58
3,762
cpp
C++
Pang/Pang/Source/ModuleGunShot.cpp
UriKurae/Pang
2634bb22e674f022c0218a3802d0d5f80a9661fa
[ "MIT" ]
1
2020-12-21T17:21:28.000Z
2020-12-21T17:21:28.000Z
Pang/Pang/Source/ModuleGunShot.cpp
UriKurae/Pang
2634bb22e674f022c0218a3802d0d5f80a9661fa
[ "MIT" ]
null
null
null
Pang/Pang/Source/ModuleGunShot.cpp
UriKurae/Pang
2634bb22e674f022c0218a3802d0d5f80a9661fa
[ "MIT" ]
null
null
null
#include "ModuleGunShot.h" #include "ModulePlayer.h" #include"Application.h" #include "Globals.h" #include "ModuleTextures.h" #include "ModuleRender.h" #include "ModuleInput.h" #include "ModuleCollisions.h" #include "ModuleScene.h" #include "ModuleScene2.h" #include "ModuleEnemies.h" #include "ModuleParticles.h" #include "ModuleAudio.h" #include <SDL\include\SDL_scancode.h> ModuleGunShot::ModuleGunShot(bool startEnabled) : Module(startEnabled) { shotGun.anim.PushBack({ 155, 11, 12, 8 }); shotGun.anim.PushBack({ 155, 11, 12, 8 }); shotGun.anim.PushBack({ 169, 11, 12, 8 }); shotGun.anim.PushBack({ 169, 11, 12, 8 }); shotGun.anim.PushBack({ 187, 11, 12, 8 }); shotGun.anim.PushBack({ 187, 11, 12, 8 }); shotGun.anim.PushBack({ 207, 12, 16, 7 }); shotGun.anim.PushBack({ 231, 10, 14, 9 }); shotGun.anim.PushBack({ 207, 12, 16, 7 }); shotGun.anim.PushBack({ 231, 10, 14, 9 }); shotGun.anim.PushBack({ 207, 12, 16, 7 }); shotGun.anim.PushBack({ 231, 10, 14, 9 }); shotGun.anim.PushBack({ 207, 12, 16, 7 }); shotGun.anim.PushBack({ 231, 10, 14, 9 }); shotGun.anim.PushBack({ 207, 12, 16, 7 }); shotGun.anim.PushBack({ 231, 10, 14, 9 }); shotGun.anim.PushBack({ 207, 12, 16, 7 }); shotGun.anim.PushBack({ 231, 10, 14, 9 }); shotGun.anim.PushBack({ 207, 12, 16, 7 }); shotGun.anim.PushBack({ 231, 10, 14, 9 }); shotGun.anim.PushBack({ 207, 12, 16, 7 }); shotGun.anim.PushBack({ 231, 10, 14, 9 }); shotGun.anim.PushBack({ 207, 12, 16, 7 }); shotGun.anim.PushBack({ 231, 10, 14, 9 }); shotGun.anim.PushBack({ 207, 12, 16, 7 }); shotGun.anim.PushBack({ 231, 10, 14, 9 }); shotGun.anim.PushBack({ 207, 12, 16, 7 }); shotGun.anim.PushBack({ 231, 10, 14, 9 }); shotGun.anim.PushBack({ 207, 12, 16, 7 }); shotGun.anim.PushBack({ 231, 10, 14, 9 }); shotGun.anim.PushBack({ 207, 12, 16, 7 }); shotGun.anim.PushBack({ 231, 10, 14, 9 }); shotGun.anim.PushBack({ 207, 12, 16, 7 }); shotGun.anim.PushBack({ 231, 10, 14, 9 }); shotGun.anim.PushBack({ 207, 12, 16, 7 }); shotGun.anim.PushBack({ 231, 10, 14, 9 }); shotGun.anim.loop = true; shotGun.anim.speed = 0.1f; gunShotParticle.anim.PushBack({ 62, 13, 16, 6 }); gunShotParticle.anim.PushBack({ 76, 8, 16, 11 }); gunShotParticle.anim.PushBack({ 95, 9, 16, 10 }); gunShotParticle.anim.PushBack({ 119, 5, 16, 14 }); gunShotParticle.anim.loop = false; gunShotParticle.anim.speed = 0.3f; } ModuleGunShot::~ModuleGunShot() { } bool ModuleGunShot::Start() { gunShotFx = App->audio->LoadFx("Assets/Sound/FX/GunShoot.wav"); ++totalFx; x = App->player->position.x; y = App->player->position.y - speed; return true; } void ModuleGunShot::shot() { App->audio->PlayFx(gunShotFx); ++activeFx; x = App->player->position.x + 10; y = App->player->position.y - 2; App->particles->AddParticle(gunShotParticle, x - 3, y - 6, Collider::Type::NONE, 0); shotGun.speed.y = -2.0f; App->particles->AddParticle(shotGun, x - 3, y + 2, Collider::Type::PLAYER_SHOT, 0); } update_status ModuleGunShot::Update() { update_status ret = update_status::UPDATE_CONTINUE; GamePad& pad = App->input->pads[0]; if (App->player->destroyed == false && App->player->currWeapon == 2 && App->enemies->balloon.balloonsOnScene > 0 && !canShot && App->player->ready == 0) { if (canShot == 0 && pad.a) { shot(); canShot = 10; } else if (App->input->keys[SDL_SCANCODE_SPACE] == KEY_STATE::KEY_DOWN) { shot(); } } if (canShot > 0){ canShot--; } return ret; } update_status ModuleGunShot::PostUpdate() { update_status ret = update_status::UPDATE_CONTINUE; App->render->Blit(texture, shotGun.position.x, shotGun.position.y, &(shotGun.anim.GetCurrentFrame())); return ret; } bool ModuleGunShot::CleanUp() { App->audio->UnloadFx(gunShotFx); return true; }
26.871429
103
0.656566
[ "render" ]
bc59d1410ef1c6f06bb1b808a84d3671765dfc9b
252
cpp
C++
src/example_linear_model.cpp
mlverse/cuda.ml
54fc9575e271b6a94c8650bea1887bb7ffa2b333
[ "MIT" ]
12
2021-10-05T15:34:55.000Z
2021-12-28T14:50:44.000Z
src/example_linear_model.cpp
mlverse/cuml4r
54fc9575e271b6a94c8650bea1887bb7ffa2b333
[ "MIT" ]
39
2021-07-12T13:12:52.000Z
2021-08-24T14:18:05.000Z
src/example_linear_model.cpp
mlverse/cuda.ml
54fc9575e271b6a94c8650bea1887bb7ffa2b333
[ "MIT" ]
1
2021-11-06T02:28:04.000Z
2021-11-06T02:28:04.000Z
#include "example_linear_model.h" #include "lm.h" Rcpp::List cuml4r_example_linear_model() { // return a trivial model Rcpp::List model; model[cuml4r::lm::kCoef] = Rcpp::NumericVector(10); model[cuml4r::lm::kIntercept] = 0; return model; }
21
53
0.702381
[ "model" ]
bc5a9de782ec4fd87de3c2fd7bd0ed7a4d722068
5,611
hpp
C++
engine/include/stl/static_hash_map.hpp
ValtoForks/Terminus-Engine
0c7381af84736ec7b029977843590453cde64b1d
[ "MIT" ]
44
2017-01-25T05:57:21.000Z
2021-09-21T13:36:49.000Z
engine/include/stl/static_hash_map.hpp
ValtoForks/Terminus-Engine
0c7381af84736ec7b029977843590453cde64b1d
[ "MIT" ]
1
2017-04-05T01:50:18.000Z
2017-04-05T01:50:18.000Z
engine/include/stl/static_hash_map.hpp
ValtoForks/Terminus-Engine
0c7381af84736ec7b029977843590453cde64b1d
[ "MIT" ]
3
2017-09-28T08:11:00.000Z
2019-03-27T03:38:47.000Z
#pragma once #include <stl/deque.hpp> #include <stl/murmur_hash.hpp> // @TODO: // 1. Turn HashEntry array into SOA. [DONE] // 2. Add new StringBuffer16 (or 32) array for Keys. // 3. Finish data swap-and-pop upon erase. [DONE] // 4. Implement iterators. // 5. Add prev index to HashEntry. [DONE] // (48 + sizeof(T)) * N template <typename T> uint64_t create_hash(const T& key) { return murmur_hash_64(&key, sizeof(T), 0); } //template <> //uint64_t create_hash<uint64_t>(const uint64_t& key) //{ // return key; //} template<typename KEY, typename VALUE, size_t SIZE> class StaticHashMap { public: struct FindResult { uint32_t hash_index; uint32_t data_prev_index; uint32_t data_index; }; uint32_t m_hash[SIZE]; Deque<uint32_t, SIZE> m_free_indices; uint64_t m_key[SIZE]; uint32_t m_next[SIZE]; uint32_t m_prev[SIZE]; VALUE m_value[SIZE]; KEY m_key_original[SIZE]; uint32_t m_num_objects; const uint32_t INVALID_INDEX = 0xffffffffu; public: StaticHashMap() { for (uint32_t i = 0; i< SIZE; ++i) { m_hash[i] = INVALID_INDEX; m_next[i] = INVALID_INDEX; m_prev[i] = INVALID_INDEX; m_free_indices.push_back(i); } m_num_objects = 0; } ~StaticHashMap() { } void set(const KEY& key, const VALUE& value) { uint32_t data_index = find_or_make(create_hash(key)); m_key_original[data_index] = key; m_value[data_index] = value; } bool has(const KEY& key) { uint32_t data_index = find_or_fail(create_hash(key)); return data_index != INVALID_INDEX; } bool get(const KEY& key, VALUE& object) { uint32_t data_index = find_or_fail(create_hash(key)); if (data_index == INVALID_INDEX) return false; else { object = m_value[data_index]; return true; } } VALUE* get_ptr(const KEY& key) { uint32_t data_index = find_or_fail(create_hash(key)); if (data_index == INVALID_INDEX) return nullptr; else return &m_value[data_index]; } void remove(const KEY& key) { FindResult result = find(create_hash(key)); // check if key actually exists if (result.data_index != INVALID_INDEX) erase(result); } uint32_t size() { return m_num_objects; } private: FindResult find(const uint64_t& key) { FindResult result; result.hash_index = INVALID_INDEX; result.data_prev_index = INVALID_INDEX; result.data_index = INVALID_INDEX; result.hash_index = key % SIZE; result.data_index = m_hash[result.hash_index]; while (result.data_index != INVALID_INDEX) { if (m_key[result.data_index] == key) return result; result.data_prev_index = result.data_index; result.data_index = m_next[result.data_index]; } return result; } // tries to find an object. if not found returns INVALID_INDEX. uint32_t find_or_fail(const uint64_t& key) { FindResult result = find(key); return result.data_index; } // tries to find an object. if not found creates Hash Entry. uint32_t find_or_make(const uint64_t& key) { FindResult result = find(key); if (result.data_index == INVALID_INDEX) { result.data_index = m_free_indices.pop_front(); m_next[result.data_index] = INVALID_INDEX; m_key[result.data_index] = key; m_num_objects++; if (result.data_prev_index != INVALID_INDEX) { m_next[result.data_prev_index] = result.data_index; m_prev[result.data_index] = result.data_prev_index; } if (m_hash[result.hash_index] == INVALID_INDEX) m_hash[result.hash_index] = result.data_index; } return result.data_index; } void erase(FindResult& result) { uint32_t last_data_index = m_num_objects - 1; m_num_objects--; // push last items' index into freelist m_free_indices.push_front(last_data_index); // Handle the element to be deleted if (result.data_prev_index == INVALID_INDEX) m_hash[result.hash_index] = INVALID_INDEX; else m_next[result.data_prev_index] = m_next[result.data_index]; if (m_next[result.data_index] != INVALID_INDEX) m_prev[m_next[result.data_index]] = result.data_prev_index; if (result.data_index != last_data_index) // is NOT last element { // Handle the last element if (m_prev[last_data_index] == INVALID_INDEX) { uint64_t last_hash_index = m_key[last_data_index] % SIZE; m_hash[last_hash_index] = result.data_index; } else m_next[m_prev[last_data_index]] = result.data_index; if (m_next[last_data_index] != INVALID_INDEX) m_prev[m_next[last_data_index]] = result.data_index; // Swap elements m_key[result.data_index] = m_key[last_data_index]; m_next[result.data_index] = m_next[last_data_index]; m_prev[result.data_index] = m_prev[last_data_index]; m_value[result.data_index] = m_value[last_data_index]; } } };
26.592417
73
0.592408
[ "object" ]
bc5cd5262ef4ed804de7fedc3650cc028e7d56a7
4,906
hpp
C++
include/graphics/materials/MaterialInstanceDefinition.hpp
manvis/IYFEngine
741a8d0dcc9b3e3ff8a8adb92850633523516604
[ "BSD-3-Clause" ]
5
2018-07-03T17:05:43.000Z
2020-02-03T00:23:46.000Z
include/graphics/materials/MaterialInstanceDefinition.hpp
manvis/IYFEngine
741a8d0dcc9b3e3ff8a8adb92850633523516604
[ "BSD-3-Clause" ]
null
null
null
include/graphics/materials/MaterialInstanceDefinition.hpp
manvis/IYFEngine
741a8d0dcc9b3e3ff8a8adb92850633523516604
[ "BSD-3-Clause" ]
null
null
null
// The IYFEngine // // Copyright (C) 2015-2018, Manvydas Šliamka // // 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 IYF_MATERIAL_INSTANCE_DEFINITION_HPP #define IYF_MATERIAL_INSTANCE_DEFINITION_HPP #include "utilities/hashing/Hashing.hpp" #include "core/Constants.hpp" #include "io/interfaces/Serializable.hpp" #include "io/interfaces/TextSerializable.hpp" #include "graphics/materials/MaterialRenderMode.hpp" #include "glm/vec4.hpp" #include <vector> namespace iyf { /// This class stores material data and metadata for editing, serializes it into files and is used by the World objects to /// instantiate Material objects that contain data used by the GPU during rendering. class MaterialInstanceDefinition : public Serializable, public TextSerializable { public: MaterialInstanceDefinition() : materialTemplateDefinition(0), renderMode(MaterialRenderMode::Opaque) {} /// \brief Get a StringHash of a MaterialTemplateDefinition that this MaterialInstanceDefinition is based on. inline StringHash getMaterialTemplateDefinition() const { return materialTemplateDefinition; } /// \brief Associate a new MaterialTemplateDefinition with this MaterialInstanceDefinition. inline void setMaterialTemplateDefinition(StringHash newMaterialTemplateDefinition, std::vector<std::pair<StringHash, glm::vec4>> variables, std::vector<std::pair<StringHash, StringHash>> textures) { materialTemplateDefinition = newMaterialTemplateDefinition; this->variables = std::move(variables); this->textures = std::move(textures); } /// \brief Get a MaterialRenderMode that is used by MaterialInstances created from this MaterialInstanceDefinition inline MaterialRenderMode getRenderMode() const { return renderMode; } /// \brief Set a new MaterialRenderMode that will be used by MaterialInstances created from this MaterialInstanceDefinition /// /// \warning Calling this will invalidate and potentially change the ID. It will be recomputed the next time getID() is called. /// /// \todo since I'm planning to make familyVariant carry more data, the render mode should PROBABLY be a part of it inline void setRenderMode(MaterialRenderMode newRenderMode) { renderMode = newRenderMode; } inline const std::vector<std::pair<StringHash, glm::vec4>>& getVariables() const { return variables; } inline const std::vector<std::pair<StringHash, StringHash>>& getTextures() const { return textures; } virtual void serialize(Serializer& fw) const final override; virtual void deserialize(Serializer& fr) final override; virtual void serializeJSON(PrettyStringWriter& pw) const final override; virtual void deserializeJSON(JSONObject& jo) final override; virtual bool makesJSONRoot() const final override { return true; } protected: StringHash materialTemplateDefinition; std::vector<std::pair<StringHash, glm::vec4>> variables; std::vector<std::pair<StringHash, StringHash>> textures; /// Used to determine if an Entity object that uses a Material created from this definition should be stored in "opaque objects" draw list or in "transparent objects" draw list MaterialRenderMode renderMode; }; } #endif // IYF_MATERIAL_INSTANCE_DEFINITION_HPP
45.850467
180
0.743579
[ "render", "object", "vector" ]
bc60845b215311a05eaa599adcd1f450f19cb7f8
9,538
cpp
C++
spt/features/vag_trace.cpp
tmob03/SourcePauseTool
5bc27b63c74a2392803c0471067d2af138c43efd
[ "RSA-MD" ]
1
2021-11-13T05:42:45.000Z
2021-11-13T05:42:45.000Z
spt/features/vag_trace.cpp
lipsanen/SourcePauseTool
5bc27b63c74a2392803c0471067d2af138c43efd
[ "RSA-MD" ]
null
null
null
spt/features/vag_trace.cpp
lipsanen/SourcePauseTool
5bc27b63c74a2392803c0471067d2af138c43efd
[ "RSA-MD" ]
null
null
null
#include "stdafx.h" #if defined(SSDK2007) || defined(SSDK2013) #include "..\feature.hpp" #include "icliententity.h" #include "..\utils\game_detection.hpp" #include "ent_utils.hpp" #include "interfaces.hpp" #include "..\cvars.hpp" #include "tickrate.hpp" #include "signals.hpp" #include "playerio.hpp" #include "..\overlay\portal_camera.hpp" ConVar y_spt_vag_trace("y_spt_vag_trace", "0", FCVAR_CHEAT, "Draws VAG trace.\n"); ConVar y_spt_vag_target("y_spt_vag_target", "0", FCVAR_CHEAT, "Draws VAG target trace.\n"); ConVar y_spt_vag_trace_portal( "y_spt_vag_trace_portal", "overlay", FCVAR_CHEAT, "Chooses the portal for the VAG trace. Valid options are overlay/blue/orange/portal index. This is the portal you enter.\n"); // VAG finding tool class VagTrace : public FeatureWrapper<VagTrace> { public: void DrawTrace(); Vector CalculateAG(Vector enter_origin, QAngle enter_angles, Vector exit_origin, QAngle exit_angles); void SetTarget(Vector target); Vector ReverseAG(Vector enter_origin, QAngle enter_angles, QAngle exit_angles); protected: virtual bool ShouldLoadFeature() override; virtual void LoadFeature() override; virtual void UnloadFeature() override; private: Vector target = {0.0f, 0.0f, 0.0f}; }; VagTrace spt_vag_trace; CON_COMMAND(y_spt_vag_target_set, "Set VAG target\n") { spt_vag_trace.SetTarget(spt_playerio.GetPlayerEyePos()); } void VagTrace::DrawTrace() { bool vag_trace = y_spt_vag_trace.GetBool(); bool vag_target = y_spt_vag_target.GetBool(); if (!vag_trace && !vag_target) return; float lifeTime = spt_tickrate.GetTickrate() * 2; if (vag_target) { interfaces::debugOverlay->AddBoxOverlay(target, Vector(-20, -20, -20), Vector(20, 20, 20), QAngle(0, 0, 0), 255, 255, 0, 100, lifeTime); } IClientEntity* enter_portal; if (strcmp(y_spt_vag_trace_portal.GetString(), "overlay") == 0) { enter_portal = getPortal(_y_spt_overlay_portal.GetString(), false); } else { enter_portal = getPortal(y_spt_vag_trace_portal.GetString(), false); } if (!enter_portal) return; auto exit_portal = utils::FindLinkedPortal(enter_portal); if (!exit_portal) return; auto enter_origin = utils::GetPortalPosition(enter_portal); auto enter_angles = utils::GetPortalAngles(enter_portal); auto exit_origin = utils::GetPortalPosition(exit_portal); auto exit_angles = utils::GetPortalAngles(exit_portal); if (y_spt_vag_trace.GetBool()) { interfaces::debugOverlay->AddLineOverlay(enter_origin, exit_origin, 0, 0, 255, true, lifeTime); interfaces::debugOverlay ->AddLineOverlay(CalculateAG(enter_origin, enter_angles, exit_origin, exit_angles), enter_origin, 0, 255, 0, true, lifeTime); if (abs(abs(exit_angles.x) - 90) < 0.04 && abs(exit_angles.z) < 0.04) { // Is floor/ceiling portal QAngle angle = exit_angles; angle.y = 179.0f; Vector prev = CalculateAG(enter_origin, enter_angles, exit_origin, angle); for (angle.y = -180.0f; angle.y < 180.0f; angle.y += 1.0f) { Vector curr = CalculateAG(enter_origin, enter_angles, exit_origin, angle); interfaces::debugOverlay->AddLineOverlay(curr, prev, 255, 255, 255, false, lifeTime); prev = curr; } } } if (y_spt_vag_target.GetBool()) { QAngle wall_angles[4] = {{0.0f, 0.0f, 0.0f}, {0.0f, 90.0f, 0.0f}, {0.0f, -90.0f, 0.0f}, {0.0f, 180.0f, 0.0f}}; Vector wall_normal[4] = {{1.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f}, {0.0f, -1.0f, 0.0f}, {-1.0f, 0.0f, 0.0f}}; for (int i = 0; i < 4; i++) { Vector exit = ReverseAG(enter_origin, enter_angles, wall_angles[i]); interfaces::debugOverlay->AddBoxOverlay2(exit, Vector(-1, -32, -54), Vector(1, 32, 54), wall_angles[i], Color(255, 0, 0, 64), Color(255, 0, 0, 255), lifeTime); interfaces::debugOverlay ->AddLineOverlay(exit, exit + wall_normal[i] * 20, 255, 0, 0, true, lifeTime); } QAngle angle(90.0f, 179.0f, 0.0f); Vector prev = ReverseAG(enter_origin, enter_angles, angle); for (angle.y = -180.0f; angle.y < 180.0f; angle.y += 1.0f) { Vector curr = ReverseAG(enter_origin, enter_angles, angle); interfaces::debugOverlay->AddLineOverlay(curr, prev, 255, 0, 255, false, lifeTime); prev = curr; } angle = QAngle(-90.0f, 179.0f, 0.0f); prev = ReverseAG(enter_origin, enter_angles, angle); for (angle.y = -180.0f; angle.y < 180.0f; angle.y += 1.0f) { Vector curr = ReverseAG(enter_origin, enter_angles, angle); interfaces::debugOverlay->AddLineOverlay(curr, prev, 0, 255, 255, false, lifeTime); prev = curr; } } } Vector VagTrace::CalculateAG(Vector enter_origin, QAngle enter_angles, Vector exit_origin, QAngle exit_angles) { Vector exitForward, exitRight, exitUp; Vector enterForward, enterRight, enterUp; AngleVectors(enter_angles, &enterForward, &enterRight, &enterUp); AngleVectors(exit_angles, &exitForward, &exitRight, &exitUp); auto delta = enter_origin - exit_origin; Vector exit_portal_coords; exit_portal_coords.x = delta.Dot(exitForward); exit_portal_coords.y = delta.Dot(exitRight); exit_portal_coords.z = delta.Dot(exitUp); Vector transition(0, 0, 0); transition -= exit_portal_coords.x * enterForward; transition -= exit_portal_coords.y * enterRight; transition += exit_portal_coords.z * enterUp; return enter_origin + transition; } void VagTrace::SetTarget(Vector target_pos) { this->target = target_pos; } Vector VagTrace::ReverseAG(Vector enter_origin, QAngle enter_angles, QAngle exit_angles) { Vector transition = target - enter_origin; Vector enter[3]; AngleVectors(enter_angles, &enter[0], &enter[1], &enter[2]); enter[0] *= -1; enter[1] *= -1; float det = enter[0][0] * (enter[1][1] * enter[2][2] - enter[2][1] * enter[1][2]) - enter[0][1] * (enter[1][0] * enter[2][2] - enter[1][2] * enter[2][0]) + enter[0][2] * (enter[1][0] * enter[2][1] - enter[1][1] * enter[2][0]); float invdet; if (det == 0) { invdet = 1; } else { invdet = 1 / det; } VMatrix enter_mat(enter[0][0], enter[0][1], enter[0][2], 0, enter[1][0], enter[1][1], enter[1][2], 0, enter[2][0], enter[2][1], enter[2][2], 0, 0, 0, 0, 1); VMatrix inv; enter_mat.InverseGeneral(inv); Vector inv_enter[3] = {{inv[0][0], inv[0][1], inv[0][2]}, {inv[1][0], inv[1][1], inv[1][2]}, {inv[2][0], inv[2][1], inv[2][2]}}; Vector exit_portal_coords; exit_portal_coords.x = transition.x * inv_enter[0][0] + transition.y * inv_enter[1][0] + transition.z * inv_enter[2][0]; exit_portal_coords.y = transition.x * inv_enter[0][1] + transition.y * inv_enter[1][1] + transition.z * inv_enter[2][1]; exit_portal_coords.z = transition.x * inv_enter[0][2] + transition.y * inv_enter[1][2] + transition.z * inv_enter[2][2]; Vector exit[3]; AngleVectors(exit_angles, &exit[0], &exit[1], &exit[2]); det = exit[0][0] * (exit[1][1] * exit[2][2] - exit[2][1] * exit[1][2]) - exit[0][1] * (exit[1][0] * exit[2][2] - exit[1][2] * exit[2][0]) + exit[0][2] * (exit[1][0] * exit[2][1] - exit[1][1] * exit[2][0]); if (det == 0) { invdet = 1; } else { invdet = 1 / det; } VMatrix exit_mat(exit[0][0], exit[0][1], exit[0][2], 0, exit[1][0], exit[1][1], exit[1][2], 0, exit[2][0], exit[2][1], exit[2][2], 0, 0, 0, 0, 1); exit_mat.InverseGeneral(inv); Vector inv_exit_angles[3] = {{inv[0][0], inv[0][1], inv[0][2]}, {inv[1][0], inv[1][1], inv[1][2]}, {inv[2][0], inv[2][1], inv[2][2]}}; Vector delta; delta.x = inv_exit_angles[0].Dot(exit_portal_coords); delta.y = inv_exit_angles[1].Dot(exit_portal_coords); delta.z = inv_exit_angles[2].Dot(exit_portal_coords); return -(delta - enter_origin); } bool VagTrace::ShouldLoadFeature() { return utils::DoesGameLookLikePortal(); } void VagTrace::LoadFeature() { if (interfaces::debugOverlay && TickSignal.Works) { TickSignal.Connect(this, &VagTrace::DrawTrace); InitCommand(y_spt_vag_target_set); InitConcommandBase(y_spt_vag_trace); InitConcommandBase(y_spt_vag_target); InitConcommandBase(y_spt_vag_trace_portal); } } void VagTrace::UnloadFeature() {} #endif
30.967532
129
0.568673
[ "vector" ]
bc664d53c600907f5e113afcdae6570ea3e6b2af
895
cpp
C++
AtCoder/Educational DP Contest/F.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
3
2020-11-01T06:31:30.000Z
2022-02-21T20:37:51.000Z
AtCoder/Educational DP Contest/F.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
null
null
null
AtCoder/Educational DP Contest/F.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
1
2021-05-05T18:56:31.000Z
2021-05-05T18:56:31.000Z
/** * author: MaGnsi0 * created: 29/07/2021 17:04:23 **/ #include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0); string s, t; cin >> s >> t; int n = s.size(), m = t.size(); vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0)); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + (s[i - 1] == t[j - 1])); } } string lcs = ""; for (int i = n, j = m, k = dp[n][m]; k; --i, --j, --k) { while (s[i - 1] != t[j - 1]) { if (dp[i - 1][j] > dp[i][j - 1]) { i--; } else { j--; } } lcs.push_back(s[i - 1]); } reverse(lcs.begin(), lcs.end()); cout << lcs; }
26.323529
80
0.373184
[ "vector" ]
bc6df7924c07469cd58d88779287e784220ad119
1,767
cc
C++
benchmark/prod.cc
s-kanev/gperftools
6af68f4cc7877deeae43dbe3510047d32f031153
[ "BSD-3-Clause" ]
null
null
null
benchmark/prod.cc
s-kanev/gperftools
6af68f4cc7877deeae43dbe3510047d32f031153
[ "BSD-3-Clause" ]
null
null
null
benchmark/prod.cc
s-kanev/gperftools
6af68f4cc7877deeae43dbe3510047d32f031153
[ "BSD-3-Clause" ]
null
null
null
#include <algorithm> #include <chrono> #include <cstdlib> #include <cstdint> #include <cstring> #include <random> #include <thread> #include <vector> #include <pthread.h> #include "run_benchmark.h" #include "num_iterations.h" std::vector<void*> allocated[REPEATS]; std::vector<size_t> free_ind[REPEATS]; static void set_affinity(int core_id) { pthread_t thread = pthread_self(); cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(core_id, &cpuset); int res = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset); if (res != 0) { fprintf(stderr, "%s\n", strerror(res)); abort(); } } void init(long rep) { allocated[rep].insert(allocated[rep].begin(), ITERATIONS, nullptr); free_ind[rep].reserve(ITERATIONS); std::random_device rd; std::default_random_engine re(rd()); for (size_t i = 0; i < ITERATIONS; i++) { free_ind[rep][i] = i; } std::shuffle(std::begin(free_ind[rep]), std::end(free_ind[rep]), re); } static void consumer(long rep) { set_affinity(1); size_t freed = 0; size_t i = 0; while (freed < ITERATIONS) { void*& curr = allocated[rep][free_ind[rep][i]]; if (curr) { freed++; free(curr); curr = nullptr; } i = (i + 1) % ITERATIONS; } } static void producer(long rep, long iterations, uintptr_t param) { size_t sz = 32; set_affinity(0); std::thread t(consumer, rep); for (size_t i = 0; i < ITERATIONS; i++) { void *p = malloc(sz); if (!p) { abort(); } allocated[rep][i] = p; // this makes next iteration use different free list. So // subsequent iterations may actually overlap in time. sz = (sz & 511) + 16; } t.join(); } int main(void) { report_benchmark("bench_producer", producer, init, 0); return 0; }
21.814815
71
0.63554
[ "vector" ]
bc6fcb907231fadd38b9eb0ad82578cdf58d8b9d
5,810
cc
C++
L1Trigger/TrackFindingTMTT/src/InputData.cc
djcranshaw/cmssw
d66d1b15005a5f253dcbd3704591620e39fe4290
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
L1Trigger/TrackFindingTMTT/src/InputData.cc
djcranshaw/cmssw
d66d1b15005a5f253dcbd3704591620e39fe4290
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
L1Trigger/TrackFindingTMTT/src/InputData.cc
djcranshaw/cmssw
d66d1b15005a5f253dcbd3704591620e39fe4290
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Utilities/interface/InputTag.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "SimDataFormats/Track/interface/SimTrack.h" #include "SimDataFormats/EncodedEventId/interface/EncodedEventId.h" // #include "Geometry/Records/interface/StackedTrackerGeometryRecord.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h" #include "DataFormats/TrackerCommon/interface/TrackerTopology.h" // TTStubAssociationMap.h forgets to two needed files, so must include them here ... #include "SimDataFormats/TrackingAnalysis/interface/TrackingParticle.h" #include "SimTracker/TrackTriggerAssociation/interface/TTClusterAssociationMap.h" #include "SimTracker/TrackTriggerAssociation/interface/TTStubAssociationMap.h" #include "DataFormats/JetReco/interface/GenJetCollection.h" #include "DataFormats/JetReco/interface/GenJet.h" #include "L1Trigger/TrackFindingTMTT/interface/InputData.h" #include "L1Trigger/TrackFindingTMTT/interface/Settings.h" #include <map> using namespace std; namespace TMTT { InputData::InputData(const edm::Event& iEvent, const edm::EventSetup& iSetup, Settings* settings, const edm::EDGetTokenT<TrackingParticleCollection> tpInputTag, const edm::EDGetTokenT<DetSetVec> stubInputTag, const edm::EDGetTokenT<TTStubAssMap> stubTruthInputTag, const edm::EDGetTokenT<TTClusterAssMap> clusterTruthInputTag, const edm::EDGetTokenT< reco::GenJetCollection > genJetInputTag ) { vTPs_.reserve(2500); vStubs_.reserve(35000); vAllStubs_.reserve(35000); // Note if job will use MC truth info (or skip it to save CPU). enableMCtruth_ = settings->enableMCtruth(); // Get TrackingParticle info edm::Handle<TrackingParticleCollection> tpHandle; if (enableMCtruth_) { iEvent.getByToken(tpInputTag, tpHandle ); unsigned int tpCount = 0; for (unsigned int i = 0; i < tpHandle->size(); i++) { const TrackingParticle& tPart = tpHandle->at(i); // Creating Ptr uses CPU, so apply Pt cut here, copied from TP::fillUse(), to avoid doing it too often. const float ptMin = min(settings->genMinPt(), 0.7*settings->houghMinPt()); if (tPart.pt() > ptMin) { TrackingParticlePtr tpPtr(tpHandle, i); // Store the TrackingParticle info, using class TP to provide easy access to the most useful info. TP tp(tpPtr, tpCount, settings); // Only bother storing tp if it could be useful for tracking efficiency or fake rate measurements. if (tp.use()) { edm::Handle< reco::GenJetCollection > genJetHandle; iEvent.getByToken(genJetInputTag, genJetHandle); if ( genJetHandle.isValid() ) { tp.fillNearestJetInfo( genJetHandle.product() ); } vTPs_.push_back( tp ); tpCount++; } } } } // Also create map relating edm::Ptr<TrackingParticle> to TP. map<edm::Ptr< TrackingParticle >, const TP* > translateTP; if (enableMCtruth_) { for (const TP& tp : vTPs_) { TrackingParticlePtr tpPtr(tp); translateTP[tpPtr] = &tp; } } // Get the tracker geometry info needed to unpack the stub info. edm::ESHandle<TrackerGeometry> trackerGeometryHandle; iSetup.get<TrackerDigiGeometryRecord>().get( trackerGeometryHandle ); const TrackerGeometry* trackerGeometry = trackerGeometryHandle.product(); edm::ESHandle<TrackerTopology> trackerTopologyHandle; iSetup.get<TrackerTopologyRcd>().get(trackerTopologyHandle); const TrackerTopology* trackerTopology = trackerTopologyHandle.product(); // Get stub info, by looping over modules and then stubs inside each module. // Also get the association map from stubs to tracking particles. edm::Handle<DetSetVec> ttStubHandle; edm::Handle<TTStubAssMap> mcTruthTTStubHandle; edm::Handle<TTClusterAssMap> mcTruthTTClusterHandle; iEvent.getByToken(stubInputTag, ttStubHandle ); if (enableMCtruth_) { iEvent.getByToken(stubTruthInputTag, mcTruthTTStubHandle ); iEvent.getByToken(clusterTruthInputTag, mcTruthTTClusterHandle ); } unsigned int stubCount = 0; for (DetSetVec::const_iterator p_module = ttStubHandle->begin(); p_module != ttStubHandle->end(); p_module++) { for (DetSet::const_iterator p_ttstub = p_module->begin(); p_ttstub != p_module->end(); p_ttstub++) { TTStubRef ttStubRef = edmNew::makeRefTo(ttStubHandle, p_ttstub ); // Store the Stub info, using class Stub to provide easy access to the most useful info. Stub stub(ttStubRef, stubCount, settings, trackerGeometry, trackerTopology ); // Also fill truth associating stubs to tracking particles. if (enableMCtruth_) stub.fillTruth(translateTP, mcTruthTTStubHandle, mcTruthTTClusterHandle); vAllStubs_.push_back( stub ); stubCount++; } } // Produced reduced list containing only the subset of stubs that the user has declared will be // output by the front-end readout electronics. for (const Stub& s : vAllStubs_) { if (s.frontendPass()) vStubs_.push_back( &s ); } // Optionally sort stubs according to bend, so highest Pt ones are sent from DTC to GP first. if (settings->orderStubsByBend()) std::sort(vStubs_.begin(), vStubs_.end(), SortStubsInBend()); // Note list of stubs produced by each tracking particle. // (By passing vAllStubs_ here instead of vStubs_, it means that any algorithmic efficiencies // measured will be reduced if the tightened frontend electronics cuts, specified in section StubCuts // of Analyze_Defaults_cfi.py, are not 100% efficient). if (enableMCtruth_) { for (unsigned int j = 0; j < vTPs_.size(); j++) { vTPs_[j].fillTruth(vAllStubs_); } } } }
38.733333
113
0.744062
[ "geometry" ]
bc70e615365c36f21c309539ca05aeac44513626
6,419
cpp
C++
MAIN/src/main.cpp
MagicRB/MODDABLE_RPG
567f007b15eead07bac73608a6e980c138553761
[ "MIT" ]
null
null
null
MAIN/src/main.cpp
MagicRB/MODDABLE_RPG
567f007b15eead07bac73608a6e980c138553761
[ "MIT" ]
null
null
null
MAIN/src/main.cpp
MagicRB/MODDABLE_RPG
567f007b15eead07bac73608a6e980c138553761
[ "MIT" ]
null
null
null
#include "main.h" #include <iostream> #include <map> #include <cmath> #include <iomanip> #include "player.hpp" #include "door.hpp" #include "generic_wall.hpp" bool mouse_left_pressed; player* pl; std::vector<std::string> split(const char *str, char c = ' ') { std::vector<std::string> result; do { const char *begin = str; while(*str != c && *str) str++; result.push_back(std::string(begin, str)); } while (0 != *str++); return result; } void controller(modAPI* mAPI, sf::Event event) { if (mAPI->keyBindMap[event.key.code] != NULL && event.type == sf::Event::KeyPressed) { mAPI->keyBindMap[event.key.code](mAPI); } if (mAPI->inputE.get_event_vector().size() != 0 && mAPI->window.get()->hasFocus()) { for (unsigned int i = 0; i < mAPI->inputE.get_event_vector().size(); i++) { mAPI->inputE.get_event_vector().at(i)(mAPI); } } if(event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::E) { int mouseX = sf::Mouse::getPosition(*mAPI->window.get()).x; int mouseY = sf::Mouse::getPosition(*mAPI->window.get()).y; sf::Vector2i mouse(mouseX, mouseY); if (sqrt( pow(mAPI->window.get()->mapPixelToCoords(mouse).x - pl->getPosition().x, 2) + pow( mAPI->window.get()->mapPixelToCoords(mouse).y - pl->getPosition().y, 2) ) <= 60) { for (int i = 0; i < mAPI->gameObjectManager.get()->go_vector.size(); i++) { if (mAPI->gameObjectManager.get()->go_vector.at(i)->getBounds().contains(mAPI->window.get()->mapPixelToCoords(mouse))) { mAPI->gameObjectManager.get()->go_vector.at(i)->interact(pl); } } } } if (event.type == sf::Event::Closed) { mAPI->window.get()->close(); exit(EXIT_SUCCESS); } else if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Q) { mAPI->window.get()->close(); exit(EXIT_SUCCESS); } } void loadFromWorldLine(modAPI* mAPI, std::string line) { int i = 0; std::string operation; std::string arguments; while (line.at(i) != ' ') { operation += line.at(i); i++; } arguments = line.substr(i + 1, line.size() - 1); arguments.erase(std::remove(arguments.begin(), arguments.end(), ' '), arguments.end()); std::vector<std::string> tokens = split(arguments.c_str(), ';'); if (operation == ":DOOR") { mAPI->gameObjectManager.get()->go_vector.push_back(std::unique_ptr<gameObject>(new door())); door* d = dynamic_cast<door*>(mAPI->gameObjectManager.get()->go_vector.at(mAPI->gameObjectManager.get()->go_vector.size() - 1).get()); d->setTilePosition(atoi(tokens.at(0).c_str()), atoi(tokens.at(1).c_str())); mAPI->textureManager.get()->addNewTexture("door"); mAPI->textureManager.get()->texture_map.at("door").loadFromFile("Textures/door.png"); d->setTexture(mAPI->textureManager.get()->texture_map.at("door")); } else if (operation == ":GENERIC_WALL") { generic_wall* w = new generic_wall(mAPI, atoi(tokens.at(0).c_str()), atoi(tokens.at(1).c_str())); w->mAPI = mAPI; if (mAPI->textureManager.get()->addNewTexture("wall_vertical")) { mAPI->textureManager.get()->texture_map.at("wall_vertical").loadFromFile("Textures/wall_vertical.png"); } if (mAPI->textureManager.get()->addNewTexture("wall_horizontal")) { mAPI->textureManager.get()->texture_map.at("wall_horizontal").loadFromFile("Textures/wall_horizontal.png"); } if (mAPI->textureManager.get()->addNewTexture("wall_corner_bottom_left")) { mAPI->textureManager.get()->texture_map.at("wall_corner_bottom_left").loadFromFile("Textures/wall_corner_bottom_left.png"); } if (mAPI->textureManager.get()->addNewTexture("wall_corner_bottom_right")) { mAPI->textureManager.get()->texture_map.at("wall_corner_bottom_right").loadFromFile("Textures/wall_corner_bottom_right.png"); } if (mAPI->textureManager.get()->addNewTexture("wall_corner_top_left")) { mAPI->textureManager.get()->texture_map.at("wall_corner_top_left").loadFromFile("Textures/wall_corner_top_left.png"); } if (mAPI->textureManager.get()->addNewTexture("wall_corner_top_right")) { mAPI->textureManager.get()->texture_map.at("wall_corner_top_right").loadFromFile("Textures/wall_corner_top_right.png"); } if (mAPI->textureManager.get()->addNewTexture("wall_t_left")) { mAPI->textureManager.get()->texture_map.at("wall_t_left").loadFromFile("Textures/wall_t_left.png"); } if (mAPI->textureManager.get()->addNewTexture("wall_t_right")) { mAPI->textureManager.get()->texture_map.at("wall_t_right").loadFromFile("Textures/wall_t_right.png"); } if (mAPI->textureManager.get()->addNewTexture("wall_t_top")) { mAPI->textureManager.get()->texture_map.at("wall_t_top").loadFromFile("Textures/wall_t_top.png"); } if (mAPI->textureManager.get()->addNewTexture("wall_t_bottom")) { mAPI->textureManager.get()->texture_map.at("wall_t_bottom").loadFromFile("Textures/wall_t_bottom.png"); } if (mAPI->textureManager.get()->addNewTexture("wall_pillar")) { mAPI->textureManager.get()->texture_map.at("wall_pillar").loadFromFile("Textures/wall_pillar.png"); } if (mAPI->textureManager.get()->addNewTexture("wall_cross")) { mAPI->textureManager.get()->texture_map.at("wall_cross").loadFromFile("Textures/wall_cross.png"); } if (mAPI->textureManager.get()->addNewTexture("wall_end_left")) { mAPI->textureManager.get()->texture_map.at("wall_end_left").loadFromFile("Textures/wall_end_left.png"); } if (mAPI->textureManager.get()->addNewTexture("wall_end_right")) { mAPI->textureManager.get()->texture_map.at("wall_end_right").loadFromFile("Textures/wall_end_right.png"); } if (mAPI->textureManager.get()->addNewTexture("wall_end_top")) { mAPI->textureManager.get()->texture_map.at("wall_end_top").loadFromFile("Textures/wall_end_top.png"); } if (mAPI->textureManager.get()->addNewTexture("wall_end_bottom")) { mAPI->textureManager.get()->texture_map.at("wall_end_bottom").loadFromFile("Textures/wall_end_bottom.png"); } w->blockUpdate(NULL); } } void initializeMod(modAPI* mAPI) { mAPI->control_override.set(controller); mAPI->worldFileEntryE.add_event(loadFromWorldLine); pl = new player(mAPI); mAPI->gameObjectManager.get()->go_vector.push_back(std::unique_ptr<gameObject>(pl)); mAPI->rigid_body_vector.push_back(pl); }
50.148438
209
0.674871
[ "vector" ]
bc77f4152ef00ea8b5d29b2d1a36d6116da70bdd
2,443
cpp
C++
test/SelectTest.cpp
ruszkait/DefQuery
bb2269cd7d918a5ce36cb7a1e9fd426c37370f68
[ "Apache-2.0" ]
null
null
null
test/SelectTest.cpp
ruszkait/DefQuery
bb2269cd7d918a5ce36cb7a1e9fd426c37370f68
[ "Apache-2.0" ]
null
null
null
test/SelectTest.cpp
ruszkait/DefQuery
bb2269cd7d918a5ce36cb7a1e9fd426c37370f68
[ "Apache-2.0" ]
null
null
null
#include "gtest/gtest.h" #include <DefQuery/from.h> #include <DefQuery/select.h> #include <list> TEST(SelectTest, ProjectionTest) { std::list<int> list = {1, 2, 3}; auto enumerator = DefQuery::from(list).select([](int a) { return a * 1.5; }); ASSERT_TRUE(++enumerator); ASSERT_EQ(1.5, *enumerator); ASSERT_TRUE(++enumerator); ASSERT_EQ(3.0, *enumerator); ASSERT_TRUE(++enumerator); ASSERT_EQ(4.5, *enumerator); ASSERT_FALSE(++enumerator); ASSERT_FALSE(++enumerator); } TEST(SelectTest, StructProjectionTest) { struct Person { std::string _name; double _age; }; std::vector<Person> list = {Person{"Oliver", 10}, Person{"Hanna", 11}, Person{"Peter", 20}}; auto enumerator = DefQuery::from(list).select([](const Person& person) { return person._age; }); ASSERT_TRUE(++enumerator); ASSERT_EQ(10, *enumerator); ASSERT_TRUE(++enumerator); ASSERT_EQ(11, *enumerator); ASSERT_TRUE(++enumerator); ASSERT_EQ(20, *enumerator); ASSERT_FALSE(++enumerator); ASSERT_FALSE(++enumerator); } TEST(SelectTest, CopyTest) { struct Person { std::string _name; double _age; }; std::vector<Person> list = {Person{"Oliver", 10}, Person{"Hanna", 11}, Person{"Peter", 20}}; auto enumerator = DefQuery::from(list).select([](const Person& person) { return person._age; }); auto enumeratorCopy = enumerator; ASSERT_TRUE(++enumerator); ASSERT_EQ(10, *enumerator); ASSERT_TRUE(++enumerator); ASSERT_EQ(11, *enumerator); ASSERT_TRUE(++enumerator); ASSERT_EQ(20, *enumerator); ASSERT_FALSE(++enumerator); ASSERT_FALSE(++enumerator); ASSERT_TRUE(++enumeratorCopy); ASSERT_EQ(10, *enumeratorCopy); ASSERT_TRUE(++enumeratorCopy); ASSERT_EQ(11, *enumeratorCopy); ASSERT_TRUE(++enumeratorCopy); ASSERT_EQ(20, *enumeratorCopy); ASSERT_FALSE(++enumeratorCopy); ASSERT_FALSE(++enumeratorCopy); } TEST(SelectTest, MoveTest) { struct Person { std::string _name; double _age; }; std::vector<Person> lis = {Person{"Oliver", 10}, Person{"Hanna", 11}, Person{"Peter", 20}}; auto enumerator = DefQuery::from(lis).select([](const Person& person) { return person._age; }); auto enumerator2 = std::move(enumerator); ASSERT_TRUE(++enumerator2); ASSERT_EQ(10, *enumerator2); ASSERT_TRUE(++enumerator2); ASSERT_EQ(11, *enumerator2); ASSERT_TRUE(++enumerator2); ASSERT_EQ(20, *enumerator2); ASSERT_FALSE(++enumerator2); ASSERT_FALSE(++enumerator2); ASSERT_FALSE(++enumerator); ASSERT_FALSE(++enumerator); }
23.718447
97
0.706918
[ "vector" ]
bc7b87a27ac30fa46de35ebe9c997ae158853096
8,305
cpp
C++
src/algorithms.cpp
vavilovm/photoeditor-project-cpp
c9f5e3ea3476b08e50bbad4befa37b452feae702
[ "MIT" ]
1
2022-02-14T22:34:13.000Z
2022-02-14T22:34:13.000Z
src/algorithms.cpp
vavilovm/photoeditor-project-cpp
c9f5e3ea3476b08e50bbad4befa37b452feae702
[ "MIT" ]
null
null
null
src/algorithms.cpp
vavilovm/photoeditor-project-cpp
c9f5e3ea3476b08e50bbad4befa37b452feae702
[ "MIT" ]
1
2020-02-27T17:37:11.000Z
2020-02-27T17:37:11.000Z
// // Created by mark on 27.02.2020. // #include "../include/algorithms.h" namespace image_algorithms { using namespace cv; cv::Mat takePicture(cv::VideoCapture camera) { cv::Mat image; while (!camera.isOpened()) { std::cout << "Failed to make connection to camera" << std::endl; camera.open(0); } camera >> image; flip(image, image, 1); return image; } cv::Mat crop(const cv::Mat& image, int w, int h, int x, int y) { return image(cv::Rect(x, y, w, h)); } cv::Mat gray(const cv::Mat& image) { cv::Mat bw; // black & white filter cvtColor(image, bw, cv::COLOR_BGR2GRAY); cvtColor(bw, bw, cv::COLOR_GRAY2BGR); return bw; } cv::Mat rotate_in_frame(const cv::Mat& image, double angle) { // get rotation matrix for rotating the image around its center in pixel coordinates cv::Point2f center((image.cols - 1) / 2.0, (image.rows - 1) / 2.0); cv::Mat rot = cv::getRotationMatrix2D(center, angle, 1.0); // determine bounding rectangle, center not relevant cv::Rect2f bbox = cv::RotatedRect(cv::Point2f(), image.size(), angle).boundingRect2f(); // adjust transformation matrix rot.at<double>(0, 2) += bbox.width / 2.0 - image.cols / 2.0; rot.at<double>(1, 2) += bbox.height / 2.0 - image.rows / 2.0; cv::Mat dst; cv::warpAffine(image, dst, rot, bbox.size()); return dst; } cv::Mat hsv_add_scalar(const cv::Mat& image, int h, int s, int v) { cv::Mat res; // convert to hsv cvtColor(image, res, COLOR_BGR2HSV);; //add scalar res += Scalar(h, s, v); // convert back to bgr cvtColor(res, res, COLOR_HSV2BGR); return res; } // value in [-100, 100] cv::Mat saturate(const cv::Mat& image, int value) { value += 100; double alpha = value / 100.0; cv::Mat tmp, res; addWeighted(image, alpha, gray(image), 1 - alpha, 0.0, res); return res; } cv::Mat brighten(const cv::Mat& image, int value) { // add value to "value" in hsv color space return hsv_add_scalar(image, 0, 0, value); } cv::Mat hue(const cv::Mat& image, int value) { // add value to hue in hsv color space return hsv_add_scalar(image, value); } cv::Mat contrast(const cv::Mat& image, int value) { cv::Mat res; // get factor double factor = (double) (259 * (value + 255)) / (255 * (259 - value)); // linear transformation // what it does here is basically: // C' = (C - 128) * (factor) + 128 image.convertTo(res, CV_8UC1, (factor), 128 * (1 - factor)); return res; } cv::Mat lighten(const cv::Mat& image, int value) { // simply add value to Lightness channel in // Lab color space return lab_add_scalar(image, value); } cv::Mat lab_add_scalar(const cv::Mat& image, int l, int a, int b) { cv::Mat res; // convert to Lab cvtColor(image, res, cv::COLOR_BGR2Lab);; // add scalar res += Scalar(l, a, b); // convert back to BGR cvtColor(res, res, cv::COLOR_Lab2BGR); return res; } cv::Mat blend(const cv::Mat& img1, const cv::Mat& img2, double alpha) { // get beta double beta = (1.0 - alpha); cv::Mat dst; // sum of images addWeighted(img1, alpha, img2, beta, 0.0, dst); return dst; } cv::Mat tint(const cv::Mat& image, int value) { // + green return image + Scalar(0, value, 0); } cv::Mat temperature(const cv::Mat& image, int value) { // - blue + red return image + Scalar(-value, 0, value); } cv::Mat blur(const cv::Mat& image, double value) { cv::Mat res; // basic gaussian blur with automatically made kernel GaussianBlur(image, res, Size(0, 0), value); return res; } cv::Mat sharpen(const cv::Mat& image, double value) { // get default blur of the image cv::Mat res = blur(image, 3); // just subtract blur image with given factor cv::addWeighted(image, 1 + value, res, -value, 0, res); return res; } cv::Mat transform_perspective(const cv::Mat& input, cv::Point2f outputQuad[4]) { cv::Mat res; // Input Quadilateral or Image plane coordinates Point2f inputQuad[4]; // Lambda Matrix Mat lambda(2, 4, CV_32FC1); // Set the lambda matrix the same type and size as input lambda = Mat::zeros(input.rows, input.cols, input.type()); // The 4 points that select quadilateral on the input , from top-left in clockwise order // These four pts are the sides of the rect box used as input inputQuad[0] = Point2f(0, 0); inputQuad[1] = Point2f(input.cols, 0); inputQuad[2] = Point2f(input.cols, input.rows); inputQuad[3] = Point2f(0, input.rows); // Get the Perspective Transform Matrix i.e. lambda lambda = getPerspectiveTransform(inputQuad, outputQuad); // Apply the Perspective Transform just found to the src image warpPerspective(input, res, lambda, res.size()); return res; } cv::Mat apply_color(const cv::Mat& mat, int r, int g, int b, double alpha) { cv::Mat m(mat.rows, mat.cols, CV_8UC3, cv::Scalar(b, g, r)); return blend(mat, m, 1 - alpha); } Crop::Crop(int width, int height, int x, int y) : w{width}, h{height}, x{x}, y{y} {} cv::Mat Crop::execute(const cv::Mat& image) const { return crop(image, w, h, x, y); } RotateInFrame::RotateInFrame(double angle) : angle{angle} {} cv::Mat RotateInFrame::execute(const cv::Mat& base_image) const { return rotate_in_frame(base_image, angle); } Saturate::Saturate(int value) : value{value} { } cv::Mat Saturate::execute(const cv::Mat& image) const { return saturate(image, value); } Brighten::Brighten(int value) : value{value} { } cv::Mat Brighten::execute(const Mat& image) const { return brighten(image, value); } Lighten::Lighten(int value) : value{value} { } cv::Mat Lighten::execute(const Mat& image) const { return lighten(image, value); } Hue::Hue(int value) : value{value} { } cv::Mat Hue::execute(const Mat& image) const { return hue(image, value); } Contrast::Contrast(int value) : value{value} { } cv::Mat Contrast::execute(const Mat& image) const { return contrast(image, value); } cv::Mat Gray::execute(const Mat& image) const { return gray(image); } Blend::Blend(const Mat& image_2, double alpha) : image_2{image_2}, value{alpha} { } cv::Mat Blend::execute(const Mat& image_1) const { return blend(image_1, image_2, value); } Tint::Tint(int value) : value{value} { } cv::Mat Tint::execute(const Mat& image) const { return tint(image, value); } Temperature::Temperature(int value) : value{value} { } cv::Mat Temperature::execute(const Mat& image) const { return temperature(image, value); } Blur::Blur(double value) : value{value} { } cv::Mat Blur::execute(const Mat& image) const { return blur(image, value); } Sharpen::Sharpen(double value) : value{value} { } cv::Mat Sharpen::execute(const Mat& image) const { return sharpen(image, value); } ApplyColor::ApplyColor(int r, int g, int b, double alpha) : r{r}, g{g}, b{b}, alpha{alpha} { } cv::Mat ApplyColor::execute(const Mat& image) const { return apply_color(image, r, g, b, alpha); } TransformPerspective::TransformPerspective(cv::Point2f* outputQuad) : outputQuad{outputQuad} { } cv::Mat TransformPerspective::execute(const Mat& image) const { return transform_perspective(image, outputQuad); } cv::Mat Nothing::execute(const Mat& image) const { return image; } }
24.865269
98
0.571463
[ "transform" ]
bc960f8627a514dbb3ea801baec4b6264efefb45
15,135
cpp
C++
Engine/Plugins/MovieScene/ActorSequenceEditor/Source/ActorSequenceEditor/Private/ActorSequenceEditorTabSummoner.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Plugins/MovieScene/ActorSequenceEditor/Source/ActorSequenceEditor/Private/ActorSequenceEditorTabSummoner.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Plugins/MovieScene/ActorSequenceEditor/Source/ActorSequenceEditor/Private/ActorSequenceEditorTabSummoner.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "ActorSequenceEditorTabSummoner.h" #include "ActorSequence.h" #include "ISequencer.h" #include "ISequencerModule.h" #include "LevelEditorSequencerIntegration.h" #include "SSCSEditor.h" #include "SlateIconFinder.h" #include "BlueprintEditorUtils.h" #include "EditorStyleSet.h" #include "Widgets/Images/SImage.h" #include "Editor.h" #include "ScopedTransaction.h" #include "Framework/MultiBox/MultiBoxBuilder.h" #include "Framework/Application/SlateApplication.h" #define LOCTEXT_NAMESPACE "ActorSequenceEditorSummoner" DECLARE_DELEGATE_OneParam(FOnComponentSelected, TSharedPtr<FSCSEditorTreeNode>); DECLARE_DELEGATE_RetVal_OneParam(bool, FIsComponentValid, UActorComponent*); class SComponentSelectionTree : public SCompoundWidget { public: SLATE_BEGIN_ARGS(SComponentSelectionTree) : _IsInEditMode(false) {} SLATE_EVENT(FOnComponentSelected, OnComponentSelected) SLATE_EVENT(FIsComponentValid, IsComponentValid) SLATE_ARGUMENT(bool, IsInEditMode) SLATE_END_ARGS() void Construct(const FArguments& InArgs, AActor* InPreviewActor) { bIsInEditMode = InArgs._IsInEditMode; OnComponentSelected = InArgs._OnComponentSelected; IsComponentValid = InArgs._IsComponentValid; ChildSlot [ SAssignNew(TreeView, STreeView<TSharedPtr<FSCSEditorTreeNode>>) .TreeItemsSource(&RootNodes) .SelectionMode(ESelectionMode::Single) .OnGenerateRow(this, &SComponentSelectionTree::GenerateRow) .OnGetChildren(this, &SComponentSelectionTree::OnGetChildNodes) .OnSelectionChanged(this, &SComponentSelectionTree::OnSelectionChanged) .ItemHeight(24) ]; BuildTree(InPreviewActor); if (RootNodes.Num() == 0) { ChildSlot [ SNew(SBox) .Padding(FMargin(5.f)) [ SNew(STextBlock) .Text(LOCTEXT("NoValidComponentsFound", "No valid components available")) ] ]; } } void BuildTree(AActor* Actor) { RootNodes.Reset(); ObjectToNode.Reset(); for (UActorComponent* Component : TInlineComponentArray<UActorComponent*>(Actor)) { if (IsComponentVisibleInTree(Component)) { FindOrAddNodeForComponent(Component); } } } private: void OnSelectionChanged(TSharedPtr<FSCSEditorTreeNode> InNode, ESelectInfo::Type SelectInfo) { OnComponentSelected.ExecuteIfBound(InNode); } void OnGetChildNodes(TSharedPtr<FSCSEditorTreeNode> InNodePtr, TArray<TSharedPtr<FSCSEditorTreeNode>>& OutChildren) { OutChildren = InNodePtr->GetChildren(); } TSharedRef<ITableRow> GenerateRow(TSharedPtr<FSCSEditorTreeNode> InNodePtr, const TSharedRef<STableViewBase>& OwnerTable) { const FSlateBrush* ComponentIcon = FEditorStyle::GetBrush("SCS.NativeComponent"); if (InNodePtr->GetComponentTemplate() != NULL) { ComponentIcon = FSlateIconFinder::FindIconBrushForClass( InNodePtr->GetComponentTemplate()->GetClass(), TEXT("SCS.Component") ); } FText Label = InNodePtr->IsInherited() && !bIsInEditMode ? FText::Format(LOCTEXT("NativeComponentFormatString","{0} (Inherited)"), FText::FromString(InNodePtr->GetDisplayString())) : FText::FromString(InNodePtr->GetDisplayString()); TSharedRef<STableRow<FSCSEditorTreeNodePtrType>> Row = SNew(STableRow<FSCSEditorTreeNodePtrType>, OwnerTable).Padding(FMargin(0.f, 0.f, 0.f, 4.f)); Row->SetContent( SNew(SHorizontalBox) +SHorizontalBox::Slot() .AutoWidth() .VAlign(VAlign_Center) [ SNew(SImage) .Image(ComponentIcon) .ColorAndOpacity(SSCS_RowWidget::GetColorTintForIcon(InNodePtr)) ] +SHorizontalBox::Slot() .VAlign(VAlign_Center) .Padding(2, 0, 0, 0) [ SNew(STextBlock) .Text(Label) ]); return Row; } bool IsComponentVisibleInTree(UActorComponent* ActorComponent) const { return !IsComponentValid.IsBound() || IsComponentValid.Execute(ActorComponent); } TSharedPtr<FSCSEditorTreeNode> FindOrAddNodeForComponent(UActorComponent* ActorComponent) { if (ActorComponent->IsEditorOnly()) { return nullptr; } if (TSharedPtr<FSCSEditorTreeNode>* Existing = ObjectToNode.Find(ActorComponent)) { return *Existing; } else if (USceneComponent* SceneComponent = Cast<USceneComponent>(ActorComponent)) { if (UActorComponent* Parent = SceneComponent->GetAttachParent()) { TSharedPtr<FSCSEditorTreeNode> ParentNode = FindOrAddNodeForComponent(Parent); if (!ParentNode.IsValid()) { return nullptr; } TreeView->SetItemExpansion(ParentNode, true); TSharedPtr<FSCSEditorTreeNode> ChildNode = ParentNode->AddChildFromComponent(ActorComponent); ObjectToNode.Add(ActorComponent, ChildNode); return ChildNode; } } TSharedPtr<FSCSEditorTreeNode> RootNode = FSCSEditorTreeNode::FactoryNodeFromComponent(ActorComponent); RootNodes.Add(RootNode); ObjectToNode.Add(ActorComponent, RootNode); TreeView->SetItemExpansion(RootNode, true); return RootNode; } private: bool bIsInEditMode; FOnComponentSelected OnComponentSelected; FIsComponentValid IsComponentValid; TSharedPtr<STreeView<TSharedPtr<FSCSEditorTreeNode>>> TreeView; TMap<FObjectKey, TSharedPtr<FSCSEditorTreeNode>> ObjectToNode; TArray<TSharedPtr<FSCSEditorTreeNode>> RootNodes; }; class SActorSequenceEditorWidgetImpl : public SCompoundWidget { public: SLATE_BEGIN_ARGS(SActorSequenceEditorWidgetImpl){} SLATE_END_ARGS(); ~SActorSequenceEditorWidgetImpl() { if (Sequencer.IsValid()) { FLevelEditorSequencerIntegration::Get().RemoveSequencer(Sequencer.ToSharedRef()); Sequencer->Close(); Sequencer = nullptr; } GEditor->OnBlueprintPreCompile().Remove(OnBlueprintPreCompileHandle); FCoreUObjectDelegates::OnObjectSaved.Remove(OnObjectSavedHandle); } void Construct(const FArguments&, TWeakPtr<FBlueprintEditor> InBlueprintEditor) { OnBlueprintPreCompileHandle = GEditor->OnBlueprintPreCompile().AddSP(this, &SActorSequenceEditorWidgetImpl::OnBlueprintPreCompile); OnObjectSavedHandle = FCoreUObjectDelegates::OnObjectSaved.AddSP(this, &SActorSequenceEditorWidgetImpl::OnObjectPreSave); WeakBlueprintEditor = InBlueprintEditor; ChildSlot [ SAssignNew(Content, SBox) .MinDesiredHeight(200) ]; } FText GetDisplayLabel() const { UActorSequence* Sequence = WeakSequence.Get(); return Sequence ? Sequence->GetDisplayName() : LOCTEXT("DefaultSequencerLabel", "Sequencer"); } UActorSequence* GetActorSequence() const { return WeakSequence.Get(); } UObject* GetPlaybackContext() const { UActorSequence* LocalActorSequence = GetActorSequence(); if (LocalActorSequence) { if (AActor* Actor = LocalActorSequence->GetTypedOuter<AActor>()) { return Actor; } else if (UBlueprintGeneratedClass* GeneratedClass = LocalActorSequence->GetTypedOuter<UBlueprintGeneratedClass>()) { return GeneratedClass->SimpleConstructionScript->GetComponentEditorActorInstance(); } } return nullptr; } TArray<UObject*> GetEventContexts() const { TArray<UObject*> Contexts; if (auto* Context = GetPlaybackContext()) { Contexts.Add(Context); } return Contexts; } void SetActorSequence(UActorSequence* NewSequence) { if (UActorSequence* OldSequence = WeakSequence.Get()) { if (OnSequenceChangedHandle.IsValid()) { OldSequence->OnSignatureChanged().Remove(OnSequenceChangedHandle); } } WeakSequence = NewSequence; if (NewSequence) { OnSequenceChangedHandle = NewSequence->OnSignatureChanged().AddSP(this, &SActorSequenceEditorWidgetImpl::OnSequenceChanged); } // If we already have a sequencer open, just assign the sequence if (Sequencer.IsValid() && NewSequence) { if (Sequencer->GetRootMovieSceneSequence() != NewSequence) { Sequencer->ResetToNewRootSequence(*NewSequence); } return; } // If we're setting the sequence to none, destroy sequencer if (!NewSequence) { if (Sequencer.IsValid()) { FLevelEditorSequencerIntegration::Get().RemoveSequencer(Sequencer.ToSharedRef()); Sequencer->Close(); Sequencer = nullptr; } Content->SetContent(SNew(STextBlock).Text(LOCTEXT("NothingSelected", "Select a sequence"))); return; } // We need to initialize a new sequencer instance FSequencerInitParams SequencerInitParams; { TWeakObjectPtr<UActorSequence> LocalWeakSequence = NewSequence; SequencerInitParams.RootSequence = NewSequence; SequencerInitParams.EventContexts = TAttribute<TArray<UObject*>>(this, &SActorSequenceEditorWidgetImpl::GetEventContexts); SequencerInitParams.PlaybackContext = TAttribute<UObject*>(this, &SActorSequenceEditorWidgetImpl::GetPlaybackContext); TSharedRef<FExtender> AddMenuExtender = MakeShareable(new FExtender); AddMenuExtender->AddMenuExtension("AddTracks", EExtensionHook::Before, nullptr, FMenuExtensionDelegate::CreateLambda([=](FMenuBuilder& MenuBuilder){ MenuBuilder.AddSubMenu( LOCTEXT("AddComponent_Label", "Component"), LOCTEXT("AddComponent_ToolTip", "Add a binding to one of this actor's components and allow it to be animated by Sequencer"), FNewMenuDelegate::CreateRaw(this, &SActorSequenceEditorWidgetImpl::AddPossessComponentMenuExtensions), false /*bInOpenSubMenuOnClick*/, FSlateIcon()//"LevelSequenceEditorStyle", "LevelSequenceEditor.PossessNewActor") ); }) ); SequencerInitParams.ViewParams.bReadOnly = !WeakBlueprintEditor.IsValid() && !NewSequence->IsEditable(); SequencerInitParams.bEditWithinLevelEditor = false; SequencerInitParams.ViewParams.AddMenuExtender = AddMenuExtender; SequencerInitParams.ViewParams.UniqueName = "EmbeddedActorSequenceEditor"; SequencerInitParams.ViewParams.OnReceivedFocus.BindRaw(this, &SActorSequenceEditorWidgetImpl::OnSequencerReceivedFocus); } Sequencer = FModuleManager::LoadModuleChecked<ISequencerModule>("Sequencer").CreateSequencer(SequencerInitParams); Content->SetContent(Sequencer->GetSequencerWidget()); FLevelEditorSequencerIntegrationOptions Options; Options.bRequiresLevelEvents = true; Options.bRequiresActorEvents = false; Options.bCanRecord = false; FLevelEditorSequencerIntegration::Get().AddSequencer(Sequencer.ToSharedRef(), Options); } void OnSequencerReceivedFocus() { if (Sequencer.IsValid()) { FLevelEditorSequencerIntegration::Get().OnSequencerReceivedFocus(Sequencer.ToSharedRef()); } } void OnObjectPreSave(UObject* InObject) { TSharedPtr<FBlueprintEditor> BlueprintEditor = WeakBlueprintEditor.Pin(); if (Sequencer.IsValid() && BlueprintEditor.IsValid() && InObject && InObject == BlueprintEditor->GetBlueprintObj()) { Sequencer->RestorePreAnimatedState(); } } void OnBlueprintPreCompile(UBlueprint* InBlueprint) { TSharedPtr<FBlueprintEditor> BlueprintEditor = WeakBlueprintEditor.Pin(); if (Sequencer.IsValid() && BlueprintEditor.IsValid() && InBlueprint && InBlueprint == BlueprintEditor->GetBlueprintObj()) { Sequencer->RestorePreAnimatedState(); } } void OnSelectionUpdated(TSharedPtr<FSCSEditorTreeNode> SelectedNode) { if (SelectedNode->GetNodeType() != FSCSEditorTreeNode::ComponentNode) { return; } UActorComponent* EditingComponent = nullptr; TSharedPtr<FBlueprintEditor> BlueprintEditor = WeakBlueprintEditor.Pin(); if (BlueprintEditor.IsValid()) { UBlueprint* Blueprint = BlueprintEditor->GetBlueprintObj(); if (Blueprint) { EditingComponent = SelectedNode->GetEditableComponentTemplate(Blueprint); } } else if (AActor* Actor = GetPreviewActor()) { EditingComponent = SelectedNode->FindComponentInstanceInActor(Actor); } if (EditingComponent) { const FScopedTransaction Transaction(LOCTEXT("AddComponentToSequencer", "Add component to Sequencer")); Sequencer->GetHandleToObject(EditingComponent, true); } FSlateApplication::Get().DismissAllMenus(); } void AddPossessComponentMenuExtensions(FMenuBuilder& MenuBuilder) { AActor* Actor = GetPreviewActor(); if (!Actor) { return; } Sequencer->State.ClearObjectCaches(*Sequencer); TSet<UObject*> AllBoundObjects; AllBoundObjects.Add(GetOwnerComponent()); UMovieScene* MovieScene = Sequencer->GetFocusedMovieSceneSequence()->GetMovieScene(); for (int32 Index = 0; Index < MovieScene->GetPossessableCount(); ++Index) { FMovieScenePossessable& Possessable = MovieScene->GetPossessable(Index); for (TWeakObjectPtr<> WeakObject : Sequencer->FindBoundObjects(Possessable.GetGuid(), Sequencer->GetFocusedTemplateID())) { if (UObject* Object = WeakObject.Get()) { AllBoundObjects.Add(Object); } } } bool bIdent = false; MenuBuilder.AddWidget( SNew(SComponentSelectionTree, Actor) .IsInEditMode(WeakBlueprintEditor.Pin().IsValid()) .OnComponentSelected(this, &SActorSequenceEditorWidgetImpl::OnSelectionUpdated) .IsComponentValid_Lambda( [AllBoundObjects](UActorComponent* Component) { return !AllBoundObjects.Contains(Component); } ) , FText(), !bIdent ); } AActor* GetPreviewActor() const { TSharedPtr<FBlueprintEditor> BlueprintEditor = WeakBlueprintEditor.Pin(); if (BlueprintEditor.IsValid()) { return BlueprintEditor->GetPreviewActor(); } if (UActorSequence* Sequence = WeakSequence.Get()) { return Sequence->GetTypedOuter<AActor>(); } return nullptr; } UActorComponent* GetOwnerComponent() const { UActorSequence* ActorSequence = WeakSequence.Get(); AActor* Actor = ActorSequence ? GetPreviewActor() : nullptr; return Actor ? FindObject<UActorComponent>(Actor, *ActorSequence->GetOuter()->GetName()) : nullptr; } void OnSequenceChanged() { UActorSequence* ActorSequence = WeakSequence.Get(); UBlueprint* Blueprint = ActorSequence ? ActorSequence->GetParentBlueprint() : nullptr; if (Blueprint) { FBlueprintEditorUtils::MarkBlueprintAsModified(Blueprint); } } private: TWeakObjectPtr<UActorSequence> WeakSequence; TWeakPtr<FBlueprintEditor> WeakBlueprintEditor; TSharedPtr<SBox> Content; TSharedPtr<ISequencer> Sequencer; FDelegateHandle OnBlueprintPreCompileHandle; FDelegateHandle OnObjectSavedHandle; FDelegateHandle OnSequenceChangedHandle; }; void SActorSequenceEditorWidget::Construct(const FArguments&, TWeakPtr<FBlueprintEditor> InBlueprintEditor) { ChildSlot [ SAssignNew(Impl, SActorSequenceEditorWidgetImpl, InBlueprintEditor) ]; } FText SActorSequenceEditorWidget::GetDisplayLabel() const { return Impl.Pin()->GetDisplayLabel(); } void SActorSequenceEditorWidget::AssignSequence(UActorSequence* NewActorSequence) { Impl.Pin()->SetActorSequence(NewActorSequence); } UActorSequence* SActorSequenceEditorWidget::GetSequence() const { return Impl.Pin()->GetActorSequence(); } FActorSequenceEditorSummoner::FActorSequenceEditorSummoner(TSharedPtr<FBlueprintEditor> BlueprintEditor) : FWorkflowTabFactory("EmbeddedSequenceID", BlueprintEditor) , WeakBlueprintEditor(BlueprintEditor) { bIsSingleton = true; TabLabel = LOCTEXT("SequencerTabName", "Sequencer"); } TSharedRef<SWidget> FActorSequenceEditorSummoner::CreateTabBody(const FWorkflowTabSpawnInfo& Info) const { return SNew(SActorSequenceEditorWidget, WeakBlueprintEditor); } #undef LOCTEXT_NAMESPACE
28.719165
149
0.762273
[ "object" ]
bc9a85377db909fe3f64313e8ba47eb3ad270527
3,245
cpp
C++
src/cless/new_blockdt_cl.cpp
roarkhabegger/athena-public-version
3446d2f4601c1dbbfd7a98d4f53335d97e21e195
[ "BSD-3-Clause" ]
1
2021-03-05T20:59:04.000Z
2021-03-05T20:59:04.000Z
src/cless/new_blockdt_cl.cpp
roarkhabegger/athena-public-version
3446d2f4601c1dbbfd7a98d4f53335d97e21e195
[ "BSD-3-Clause" ]
null
null
null
src/cless/new_blockdt_cl.cpp
roarkhabegger/athena-public-version
3446d2f4601c1dbbfd7a98d4f53335d97e21e195
[ "BSD-3-Clause" ]
2
2019-02-26T18:49:13.000Z
2019-07-22T17:04:41.000Z
//======================================================================================== // Athena++ astrophysical MHD code // Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors // Licensed under the 3-clause BSD License, see LICENSE file for details //======================================================================================== //! \file new_blockdt.cpp // \brief computes timestep using CFL condition on a MEshBlock // C/C++ headers #include <algorithm> // min() #include <cfloat> // FLT_MAX #include <cmath> // fabs(), sqrt() // Athena++ headers #include "cless.hpp" #include "../athena.hpp" #include "../athena_arrays.hpp" #include "../eos/eos.hpp" #include "../mesh/mesh.hpp" #include "../coordinates/coordinates.hpp" #include "../cless/cless.hpp" // MPI/OpenMP header #ifdef MPI_PARALLEL #include <mpi.h> #endif #ifdef OPENMP_PARALLEL #include <omp.h> #endif //---------------------------------------------------------------------------------------- // \!fn Real Cless::NewBlockTimeStep(void) // \brief calculate the minimum timestep within a MeshBlock // only used in CLESS_ONLY mode Real Cless::NewBlockTimeStepCL(void) { MeshBlock *pmb=pmy_block; int is = pmb->is; int js = pmb->js; int ks = pmb->ks; int ie = pmb->ie; int je = pmb->je; int ke = pmb->ke; AthenaArray<Real> w,bcc,b_x1f,b_x2f,b_x3f, wcl; if (CLESS_ENABLED) { wcl.InitWithShallowCopy(pmb->pcless->w); } AthenaArray<Real> dt1, dt2, dt3; dt1.InitWithShallowCopy(dt1_); dt2.InitWithShallowCopy(dt2_); dt3.InitWithShallowCopy(dt3_); Real wi[(NWAVE+NINT)]; Real wicl[(NWAVECL)]; Real min_dt = (FLT_MAX); for (int k=ks; k<=ke; ++k) { for (int j=js; j<=je; ++j) { pmb->pcoord->CenterWidth1(k,j,is,ie,dt1); pmb->pcoord->CenterWidth2(k,j,is,ie,dt2); pmb->pcoord->CenterWidth3(k,j,is,ie,dt3); #pragma ivdep for (int i=is; i<=ie; ++i) { Real c1f, c2f, c3f; wicl[IDN ] = wcl(IDN ,k,j,i); wicl[IVX ] = wcl(IVX ,k,j,i); wicl[IVY ] = wcl(IVY ,k,j,i); wicl[IVZ ] = wcl(IVZ ,k,j,i); wicl[IP11] = wcl(IP11,k,j,i); wicl[IP22] = wcl(IP22,k,j,i); wicl[IP33] = wcl(IP33,k,j,i); wicl[IP12] = wcl(IP12,k,j,i); wicl[IP13] = wcl(IP13,k,j,i); wicl[IP23] = wcl(IP23,k,j,i); pmb->peos->SoundSpeedsCL(wicl,&c1f,&c2f,&c3f); dt1(i) /= fabs(wicl[IVX] + c1f); dt2(i) /= fabs(wicl[IVY] + c2f); dt3(i) /= fabs(wicl[IVZ] + c3f); } // compute minimum of (v1 +/- C) for (int i=is; i<=ie; ++i) { Real& dt_1 = dt1(i); min_dt = std::min(min_dt,dt_1); } // if grid is 2D/3D, compute minimum of (v2 +/- C) if (pmb->block_size.nx2 > 1) { for (int i=is; i<=ie; ++i) { Real& dt_2 = dt2(i); min_dt = std::min(min_dt,dt_2); } } // if grid is 3D, compute minimum of (v3 +/- C) if (pmb->block_size.nx3 > 1) { for (int i=is; i<=ie; ++i) { Real& dt_3 = dt3(i); min_dt = std::min(min_dt,dt_3); } } } } min_dt *= pmb->pmy_mesh->cfl_number; //if (UserTimeStep_!=NULL) { // min_dt = std::min(min_dt, UserTimeStep_(pmb)); //} pmb->new_block_dt=min_dt; return min_dt; }
27.974138
90
0.540832
[ "mesh", "3d" ]
bc9d64e764519fded38757b36353a23aca8c18b0
9,196
cpp
C++
src/particle_filter.cpp
ramiejleh/Particle-Filter-Localization
268b2d05795ab21ab828f223176ad5228728b67d
[ "MIT" ]
null
null
null
src/particle_filter.cpp
ramiejleh/Particle-Filter-Localization
268b2d05795ab21ab828f223176ad5228728b67d
[ "MIT" ]
null
null
null
src/particle_filter.cpp
ramiejleh/Particle-Filter-Localization
268b2d05795ab21ab828f223176ad5228728b67d
[ "MIT" ]
null
null
null
/** * particle_filter.cpp * * Created on: Dec 12, 2016 * Author: Tiffany Huang */ #include "particle_filter.h" #include <math.h> #include <algorithm> #include <iostream> #include <iterator> #include <numeric> #include <random> #include <string> #include <vector> #include "helper_functions.h" using std::string; using std::vector; void ParticleFilter::init(double x, double y, double theta, double std[]) { /** * Done: Set the number of particles. Initialize all particles to * first position (based on estimates of x, y, theta and their uncertainties * from GPS) and all weights to 1. * Done: Add random Gaussian noise to each particle. * NOTE: Consult particle_filter.h for more information about this method * (and others in this file). */ std::default_random_engine gen; // resize the vectors of particles num_particles = 100; particles.resize(num_particles); // create normal distributions for x, y, and theta std::normal_distribution<double> dist_x(x, std[0]); std::normal_distribution<double> dist_y(y, std[1]); std::normal_distribution<double> dist_theta(theta, std[2]); // generate the particles for(int i = 0; i < num_particles; i++){ particles[i].x = dist_x(gen); particles[i].y = dist_y(gen); particles[i].theta = dist_theta(gen); particles[i].weight = 1; } is_initialized = true; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { /** * Done: Add measurements to each particle and add random Gaussian noise. * NOTE: When adding noise you may find std::normal_distribution * and std::default_random_engine useful. * http://en.cppreference.com/w/cpp/numeric/random/normal_distribution * http://www.cplusplus.com/reference/random/default_random_engine/ */ // Engine for later generation of particles std::default_random_engine gen; // generate random Gaussian noise std::normal_distribution<double> dist_x(0, std_pos[0]); std::normal_distribution<double> dist_y(0, std_pos[1]); std::normal_distribution<double> dist_theta(0, std_pos[2]); for(int i = 0; i < num_particles; i++){ // add measurements to each particle if(fabs(yaw_rate) < 0.0001){ // constant velocity particles[i].x += velocity * delta_t * cos(particles[i].theta); particles[i].y += velocity * delta_t * sin(particles[i].theta); } else { particles[i].x += velocity / yaw_rate * ( sin( particles[i].theta + yaw_rate*delta_t ) - sin(particles[i].theta) ); particles[i].y += velocity / yaw_rate * ( cos( particles[i].theta ) - cos( particles[i].theta + yaw_rate*delta_t ) ); particles[i].theta += yaw_rate * delta_t; } // predicted particles with added sensor noise particles[i].x += dist_x(gen); particles[i].y += dist_y(gen); particles[i].theta += dist_theta(gen); } } void ParticleFilter::dataAssociation(vector<LandmarkObs> predicted, vector<LandmarkObs>& observations) { /** * Done: Find the predicted measurement that is closest to each * observed measurement and assign the observed measurement to this * particular landmark. * NOTE: this method will NOT be called by the grading code. But you will * probably find it useful to implement this method and use it as a helper * during the updateWeights phase. */ for (unsigned int i = 0; i < observations.size(); i++) { // For each observation // Initialize min distance as a high number. double min_distance = std::numeric_limits<double>::max(); for (unsigned j = 0; j < predicted.size(); j++ ) { // For each predition. double distance = dist(predicted[j].x, predicted[j].y, observations[i].x, observations[i].y); // If the "distance" is less than min, stored the id and update min. if ( distance < min_distance ) { min_distance = distance; observations[i].id = predicted[j].id; } } } } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const vector<LandmarkObs> &observations, const Map &map_landmarks) { /** * Done: Update the weights of each particle using a mult-variate Gaussian * distribution. You can read more about this distribution here: * https://en.wikipedia.org/wiki/Multivariate_normal_distribution * NOTE: The observations are given in the VEHICLE'S coordinate system. * Your particles are located according to the MAP'S coordinate system. * You will need to transform between the two systems. Keep in mind that * this transformation requires both rotation AND translation (but no scaling). * The following is a good resource for the theory: * https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm * and the following is a good resource for the actual equation to implement * (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html */ // Iterate through each particle for(int i = 0; i < num_particles; i++){ particles[i].weight = 1.0; // Set up landmarks vector<LandmarkObs> predictions; for(unsigned int j = 0; j < map_landmarks.landmark_list.size(); j++){ const Map::single_landmark_s landmark = map_landmarks.landmark_list[j]; double distance = dist(particles[i].x, particles[i].y, landmark.x_f, landmark.y_f); if( distance < sensor_range){ // if the landmark is within the sensor range, save it to predictions predictions.push_back(LandmarkObs{landmark.id_i, landmark.x_f, landmark.y_f}); } } // Convert vehicle observations coordinates to map coordinates vector<LandmarkObs> observations_map; double cos_theta = cos(particles[i].theta); double sin_theta = sin(particles[i].theta); for(unsigned int k = 0; k < observations.size(); k++){ const LandmarkObs observation = observations[k]; LandmarkObs temp; temp.x = observation.x * cos_theta - observation.y * sin_theta + particles[i].x; temp.y = observation.x * sin_theta + observation.y * cos_theta + particles[i].y; observations_map.push_back(temp); } // Find landmark index for each observation dataAssociation(predictions, observations_map); // Update the particle's weight: for(unsigned int o = 0; o < observations_map.size(); o++){ const LandmarkObs observation_map = observations_map[o]; Map::single_landmark_s landmark = map_landmarks.landmark_list.at(observation_map.id-1); double x_term = pow(observation_map.x - landmark.x_f, 2) / (2 * pow(std_landmark[0], 2)); double y_term = pow(observation_map.y - landmark.y_f, 2) / (2 * pow(std_landmark[1], 2)); double w = exp(-(x_term + y_term)) / (2 * M_PI * std_landmark[0] * std_landmark[1]); particles[i].weight *= w; } weights.push_back(particles[i].weight); } } void ParticleFilter::resample() { /** * Done: Resample particles with replacement with probability proportional * to their weight. * NOTE: You may find std::discrete_distribution helpful here. * http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution */ // Vector for new particles vector<Particle> new_particles (num_particles); // Use discrete distribution to return particles by weight std::random_device rd; std::default_random_engine gen(rd()); for (int i = 0; i < num_particles; i++) { std::discrete_distribution<int> index(weights.begin(), weights.end()); new_particles[i] = particles[index(gen)]; } // Replace old particles with the resampled particles particles = new_particles; weights.clear(); } void ParticleFilter::SetAssociations(Particle& particle, const vector<int>& associations, const vector<double>& sense_x, const vector<double>& sense_y) { // particle: the particle to which assign each listed association, // and association's (x,y) world coordinates mapping // associations: The landmark id that goes along with each listed association // sense_x: the associations x mapping already converted to world coordinates // sense_y: the associations y mapping already converted to world coordinates particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; std::stringstream ss; copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseCoord(Particle best, string coord) { vector<double> v; if (coord == "X") { v = best.sense_x; } else { v = best.sense_y; } std::stringstream ss; copy(v.begin(), v.end(), std::ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; }
37.688525
123
0.671161
[ "vector", "transform" ]