text
stringlengths 54
60.6k
|
---|
<commit_before>// Scintilla source code edit control
/** @file LineMarker.cxx
** Defines the look of a line marker in the margin .
**/
// Copyright 1998-2003 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <string.h>
#include "Platform.h"
#include "Scintilla.h"
#include "XPM.h"
#include "LineMarker.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
void LineMarker::RefreshColourPalette(Palette &pal, bool want) {
pal.WantFind(fore, want);
pal.WantFind(back, want);
if (pxpm) {
pxpm->RefreshColourPalette(pal, want);
}
}
void LineMarker::SetXPM(const char *textForm) {
delete pxpm;
pxpm = new XPM(textForm);
markType = SC_MARK_PIXMAP;
}
void LineMarker::SetXPM(const char * const *linesForm) {
delete pxpm;
pxpm = new XPM(linesForm);
markType = SC_MARK_PIXMAP;
}
static void DrawBox(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore, ColourAllocated back) {
PRectangle rc;
rc.left = centreX - armSize;
rc.top = centreY - armSize;
rc.right = centreX + armSize + 1;
rc.bottom = centreY + armSize + 1;
surface->RectangleDraw(rc, back, fore);
}
static void DrawCircle(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore, ColourAllocated back) {
PRectangle rcCircle;
rcCircle.left = centreX - armSize;
rcCircle.top = centreY - armSize;
rcCircle.right = centreX + armSize + 1;
rcCircle.bottom = centreY + armSize + 1;
surface->Ellipse(rcCircle, back, fore);
}
static void DrawPlus(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore) {
PRectangle rcV(centreX, centreY - armSize + 2, centreX + 1, centreY + armSize - 2 + 1);
surface->FillRectangle(rcV, fore);
PRectangle rcH(centreX - armSize + 2, centreY, centreX + armSize - 2 + 1, centreY+1);
surface->FillRectangle(rcH, fore);
}
static void DrawMinus(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore) {
PRectangle rcH(centreX - armSize + 2, centreY, centreX + armSize - 2 + 1, centreY+1);
surface->FillRectangle(rcH, fore);
}
void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharacter) {
if ((markType == SC_MARK_PIXMAP) && (pxpm)) {
pxpm->Draw(surface, rcWhole);
return;
}
// Restrict most shapes a bit
PRectangle rc = rcWhole;
rc.top++;
rc.bottom--;
int minDim = Platform::Minimum(rc.Width(), rc.Height());
minDim--; // Ensure does not go beyond edge
int centreX = (rc.right + rc.left) / 2;
int centreY = (rc.bottom + rc.top) / 2;
int dimOn2 = minDim / 2;
int dimOn4 = minDim / 4;
int blobSize = dimOn2-1;
int armSize = dimOn2-2;
if (rc.Width() > (rc.Height() * 2)) {
// Wide column is line number so move to left to try to avoid overlapping number
centreX = rc.left + dimOn2 + 1;
}
if (markType == SC_MARK_ROUNDRECT) {
PRectangle rcRounded = rc;
rcRounded.left = rc.left + 1;
rcRounded.right = rc.right - 1;
surface->RoundedRectangle(rcRounded, fore.allocated, back.allocated);
} else if (markType == SC_MARK_CIRCLE) {
PRectangle rcCircle;
rcCircle.left = centreX - dimOn2;
rcCircle.top = centreY - dimOn2;
rcCircle.right = centreX + dimOn2;
rcCircle.bottom = centreY + dimOn2;
surface->Ellipse(rcCircle, fore.allocated, back.allocated);
} else if (markType == SC_MARK_ARROW) {
Point pts[] = {
Point(centreX - dimOn4, centreY - dimOn2),
Point(centreX - dimOn4, centreY + dimOn2),
Point(centreX + dimOn2 - dimOn4, centreY),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_ARROWDOWN) {
Point pts[] = {
Point(centreX - dimOn2, centreY - dimOn4),
Point(centreX + dimOn2, centreY - dimOn4),
Point(centreX, centreY + dimOn2 - dimOn4),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_PLUS) {
Point pts[] = {
Point(centreX - armSize, centreY - 1),
Point(centreX - 1, centreY - 1),
Point(centreX - 1, centreY - armSize),
Point(centreX + 1, centreY - armSize),
Point(centreX + 1, centreY - 1),
Point(centreX + armSize, centreY -1),
Point(centreX + armSize, centreY +1),
Point(centreX + 1, centreY + 1),
Point(centreX + 1, centreY + armSize),
Point(centreX - 1, centreY + armSize),
Point(centreX - 1, centreY + 1),
Point(centreX - armSize, centreY + 1),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_MINUS) {
Point pts[] = {
Point(centreX - armSize, centreY - 1),
Point(centreX + armSize, centreY -1),
Point(centreX + armSize, centreY +1),
Point(centreX - armSize, centreY + 1),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_SMALLRECT) {
PRectangle rcSmall;
rcSmall.left = rc.left + 1;
rcSmall.top = rc.top + 2;
rcSmall.right = rc.right - 1;
rcSmall.bottom = rc.bottom - 2;
surface->RectangleDraw(rcSmall, fore.allocated, back.allocated);
} else if (markType == SC_MARK_EMPTY || markType == SC_MARK_BACKGROUND || markType == SC_MARK_UNDERLINE) {
// An invisible marker so don't draw anything
} else if (markType == SC_MARK_VLINE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_LCORNER) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rc.top + dimOn2);
surface->LineTo(rc.right - 2, rc.top + dimOn2);
} else if (markType == SC_MARK_TCORNER) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rc.top + dimOn2);
surface->LineTo(rc.right - 2, rc.top + dimOn2);
} else if (markType == SC_MARK_LCORNERCURVE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rc.top + dimOn2-3);
surface->LineTo(centreX+3, rc.top + dimOn2);
surface->LineTo(rc.right - 1, rc.top + dimOn2);
} else if (markType == SC_MARK_TCORNERCURVE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rc.top + dimOn2-3);
surface->LineTo(centreX+3, rc.top + dimOn2);
surface->LineTo(rc.right - 1, rc.top + dimOn2);
} else if (markType == SC_MARK_BOXPLUS) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
} else if (markType == SC_MARK_BOXPLUSCONNECTED) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_BOXMINUS) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_BOXMINUSCONNECTED) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_CIRCLEPLUS) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
} else if (markType == SC_MARK_CIRCLEPLUSCONNECTED) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_CIRCLEMINUS) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_CIRCLEMINUSCONNECTED) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType >= SC_MARK_CHARACTER) {
char character[1];
character[0] = static_cast<char>(markType - SC_MARK_CHARACTER);
int width = surface->WidthText(fontForCharacter, character, 1);
rc.left += (rc.Width() - width) / 2;
rc.right = rc.left + width;
surface->DrawTextClipped(rc, fontForCharacter, rc.bottom - 2,
character, 1, fore.allocated, back.allocated);
} else if (markType == SC_MARK_DOTDOTDOT) {
int right = centreX - 6;
for (int b=0; b<3; b++) {
PRectangle rcBlob(right, rc.bottom - 4, right + 2, rc.bottom-2);
surface->FillRectangle(rcBlob, fore.allocated);
right += 5;
}
} else if (markType == SC_MARK_ARROWS) {
surface->PenColour(fore.allocated);
int right = centreX - 2;
for (int b=0; b<3; b++) {
surface->MoveTo(right - 4, centreY - 4);
surface->LineTo(right, centreY);
surface->LineTo(right - 5, centreY + 5);
right += 4;
}
} else if (markType == SC_MARK_SHORTARROW) {
Point pts[] = {
Point(centreX, centreY + dimOn2),
Point(centreX + dimOn2, centreY),
Point(centreX, centreY - dimOn2),
Point(centreX, centreY - dimOn4),
Point(centreX - dimOn4, centreY - dimOn4),
Point(centreX - dimOn4, centreY + dimOn4),
Point(centreX, centreY + dimOn4),
Point(centreX, centreY + dimOn2),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_LEFTRECT) {
PRectangle rcLeft = rcWhole;
rcLeft.right = rcLeft.left + 4;
surface->FillRectangle(rcLeft, back.allocated);
} else { // SC_MARK_FULLRECT
surface->FillRectangle(rcWhole, back.allocated);
}
}
<commit_msg>Don't display SC_MARK_AVAILABLE markers.<commit_after>// Scintilla source code edit control
/** @file LineMarker.cxx
** Defines the look of a line marker in the margin .
**/
// Copyright 1998-2003 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <string.h>
#include "Platform.h"
#include "Scintilla.h"
#include "XPM.h"
#include "LineMarker.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
void LineMarker::RefreshColourPalette(Palette &pal, bool want) {
pal.WantFind(fore, want);
pal.WantFind(back, want);
if (pxpm) {
pxpm->RefreshColourPalette(pal, want);
}
}
void LineMarker::SetXPM(const char *textForm) {
delete pxpm;
pxpm = new XPM(textForm);
markType = SC_MARK_PIXMAP;
}
void LineMarker::SetXPM(const char * const *linesForm) {
delete pxpm;
pxpm = new XPM(linesForm);
markType = SC_MARK_PIXMAP;
}
static void DrawBox(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore, ColourAllocated back) {
PRectangle rc;
rc.left = centreX - armSize;
rc.top = centreY - armSize;
rc.right = centreX + armSize + 1;
rc.bottom = centreY + armSize + 1;
surface->RectangleDraw(rc, back, fore);
}
static void DrawCircle(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore, ColourAllocated back) {
PRectangle rcCircle;
rcCircle.left = centreX - armSize;
rcCircle.top = centreY - armSize;
rcCircle.right = centreX + armSize + 1;
rcCircle.bottom = centreY + armSize + 1;
surface->Ellipse(rcCircle, back, fore);
}
static void DrawPlus(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore) {
PRectangle rcV(centreX, centreY - armSize + 2, centreX + 1, centreY + armSize - 2 + 1);
surface->FillRectangle(rcV, fore);
PRectangle rcH(centreX - armSize + 2, centreY, centreX + armSize - 2 + 1, centreY+1);
surface->FillRectangle(rcH, fore);
}
static void DrawMinus(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore) {
PRectangle rcH(centreX - armSize + 2, centreY, centreX + armSize - 2 + 1, centreY+1);
surface->FillRectangle(rcH, fore);
}
void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharacter) {
if ((markType == SC_MARK_PIXMAP) && (pxpm)) {
pxpm->Draw(surface, rcWhole);
return;
}
// Restrict most shapes a bit
PRectangle rc = rcWhole;
rc.top++;
rc.bottom--;
int minDim = Platform::Minimum(rc.Width(), rc.Height());
minDim--; // Ensure does not go beyond edge
int centreX = (rc.right + rc.left) / 2;
int centreY = (rc.bottom + rc.top) / 2;
int dimOn2 = minDim / 2;
int dimOn4 = minDim / 4;
int blobSize = dimOn2-1;
int armSize = dimOn2-2;
if (rc.Width() > (rc.Height() * 2)) {
// Wide column is line number so move to left to try to avoid overlapping number
centreX = rc.left + dimOn2 + 1;
}
if (markType == SC_MARK_ROUNDRECT) {
PRectangle rcRounded = rc;
rcRounded.left = rc.left + 1;
rcRounded.right = rc.right - 1;
surface->RoundedRectangle(rcRounded, fore.allocated, back.allocated);
} else if (markType == SC_MARK_CIRCLE) {
PRectangle rcCircle;
rcCircle.left = centreX - dimOn2;
rcCircle.top = centreY - dimOn2;
rcCircle.right = centreX + dimOn2;
rcCircle.bottom = centreY + dimOn2;
surface->Ellipse(rcCircle, fore.allocated, back.allocated);
} else if (markType == SC_MARK_ARROW) {
Point pts[] = {
Point(centreX - dimOn4, centreY - dimOn2),
Point(centreX - dimOn4, centreY + dimOn2),
Point(centreX + dimOn2 - dimOn4, centreY),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_ARROWDOWN) {
Point pts[] = {
Point(centreX - dimOn2, centreY - dimOn4),
Point(centreX + dimOn2, centreY - dimOn4),
Point(centreX, centreY + dimOn2 - dimOn4),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_PLUS) {
Point pts[] = {
Point(centreX - armSize, centreY - 1),
Point(centreX - 1, centreY - 1),
Point(centreX - 1, centreY - armSize),
Point(centreX + 1, centreY - armSize),
Point(centreX + 1, centreY - 1),
Point(centreX + armSize, centreY -1),
Point(centreX + armSize, centreY +1),
Point(centreX + 1, centreY + 1),
Point(centreX + 1, centreY + armSize),
Point(centreX - 1, centreY + armSize),
Point(centreX - 1, centreY + 1),
Point(centreX - armSize, centreY + 1),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_MINUS) {
Point pts[] = {
Point(centreX - armSize, centreY - 1),
Point(centreX + armSize, centreY -1),
Point(centreX + armSize, centreY +1),
Point(centreX - armSize, centreY + 1),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_SMALLRECT) {
PRectangle rcSmall;
rcSmall.left = rc.left + 1;
rcSmall.top = rc.top + 2;
rcSmall.right = rc.right - 1;
rcSmall.bottom = rc.bottom - 2;
surface->RectangleDraw(rcSmall, fore.allocated, back.allocated);
} else if (markType == SC_MARK_EMPTY || markType == SC_MARK_BACKGROUND ||
markType == SC_MARK_UNDERLINE || markType == SC_MARK_AVAILABLE) {
// An invisible marker so don't draw anything
} else if (markType == SC_MARK_VLINE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_LCORNER) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rc.top + dimOn2);
surface->LineTo(rc.right - 2, rc.top + dimOn2);
} else if (markType == SC_MARK_TCORNER) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rc.top + dimOn2);
surface->LineTo(rc.right - 2, rc.top + dimOn2);
} else if (markType == SC_MARK_LCORNERCURVE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rc.top + dimOn2-3);
surface->LineTo(centreX+3, rc.top + dimOn2);
surface->LineTo(rc.right - 1, rc.top + dimOn2);
} else if (markType == SC_MARK_TCORNERCURVE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rc.top + dimOn2-3);
surface->LineTo(centreX+3, rc.top + dimOn2);
surface->LineTo(rc.right - 1, rc.top + dimOn2);
} else if (markType == SC_MARK_BOXPLUS) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
} else if (markType == SC_MARK_BOXPLUSCONNECTED) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_BOXMINUS) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_BOXMINUSCONNECTED) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_CIRCLEPLUS) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
} else if (markType == SC_MARK_CIRCLEPLUSCONNECTED) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_CIRCLEMINUS) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_CIRCLEMINUSCONNECTED) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType >= SC_MARK_CHARACTER) {
char character[1];
character[0] = static_cast<char>(markType - SC_MARK_CHARACTER);
int width = surface->WidthText(fontForCharacter, character, 1);
rc.left += (rc.Width() - width) / 2;
rc.right = rc.left + width;
surface->DrawTextClipped(rc, fontForCharacter, rc.bottom - 2,
character, 1, fore.allocated, back.allocated);
} else if (markType == SC_MARK_DOTDOTDOT) {
int right = centreX - 6;
for (int b=0; b<3; b++) {
PRectangle rcBlob(right, rc.bottom - 4, right + 2, rc.bottom-2);
surface->FillRectangle(rcBlob, fore.allocated);
right += 5;
}
} else if (markType == SC_MARK_ARROWS) {
surface->PenColour(fore.allocated);
int right = centreX - 2;
for (int b=0; b<3; b++) {
surface->MoveTo(right - 4, centreY - 4);
surface->LineTo(right, centreY);
surface->LineTo(right - 5, centreY + 5);
right += 4;
}
} else if (markType == SC_MARK_SHORTARROW) {
Point pts[] = {
Point(centreX, centreY + dimOn2),
Point(centreX + dimOn2, centreY),
Point(centreX, centreY - dimOn2),
Point(centreX, centreY - dimOn4),
Point(centreX - dimOn4, centreY - dimOn4),
Point(centreX - dimOn4, centreY + dimOn4),
Point(centreX, centreY + dimOn4),
Point(centreX, centreY + dimOn2),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_LEFTRECT) {
PRectangle rcLeft = rcWhole;
rcLeft.right = rcLeft.left + 4;
surface->FillRectangle(rcLeft, back.allocated);
} else { // SC_MARK_FULLRECT
surface->FillRectangle(rcWhole, back.allocated);
}
}
<|endoftext|> |
<commit_before>#include "MainWindow.h"
MainWindow::MainWindow(void)
: BWindow(BRect(100,100,900,700),"MasterPiece",B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS, B_CURRENT_WORKSPACE)
{
BRect r(Bounds());
r.bottom = 20;
mpMenuBar = new MenuBar(r);
AddChild(mpMenuBar);
rgb_color myColor = {215, 215, 215, 255};
fullView = new NewMasterView();
AddChild(fullView);
fullView->SetViewColor(myColor);
fullView->Hide();
openView = new OpenMasterView();
AddChild(openView);
openView->SetViewColor(myColor);
openView->Hide();
BRect sumRect(Bounds());
sumRect.top = 20;
sumView = new SummaryView(sumRect);
AddChild(sumView);
sumView->SetViewColor(myColor);
sumView->Hide();
/*
* NEED TO ABSTRACT THE THOUGHT STUFF TO A TAB
BRect tr = Bounds();
tr.top = 20;
contentTabView = new BTabView(tr, "tab_view");
contentTabView->SetViewColor(myColor);
tr = contentTabView->Bounds();
tr.InsetBy(5,5);
tr.bottom -= contentTabView->TabHeight();
tmpTab = new BTab();
contentTabView->AddTab(new BView(tr, 0, B_FOLLOW_ALL, B_WILL_DRAW), tmpTab);
tmpTab->SetLabel("Thoughts");
tmpTab = new BTab();
contentTabView->AddTab(new BView(tr, 0, B_FOLLOW_ALL, B_WILL_DRAW), tmpTab);
tmpTab->SetLabel("Images");
AddChild(contentTabView);
contentTabView->Hide();
*/
// Check that the MasterPiece directory exists and create it if it doesn't
// possibly check if user want's to create it or select a new one...
homeEntry = BEntry("/boot/home/MasterPiece", false);
if(!homeEntry.Exists()) // does not exist
{
// create MasterPiece directory...
}
}
void
MainWindow::MessageReceived(BMessage *msg)
{
switch (msg->what)
{
case MENU_NEW_MSG:
// 1. need to center the modal window on the parent...
if(!this->sumView->IsHidden()) this->sumView->Hide();
if(!this->openView->IsHidden()) this->openView->Hide();
if(this->fullView->IsHidden()) this->fullView->Show();
break;
case MENU_OPN_MSG:
if(!this->sumView->IsHidden()) this->sumView->Hide();
if(!this->fullView->IsHidden()) this->fullView->Hide();
this->openView->openListView->MakeEmpty();
homeDir->Rewind();
while(homeDir->GetNextEntry(&entry) == B_OK)
{
char name[B_FILE_NAME_LENGTH];
entry.GetName(name);
if(entry.IsDirectory())
{
this->openView->openListView->AddItem(new BStringItem(name));
}
}
if(this->openView->IsHidden()) this->openView->Show();
break;
case ADD_NEW_COURSE:
homeDir = new BDirectory("/boot/home/MasterPiece");
returnValue = homeDir->CreateDirectory(this->fullView->titleText->Text(), homeDir);
if(returnValue == B_FILE_EXISTS)
{
tmpString = "Do you want to open the course ";
tmpString += this->fullView->titleText->Text();
tmpString += "?";
}
if(returnValue != B_OK)
{
debugAlert = new BAlert("Debug Value", tmpString, "Yes", "No", 0, B_WIDTH_AS_USUAL, B_INFO_ALERT);
debugAlert->MoveTo(350, 250);
debugAlert->SetShortcut(1, B_ESCAPE);
int alertReturn = debugAlert->Go();
if(alertReturn == 0) // Yes
{
this->SetTitle(this->fullView->titleText->Text());
if(!this->fullView->IsHidden()) this->fullView->Hide();
}
else if(alertReturn == 1) // No
{
this->fullView->titleText->SetText("");
}
}
else
{
this->SetTitle(this->fullView->titleText->Text());
if(!this->fullView->IsHidden()) this->fullView->Hide();
if(!this->openView->IsHidden()) this->openView->Hide();
if(this->sumView->IsHidden()) this->sumView->Show();
this->mpMenuBar->contentMenu->SetEnabled(true);
this->mpMenuBar->layoutMenu->SetEnabled(true);
}
// do something here...
this->fullView->titleText->SetText("");
break;
case CANCEL_NEW_COURSE:
if(!this->fullView->IsHidden()) this->fullView->Hide();
this->fullView->titleText->SetText("");
// do soemthing here...
break;
case MENU_THT_MSG:
if(this->sumView->IsHidden()) this->sumView->Show();
// do something here...
break;
case MNG_LAYOUT_MSG:
// do something here...
break;
case CANCEL_OPEN_COURSE:
if(!this->openView->IsHidden())this->openView->Hide();
// do something here...
break;
case OPEN_EXISTING_COURSE:
// do something here...
int32 selected;
selected = this->openView->openListView->CurrentSelection();
if(selected < 0)
{
// error here
}
BStringItem *item;
item = dynamic_cast<BStringItem*>(this->openView->openListView->ItemAt(selected));
if(item)
{
this->SetTitle(item->Text());
if(!this->openView->IsHidden()) this->openView->Hide();
if(!this->fullView->IsHidden()) this->fullView->Hide();
if(this->sumView->IsHidden()) this->sumView->Show();
this->mpMenuBar->contentMenu->SetEnabled(true);
this->mpMenuBar->layoutMenu->SetEnabled(true);
}
break;
default:
{
BWindow::MessageReceived(msg);
break;
}
}
}
bool
MainWindow::QuitRequested(void)
{
be_app->PostMessage(B_QUIT_REQUESTED);
return true;
}
<commit_msg>made updates/fixes to the new/open options. need to create and then populate sumview with values based on the respective course information.<commit_after>#include "MainWindow.h"
MainWindow::MainWindow(void)
: BWindow(BRect(100,100,900,700),"MasterPiece",B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS, B_CURRENT_WORKSPACE)
{
BRect r(Bounds());
r.bottom = 20;
mpMenuBar = new MenuBar(r);
AddChild(mpMenuBar);
rgb_color myColor = {215, 215, 215, 255};
fullView = new NewMasterView();
AddChild(fullView);
fullView->SetViewColor(myColor);
fullView->Hide();
openView = new OpenMasterView();
AddChild(openView);
openView->SetViewColor(myColor);
openView->Hide();
BRect sumRect(Bounds());
sumRect.top = 20;
sumView = new SummaryView(sumRect);
AddChild(sumView);
sumView->SetViewColor(myColor);
sumView->Hide();
/*
* NEED TO ABSTRACT THE THOUGHT STUFF TO A TAB
BRect tr = Bounds();
tr.top = 20;
contentTabView = new BTabView(tr, "tab_view");
contentTabView->SetViewColor(myColor);
tr = contentTabView->Bounds();
tr.InsetBy(5,5);
tr.bottom -= contentTabView->TabHeight();
tmpTab = new BTab();
contentTabView->AddTab(new BView(tr, 0, B_FOLLOW_ALL, B_WILL_DRAW), tmpTab);
tmpTab->SetLabel("Thoughts");
tmpTab = new BTab();
contentTabView->AddTab(new BView(tr, 0, B_FOLLOW_ALL, B_WILL_DRAW), tmpTab);
tmpTab->SetLabel("Images");
AddChild(contentTabView);
contentTabView->Hide();
*/
// Check that the MasterPiece directory exists and create it if it doesn't
// possibly check if user want's to create it or select a new one...
homeEntry = BEntry("/boot/home/MasterPiece", false);
if(!homeEntry.Exists()) // does not exist
{
// create MasterPiece directory...
}
else
{
homeDir = new BDirectory("/boot/home/MasterPiece");
}
}
void
MainWindow::MessageReceived(BMessage *msg)
{
switch (msg->what)
{
case MENU_NEW_MSG:
// 1. need to center the modal window on the parent...
if(!this->sumView->IsHidden()) this->sumView->Hide();
if(!this->openView->IsHidden()) this->openView->Hide();
if(this->fullView->IsHidden()) this->fullView->Show();
break;
case MENU_OPN_MSG:
if(!this->sumView->IsHidden()) this->sumView->Hide();
if(!this->fullView->IsHidden()) this->fullView->Hide();
this->openView->openListView->MakeEmpty();
homeDir->Rewind();
while(homeDir->GetNextEntry(&entry) == B_OK)
{
char name[B_FILE_NAME_LENGTH];
entry.GetName(name);
if(entry.IsDirectory())
{
this->openView->openListView->AddItem(new BStringItem(name));
}
}
if(this->openView->IsHidden()) this->openView->Show();
break;
case ADD_NEW_COURSE:
returnValue = homeDir->CreateDirectory(this->fullView->titleText->Text(), homeDir);
if(returnValue == B_FILE_EXISTS)
{
tmpString = "Do you want to open the course ";
tmpString += this->fullView->titleText->Text();
tmpString += "?";
}
if(returnValue != B_OK)
{
debugAlert = new BAlert("Debug Value", tmpString, "Yes", "No", 0, B_WIDTH_AS_USUAL, B_INFO_ALERT);
debugAlert->MoveTo(350, 250);
debugAlert->SetShortcut(1, B_ESCAPE);
int alertReturn = debugAlert->Go();
if(alertReturn == 0) // Yes
{
this->SetTitle(this->fullView->titleText->Text());
if(!this->fullView->IsHidden()) this->fullView->Hide();
}
else if(alertReturn == 1) // No
{
this->fullView->titleText->SetText("");
}
}
else
{
this->SetTitle(this->fullView->titleText->Text());
if(!this->fullView->IsHidden()) this->fullView->Hide();
if(!this->openView->IsHidden()) this->openView->Hide();
if(this->sumView->IsHidden()) this->sumView->Show();
this->mpMenuBar->contentMenu->SetEnabled(true);
this->mpMenuBar->layoutMenu->SetEnabled(true);
}
// do something here...
this->fullView->titleText->SetText("");
break;
case CANCEL_NEW_COURSE:
if(!this->fullView->IsHidden()) this->fullView->Hide();
this->fullView->titleText->SetText("");
// do soemthing here...
break;
case MENU_THT_MSG:
if(this->sumView->IsHidden()) this->sumView->Show();
// do something here...
break;
case MNG_LAYOUT_MSG:
// do something here...
break;
case CANCEL_OPEN_COURSE:
if(!this->openView->IsHidden())this->openView->Hide();
// do something here...
break;
case OPEN_EXISTING_COURSE:
// do something here...
int32 selected;
selected = this->openView->openListView->CurrentSelection();
if(selected < 0)
{
// error here
}
BStringItem *item;
item = dynamic_cast<BStringItem*>(this->openView->openListView->ItemAt(selected));
if(item)
{
this->SetTitle(item->Text());
if(!this->openView->IsHidden()) this->openView->Hide();
if(!this->fullView->IsHidden()) this->fullView->Hide();
if(this->sumView->IsHidden()) this->sumView->Show();
this->mpMenuBar->contentMenu->SetEnabled(true);
this->mpMenuBar->layoutMenu->SetEnabled(true);
}
break;
default:
{
BWindow::MessageReceived(msg);
break;
}
}
}
bool
MainWindow::QuitRequested(void)
{
be_app->PostMessage(B_QUIT_REQUESTED);
return true;
}
<|endoftext|> |
<commit_before>// MarkedList.cpp
#include "stdafx.h"
#include "MarkedList.h"
#include "../interface/HeeksObj.h"
#include "../interface/MarkedObject.h"
#include "../interface/PropertyInt.h"
#include "DigitizeMode.h"
#include "SelectMode.h"
#include "PointOrWindow.h"
#include "GripperSelTransform.h"
#include "GraphicsCanvas.h"
#include "HeeksFrame.h"
#include "ConversionTools.h"
#include <wx/clipbrd.h>
#include "../tinyxml/tinyxml.h"
#include <wx/stdpaths.h>
#include <fstream>
using namespace std;
MarkedList::MarkedList(){
gripping = false;
point_or_window = new PointOrWindow(true);
gripper_marked_list_changed = false;
ignore_coords_only = false;
m_filter = -1;
}
MarkedList::~MarkedList(void){
delete point_or_window;
delete_move_grips(false);
}
void MarkedList::delete_move_grips(bool check_app_grippers){
std::list<Gripper*>::iterator It;
for(It = move_grips.begin(); It != move_grips.end(); It++){
Gripper* gripper = *It;
if(check_app_grippers){
if(gripper == wxGetApp().cursor_gripper)wxGetApp().cursor_gripper = NULL;
if(gripper == wxGetApp().drag_gripper)wxGetApp().drag_gripper = NULL;
}
delete gripper;
}
move_grips.clear();
}
void MarkedList::create_move_grips(){
delete_move_grips();
double pos[3];
int number_of_grips_made = 0;
std::list<HeeksObj*>::iterator Iter ;
for(Iter = m_list.begin(); Iter != m_list.end() && number_of_grips_made<100; Iter++){
HeeksObj* object = *Iter;
if(object->GetType() == GripperType)continue;
std::list<double> vl;
std::list<double>::iterator It;
object->GetGripperPositions(&vl, false);
for(It = vl.begin(); It != vl.end() && number_of_grips_made<100; It++){
EnumGripperType gripper_type = (EnumGripperType)((int)(*It));
It++;
pos[0] = *It;
It++;
pos[1] = *It;
It++;
pos[2] = *It;
move_grips.push_back(new GripperSelTransform(make_point(pos), gripper_type));
number_of_grips_made++;
}
}
}
void MarkedList::update_move_grips(){
if(gripping)return;
double pos[3];
std::list<HeeksObj*>::iterator Iter ;
std::list<Gripper*>::iterator Iter2;
Iter2 = move_grips.begin();
for(Iter = m_list.begin(); Iter != m_list.end(); Iter++){
if(Iter2 == move_grips.end())break;
HeeksObj* object = *Iter;
if(object->GetType() == GripperType)continue;
std::list<double> vl;
std::list<double>::iterator It;
object->GetGripperPositions(&vl, false);
for(It = vl.begin(); It != vl.end(); It++){
It++;
pos[0] = *It;
It++;
pos[1] = *It;
It++;
pos[2] = *It;
Gripper* gripper = *Iter2;
gripper->position = make_point(pos);
Iter2++;
if(Iter2 == move_grips.end())break;
}
}
}
void MarkedList::render_move_grips(bool select, bool no_color){
std::list<Gripper*>::iterator It;
for(It = move_grips.begin(); It != move_grips.end(); It++){
if(select)glPushName((unsigned long)(*It));
(*It)->glCommands(select, false, no_color);
if(select)glPopName();
}
}
void MarkedList::create_grippers(){
if(gripping)return;
if(gripper_marked_list_changed)create_move_grips();
else update_move_grips();
gripper_marked_list_changed = false;
}
void MarkedList::GrippersGLCommands(bool select, bool no_color){
if(size()>0){
create_grippers();
render_move_grips(select, no_color);
}
}
void MarkedList::ObjectsInWindow( wxRect window, MarkedObject* marked_object, bool single_picking){
int buffer_length = 16384;
GLuint *data = (GLuint *)malloc( buffer_length * sizeof(GLuint) );
if(data == NULL)return;
int i, j;
int half_window_width = 0;
wxPoint window_centre;
if(single_picking){
half_window_width = (window.width)/2;
window_centre.x = window.x + window.width/2;
window_centre.y = window.y + window.height/2;
}
int window_mode = 0;
while(1){
if(single_picking){
int window_size = half_window_width;
if(window_mode == 0)window_size = 0;
if(window_mode == 1)window_size = half_window_width/2;
window.x = window_centre.x - window_size;
window.y = window_centre.y - window_size;
window.width = window_size * 2;
window.height = window_size * 2;
}
GLint num_hits = -1;
while(num_hits < 0){
glSelectBuffer(buffer_length, data);
glRenderMode(GL_SELECT);
glInitNames();
wxGetApp().m_frame->m_graphics->m_view_point.SetViewport();
wxGetApp().m_frame->m_graphics->m_view_point.SetPickProjection(window);
wxGetApp().m_frame->m_graphics->m_view_point.SetModelview();
wxGetApp().glCommands(true, false, false);
GrippersGLCommands(true, false);
glFlush();
num_hits = glRenderMode(GL_RENDER);
if(num_hits<0){
free(data);
buffer_length *= 10;
data = (GLuint *)malloc( buffer_length * sizeof(GLuint) );
if(data == NULL)return;
}
}
int pos = 0;
bool added = false;
for(i=0; i<num_hits; i++)
{
unsigned int names = data[pos];
if(names == 0)break;
pos++;
unsigned int min_depth = data[pos];
pos+=2;
MarkedObject* current_found_object = marked_object;
bool ignore_coords_only_found = false;
for(j=0; j<(int)names; j++, pos++){
if(!ignore_coords_only_found && current_found_object != NULL){
HeeksObj *object = (HeeksObj *)(data[pos]);
if(object->GetType() == EdgeType)
{
int here = 0;
here = 3;
}
if(ignore_coords_only && wxGetApp().m_digitizing->OnlyCoords(object)){
ignore_coords_only_found = true;
}
else{
if(object->GetType() == GripperType || (object->GetMarkingMask() & m_filter)){
int window_size = window.width;
current_found_object = current_found_object->Add(object, min_depth, window_size);
added = true;
}
}
}
}
}
window_mode++;
if(!single_picking || added)break;
if(window_mode > 2)break;
}
free(data);
}
void MarkedList::glCommands(){
std::list<HeeksObj*>::iterator Iter ;
int object_count = 0;
for(Iter = m_list.begin(); Iter != m_list.end(); Iter++, object_count++){
HeeksObj *object = (*Iter);
object->glCommands(true, false, false);
}
}
void MarkedList::Add(std::list<HeeksObj *> &list){
std::list<HeeksObj *>::iterator It;
for(It = list.begin(); It != list.end(); It++){
HeeksObj *object = *It;
m_list.push_back(object);
m_set.insert(object);
}
OnChanged(false, false, &list, NULL);
}
void MarkedList::Remove(HeeksObj *object){
std::list<HeeksObj *> list;
list.push_back(object);
Remove(list);
}
void MarkedList::Add(HeeksObj *object){
std::list<HeeksObj *> list;
list.push_back(object);
Add(list);
}
void MarkedList::Remove(const std::list<HeeksObj *> &obj_list){
std::list<HeeksObj *>::const_iterator It;
for(It = obj_list.begin(); It != obj_list.end(); It++){
HeeksObj *object = *It;
if(m_set.find(object) != m_set.end()){
m_list.remove(object);
}
m_set.erase(object);
}
OnChanged(false, false, NULL, &obj_list);
}
void MarkedList::Clear(void){
m_list.clear();
m_set.clear();
OnChanged(false, true, NULL, NULL);
}
void MarkedList::FindMarkedObject(const wxPoint &point, MarkedObject* marked_object){
if(marked_object == NULL)return;
point_or_window->SetWithPoint(point);
ObjectsInWindow(point_or_window->box_chosen, marked_object);
}
bool MarkedList::ObjectMarked(HeeksObj *object){
return m_set.find(object) != m_set.end();
}
void MarkedList::OnChanged(bool all_marked, bool none_marked, const std::list<HeeksObj *>* added, const std::list<HeeksObj *>* removed){
gripper_marked_list_changed = true;
wxGetApp().ObserversMarkedListChanged(all_marked, none_marked, added, removed);
}
void MarkedList::set_ignore_onoff(HeeksObj* object, bool b){
if(b)m_ignore_set.insert(object);
else m_ignore_set.erase(object);
}
bool MarkedList::get_ignore(HeeksObj* object){
if(m_ignore_set.find(object) != m_ignore_set.end())return true;
return false;
}
void MarkedList::GetProperties(std::list<Property *> *list){
if(m_list.size() == 1)
{
m_list.front()->GetProperties(list);
}
else
{
// multiple selection
list->push_back(new PropertyInt(_("Number of items selected"), m_list.size(), NULL));
}
}
class DeleteMarkedListTool : public Tool
{
public:
const wxChar* GetTitle() {return _("Delete Marked Items");}
void Run() {wxGetApp().DeleteMarkedItems();}
wxString BitmapPath(){return _T("delete");}
} delete_marked_list_tool;
class CopyMarkedList: public Tool
{
public:
void Run();
const wxChar* GetTitle(){return _("Copy");}
wxString BitmapPath(){return _T("copy");}
const wxChar* GetToolTip(){return _("Copies the selected items to the clipboard");}
} copy_marked_list;
void CopyMarkedList::Run()
{
wxGetApp().m_marked_list->CopySelectedItems();
}
class PasteTool: public Tool
{
public:
HeeksObj* m_paste_into;
PasteTool():m_paste_into(NULL){}
void Run();
const wxChar* GetTitle(){return m_paste_into ? _("Paste Into") : _("Paste");}
wxString BitmapPath(){return _T("paste");}
const wxChar* GetToolTip(){return _("Paste items from the clipboard to the drawing");}
} paste_tool;
void PasteTool::Run()
{
wxGetApp().Paste(m_paste_into);
}
void MarkedList::GetTools(MarkedObject* clicked_object, std::list<Tool*>& t_list, const wxPoint* p){
if (m_list.size() > 1)
{
t_list.push_back(&delete_marked_list_tool);
t_list.push_back(NULL);
}
if(m_list.size() == 1)
{
m_list.front()->GetTools(&t_list, p);
}
GetConversionMenuTools(&t_list);
// cut and copy tools
for(std::list<HeeksObj*>::iterator It = m_list.begin(); It != m_list.end(); It++)
{
HeeksObj* object = *It;
if(object->CanBeCopied())
{
t_list.push_back(©_marked_list);
break;
}
}
// paste
if (wxGetApp().IsPasteReady())
{
paste_tool.m_paste_into = clicked_object->GetObject();
t_list.push_back(&paste_tool);
}
}
void MarkedList::CutSelectedItems()
{
wxGetApp().StartHistory();
CopySelectedItems();
wxGetApp().DeleteUndoably(m_list);
wxGetApp().EndHistory();
}
void MarkedList::CopySelectedItems()
{
wxStandardPaths sp;
sp.GetTempDir();
wxString temp_file = sp.GetTempDir() + _T("/temp_Heeks_clipboard_file.xml");
wxGetApp().SaveXMLFile(m_list, temp_file);
#if wxUSE_UNICODE
#ifdef __WXMSW__
wifstream ifs(temp_file);
#else
wifstream ifs(Ttc(temp_file.c_str()));
#endif
#else
ifstream ifs(temp_file);
#endif
if(!ifs)return;
wxString fstr;
wxChar str[1024];
while(!(ifs.eof())){
ifs.getline(str, 1022);
fstr.append(str);
fstr.append(_T("\r\n"));
if(!ifs)break;
}
if (wxTheClipboard->Open())
{
// This data object is held by the clipboard,
// so do not delete them in the app.
wxTheClipboard->SetData( new wxTextDataObject(fstr));
wxTheClipboard->Close();
}
}
void MarkedList::Reset()
{
delete_move_grips();
}
<commit_msg>tidied up a bit<commit_after>// MarkedList.cpp
#include "stdafx.h"
#include "MarkedList.h"
#include "../interface/HeeksObj.h"
#include "../interface/MarkedObject.h"
#include "../interface/PropertyInt.h"
#include "DigitizeMode.h"
#include "SelectMode.h"
#include "PointOrWindow.h"
#include "GripperSelTransform.h"
#include "GraphicsCanvas.h"
#include "HeeksFrame.h"
#include "ConversionTools.h"
#include <wx/clipbrd.h>
#include "../tinyxml/tinyxml.h"
#include <wx/stdpaths.h>
#include <fstream>
using namespace std;
MarkedList::MarkedList(){
gripping = false;
point_or_window = new PointOrWindow(true);
gripper_marked_list_changed = false;
ignore_coords_only = false;
m_filter = -1;
}
MarkedList::~MarkedList(void){
delete point_or_window;
delete_move_grips(false);
}
void MarkedList::delete_move_grips(bool check_app_grippers){
std::list<Gripper*>::iterator It;
for(It = move_grips.begin(); It != move_grips.end(); It++){
Gripper* gripper = *It;
if(check_app_grippers){
if(gripper == wxGetApp().cursor_gripper)wxGetApp().cursor_gripper = NULL;
if(gripper == wxGetApp().drag_gripper)wxGetApp().drag_gripper = NULL;
}
delete gripper;
}
move_grips.clear();
}
void MarkedList::create_move_grips(){
delete_move_grips();
double pos[3];
int number_of_grips_made = 0;
std::list<HeeksObj*>::iterator Iter ;
for(Iter = m_list.begin(); Iter != m_list.end() && number_of_grips_made<100; Iter++){
HeeksObj* object = *Iter;
if(object->GetType() == GripperType)continue;
std::list<double> vl;
std::list<double>::iterator It;
object->GetGripperPositions(&vl, false);
for(It = vl.begin(); It != vl.end() && number_of_grips_made<100; It++){
EnumGripperType gripper_type = (EnumGripperType)((int)(*It));
It++;
pos[0] = *It;
It++;
pos[1] = *It;
It++;
pos[2] = *It;
move_grips.push_back(new GripperSelTransform(make_point(pos), gripper_type));
number_of_grips_made++;
}
}
}
void MarkedList::update_move_grips(){
if(gripping)return;
double pos[3];
std::list<HeeksObj*>::iterator Iter ;
std::list<Gripper*>::iterator Iter2;
Iter2 = move_grips.begin();
for(Iter = m_list.begin(); Iter != m_list.end(); Iter++){
if(Iter2 == move_grips.end())break;
HeeksObj* object = *Iter;
if(object->GetType() == GripperType)continue;
std::list<double> vl;
std::list<double>::iterator It;
object->GetGripperPositions(&vl, false);
for(It = vl.begin(); It != vl.end(); It++){
It++;
pos[0] = *It;
It++;
pos[1] = *It;
It++;
pos[2] = *It;
Gripper* gripper = *Iter2;
gripper->position = make_point(pos);
Iter2++;
if(Iter2 == move_grips.end())break;
}
}
}
void MarkedList::render_move_grips(bool select, bool no_color){
std::list<Gripper*>::iterator It;
for(It = move_grips.begin(); It != move_grips.end(); It++){
if(select)glPushName((unsigned long)(*It));
(*It)->glCommands(select, false, no_color);
if(select)glPopName();
}
}
void MarkedList::create_grippers(){
if(gripping)return;
if(gripper_marked_list_changed)create_move_grips();
else update_move_grips();
gripper_marked_list_changed = false;
}
void MarkedList::GrippersGLCommands(bool select, bool no_color){
if(size()>0){
create_grippers();
render_move_grips(select, no_color);
}
}
void MarkedList::ObjectsInWindow( wxRect window, MarkedObject* marked_object, bool single_picking){
int buffer_length = 16384;
GLuint *data = (GLuint *)malloc( buffer_length * sizeof(GLuint) );
if(data == NULL)return;
int i, j;
int half_window_width = 0;
wxPoint window_centre;
if(single_picking){
half_window_width = (window.width)/2;
window_centre.x = window.x + window.width/2;
window_centre.y = window.y + window.height/2;
}
int window_mode = 0;
while(1){
if(single_picking){
int window_size = half_window_width;
if(window_mode == 0)window_size = 0;
if(window_mode == 1)window_size = half_window_width/2;
window.x = window_centre.x - window_size;
window.y = window_centre.y - window_size;
window.width = window_size * 2;
window.height = window_size * 2;
}
GLint num_hits = -1;
while(num_hits < 0){
glSelectBuffer(buffer_length, data);
glRenderMode(GL_SELECT);
glInitNames();
wxGetApp().m_frame->m_graphics->m_view_point.SetViewport();
wxGetApp().m_frame->m_graphics->m_view_point.SetPickProjection(window);
wxGetApp().m_frame->m_graphics->m_view_point.SetModelview();
wxGetApp().glCommands(true, false, false);
GrippersGLCommands(true, false);
glFlush();
num_hits = glRenderMode(GL_RENDER);
if(num_hits<0){
free(data);
buffer_length *= 10;
data = (GLuint *)malloc( buffer_length * sizeof(GLuint) );
if(data == NULL)return;
}
}
int pos = 0;
bool added = false;
for(i=0; i<num_hits; i++)
{
unsigned int names = data[pos];
if(names == 0)break;
pos++;
unsigned int min_depth = data[pos];
pos+=2;
MarkedObject* current_found_object = marked_object;
bool ignore_coords_only_found = false;
for(j=0; j<(int)names; j++, pos++){
if(!ignore_coords_only_found && current_found_object != NULL){
HeeksObj *object = (HeeksObj *)(data[pos]);
if(ignore_coords_only && wxGetApp().m_digitizing->OnlyCoords(object)){
ignore_coords_only_found = true;
}
else{
if(object->GetType() == GripperType || (object->GetMarkingMask() == 0) || (object->GetMarkingMask() & m_filter)){
int window_size = window.width;
current_found_object = current_found_object->Add(object, min_depth, window_size);
added = true;
}
}
}
}
}
window_mode++;
if(!single_picking || added)break;
if(window_mode > 2)break;
}
free(data);
}
void MarkedList::glCommands(){
std::list<HeeksObj*>::iterator Iter ;
int object_count = 0;
for(Iter = m_list.begin(); Iter != m_list.end(); Iter++, object_count++){
HeeksObj *object = (*Iter);
object->glCommands(true, false, false);
}
}
void MarkedList::Add(std::list<HeeksObj *> &list){
std::list<HeeksObj *>::iterator It;
for(It = list.begin(); It != list.end(); It++){
HeeksObj *object = *It;
m_list.push_back(object);
m_set.insert(object);
}
OnChanged(false, false, &list, NULL);
}
void MarkedList::Remove(HeeksObj *object){
std::list<HeeksObj *> list;
list.push_back(object);
Remove(list);
}
void MarkedList::Add(HeeksObj *object){
std::list<HeeksObj *> list;
list.push_back(object);
Add(list);
}
void MarkedList::Remove(const std::list<HeeksObj *> &obj_list){
std::list<HeeksObj *>::const_iterator It;
for(It = obj_list.begin(); It != obj_list.end(); It++){
HeeksObj *object = *It;
if(m_set.find(object) != m_set.end()){
m_list.remove(object);
}
m_set.erase(object);
}
OnChanged(false, false, NULL, &obj_list);
}
void MarkedList::Clear(void){
m_list.clear();
m_set.clear();
OnChanged(false, true, NULL, NULL);
}
void MarkedList::FindMarkedObject(const wxPoint &point, MarkedObject* marked_object){
if(marked_object == NULL)return;
point_or_window->SetWithPoint(point);
ObjectsInWindow(point_or_window->box_chosen, marked_object);
}
bool MarkedList::ObjectMarked(HeeksObj *object){
return m_set.find(object) != m_set.end();
}
void MarkedList::OnChanged(bool all_marked, bool none_marked, const std::list<HeeksObj *>* added, const std::list<HeeksObj *>* removed){
gripper_marked_list_changed = true;
wxGetApp().ObserversMarkedListChanged(all_marked, none_marked, added, removed);
}
void MarkedList::set_ignore_onoff(HeeksObj* object, bool b){
if(b)m_ignore_set.insert(object);
else m_ignore_set.erase(object);
}
bool MarkedList::get_ignore(HeeksObj* object){
if(m_ignore_set.find(object) != m_ignore_set.end())return true;
return false;
}
void MarkedList::GetProperties(std::list<Property *> *list){
if(m_list.size() == 1)
{
m_list.front()->GetProperties(list);
}
else
{
// multiple selection
list->push_back(new PropertyInt(_("Number of items selected"), m_list.size(), NULL));
}
}
class DeleteMarkedListTool : public Tool
{
public:
const wxChar* GetTitle() {return _("Delete Marked Items");}
void Run() {wxGetApp().DeleteMarkedItems();}
wxString BitmapPath(){return _T("delete");}
} delete_marked_list_tool;
class CopyMarkedList: public Tool
{
public:
void Run();
const wxChar* GetTitle(){return _("Copy");}
wxString BitmapPath(){return _T("copy");}
const wxChar* GetToolTip(){return _("Copies the selected items to the clipboard");}
} copy_marked_list;
void CopyMarkedList::Run()
{
wxGetApp().m_marked_list->CopySelectedItems();
}
class PasteTool: public Tool
{
public:
HeeksObj* m_paste_into;
PasteTool():m_paste_into(NULL){}
void Run();
const wxChar* GetTitle(){return m_paste_into ? _("Paste Into") : _("Paste");}
wxString BitmapPath(){return _T("paste");}
const wxChar* GetToolTip(){return _("Paste items from the clipboard to the drawing");}
} paste_tool;
void PasteTool::Run()
{
wxGetApp().Paste(m_paste_into);
}
void MarkedList::GetTools(MarkedObject* clicked_object, std::list<Tool*>& t_list, const wxPoint* p){
if (m_list.size() > 1)
{
t_list.push_back(&delete_marked_list_tool);
t_list.push_back(NULL);
}
if(m_list.size() == 1)
{
m_list.front()->GetTools(&t_list, p);
}
GetConversionMenuTools(&t_list);
// cut and copy tools
for(std::list<HeeksObj*>::iterator It = m_list.begin(); It != m_list.end(); It++)
{
HeeksObj* object = *It;
if(object->CanBeCopied())
{
t_list.push_back(©_marked_list);
break;
}
}
// paste
if (wxGetApp().IsPasteReady())
{
paste_tool.m_paste_into = clicked_object->GetObject();
t_list.push_back(&paste_tool);
}
}
void MarkedList::CutSelectedItems()
{
wxGetApp().StartHistory();
CopySelectedItems();
wxGetApp().DeleteUndoably(m_list);
wxGetApp().EndHistory();
}
void MarkedList::CopySelectedItems()
{
wxStandardPaths sp;
sp.GetTempDir();
wxString temp_file = sp.GetTempDir() + _T("/temp_Heeks_clipboard_file.xml");
wxGetApp().SaveXMLFile(m_list, temp_file);
#if wxUSE_UNICODE
#ifdef __WXMSW__
wifstream ifs(temp_file);
#else
wifstream ifs(Ttc(temp_file.c_str()));
#endif
#else
ifstream ifs(temp_file);
#endif
if(!ifs)return;
wxString fstr;
wxChar str[1024];
while(!(ifs.eof())){
ifs.getline(str, 1022);
fstr.append(str);
fstr.append(_T("\r\n"));
if(!ifs)break;
}
if (wxTheClipboard->Open())
{
// This data object is held by the clipboard,
// so do not delete them in the app.
wxTheClipboard->SetData( new wxTextDataObject(fstr));
wxTheClipboard->Close();
}
}
void MarkedList::Reset()
{
delete_move_grips();
}
<|endoftext|> |
<commit_before>/*===========================================================================*/
/* This file is part of a Mixed Integer Bilevel Solver */
/* developed using the BiCePS Linear Integer Solver (BLIS). */
/* */
/* Authors: Scott DeNegre, Lehigh University */
/* Ted Ralphs, Lehigh University */
/* */
/* Copyright (C) 2007-2015 Lehigh University, Scott DeNegre, and Ted Ralphs. */
/* All Rights Reserved. */
/* */
/* This software is licensed under the Eclipse Public License. Please see */
/* accompanying file for terms. */
/*===========================================================================*/
/* Include file for the configuration of MibS.
*
* On systems where the code is configured with the configure script
* (i.e., compilation is always done with HAVE_CONFIG_H defined), this
* header file includes the automatically generated header file, and
* undefines macros that might configure with other Config.h files.
*
* On systems that are compiled in other ways (e.g., with the
* Developer Studio), a header files is included to define those
* macros that depend on the operating system and the compiler. The
* macros that define the configuration of the particular user setting
* (e.g., presence of other COIN-OR packages or third party code) are set
* by the files config_*default.h. The project maintainer needs to remember
* to update these file and choose reasonable defines.
* A user can modify the default setting by editing the config_*default.h files.
*
*/
#ifndef MibSConfig_hpp_
#define MibSConfig_hpp_
#if defined(_MSC_VER) || defined(__MINGW32__)/* Different function call in
Windows */
#define SRANDOM(seed) srand(seed)
#define RANDOM() rand()
#else
#define SRANDOM(seed) srandom(seed)
#define RANDOM() random()
#endif
#ifdef HAVE_CONFIG_H
#ifdef MIBS_BUILD
#include "config.h"
#else
#include "config_mibs.h"
#endif
#else /* HAVE_CONFIG_H */
#ifdef MIBS_BUILD
#include "config_default.h"
#else
#include "config_mibs_default.h"
#endif
#endif /* HAVE_CONFIG_H */
#endif /*__MIBSCONFIG_H__*/
<commit_msg>Adding symbol for MINGW64<commit_after>/*===========================================================================*/
/* This file is part of a Mixed Integer Bilevel Solver */
/* developed using the BiCePS Linear Integer Solver (BLIS). */
/* */
/* Authors: Scott DeNegre, Lehigh University */
/* Ted Ralphs, Lehigh University */
/* */
/* Copyright (C) 2007-2015 Lehigh University, Scott DeNegre, and Ted Ralphs. */
/* All Rights Reserved. */
/* */
/* This software is licensed under the Eclipse Public License. Please see */
/* accompanying file for terms. */
/*===========================================================================*/
/* Include file for the configuration of MibS.
*
* On systems where the code is configured with the configure script
* (i.e., compilation is always done with HAVE_CONFIG_H defined), this
* header file includes the automatically generated header file, and
* undefines macros that might configure with other Config.h files.
*
* On systems that are compiled in other ways (e.g., with the
* Developer Studio), a header files is included to define those
* macros that depend on the operating system and the compiler. The
* macros that define the configuration of the particular user setting
* (e.g., presence of other COIN-OR packages or third party code) are set
* by the files config_*default.h. The project maintainer needs to remember
* to update these file and choose reasonable defines.
* A user can modify the default setting by editing the config_*default.h files.
*
*/
#ifndef MibSConfig_hpp_
#define MibSConfig_hpp_
#if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__)
/* Different function call in Windows */
#define SRANDOM(seed) srand(seed)
#define RANDOM() rand()
#else
#define SRANDOM(seed) srandom(seed)
#define RANDOM() random()
#endif
#ifdef HAVE_CONFIG_H
#ifdef MIBS_BUILD
#include "config.h"
#else
#include "config_mibs.h"
#endif
#else /* HAVE_CONFIG_H */
#ifdef MIBS_BUILD
#include "config_default.h"
#else
#include "config_mibs_default.h"
#endif
#endif /* HAVE_CONFIG_H */
#endif /*__MIBSCONFIG_H__*/
<|endoftext|> |
<commit_before>#include "MoveSystem.h"
#include <iostream>
#include <cmath>
void MoveSystem::update(int currentStep)
{
const std::vector<int> &uidList = movementNode.uids();
for(int i = 0; i < uidList.size(); i++)
{
int uid = uidList.at(i);
MovementNode &n = movementNode.get(uid);
PositionComponent &p = n.position;
VelocityComponent &v = n.velocity;
const PositionTargetComponent &t = n.target;
// estimate XY angle
int deltaX = t.targetX - p.positionX;
int deltaY = t.targetY - p.positionY;
double pathRad = std::atan2(deltaY, deltaX);
int pathR = (int) (pathRad * 180. / M_PI);
int deltaR = deltaX != 0 || deltaY != 0 ? pathR - p.positionR :
t.targetR - p.positionR;
if (deltaR <= -180)
{
deltaR = -360 - deltaR;
}
else if (deltaR >= 180)
{
deltaR = 360 - deltaR;
}
if (deltaX == 0 && deltaY == 0 && deltaR == 0)
{
v.moving = false;
movementNode.remove(uid);
continue;
}
// move angular
else if (std::abs(deltaR) > v.velocityR)
{
v.moving = true;
p.positionR = deltaR > 0 ? p.positionR + v.velocityR :
deltaR < 0 ? p.positionR - v.velocityR :
pathR;
}
// move forward
else
{
v.moving = true;
p.positionR = pathR;
int newX = (int) (v.velocityFB * std::cos(pathRad));
if (std::abs(newX) > std::abs(deltaX))
{
newX = deltaX;
}
int newY = (int) (v.velocityFB * std::sin(pathRad));
if (std::abs(newY) > std::abs(deltaY))
{
newY = deltaY;
}
p.positionX += newX;
p.positionY += newY;
}
std::cout << p.positionX << " " << p.positionY
<< " " << p.positionR << "\n";
std::cout << t.targetX << " " << t.targetY
<< " " << pathR << " " << deltaR << "\n";
}
}<commit_msg>Add: aircraftAi barebone<commit_after>#include "MoveSystem.h"
#include <iostream>
#include <cmath>
void MoveSystem::update(int currentStep)
{
const std::vector<int> &uidList = movementNode.uids();
for(int i = 0; i < uidList.size(); i++)
{
int uid = uidList.at(i);
MovementNode &n = movementNode.get(uid);
PositionComponent &p = n.position;
const VelocityComponent &v = n.velocity;
const PositionTargetComponent &t = n.target;
// estimate XY angle
int deltaX = t.targetX - p.positionX;
int deltaY = t.targetY - p.positionY;
double pathRad = std::atan2(deltaY, deltaX);
int pathR = (int) (pathRad * 180. / M_PI);
int deltaR = deltaX != 0 || deltaY != 0 ? pathR - p.positionR :
t.targetR - p.positionR;
if (deltaR <= -180)
{
deltaR = -360 - deltaR;
}
else if (deltaR >= 180)
{
deltaR = 360 - deltaR;
}
else if (deltaX == 0 && deltaY == 0 && deltaR == 0)
{
continue;
}
// move angular
else if (std::abs(deltaR) > v.velocityR)
{
p.positionR = deltaR > 0 ? p.positionR + v.velocityR :
deltaR < 0 ? p.positionR - v.velocityR :
pathR;
}
// move forward
else
{
p.positionR = pathR;
int newX = (int) (v.velocityFB * std::cos(pathRad));
if (std::abs(newX) > std::abs(deltaX))
{
newX = deltaX;
}
int newY = (int) (v.velocityFB * std::sin(pathRad));
if (std::abs(newY) > std::abs(deltaY))
{
newY = deltaY;
}
p.positionX += newX;
p.positionY += newY;
}
std::cout << p.positionX << " " << p.positionY
<< " " << p.positionR << "\n";
std::cout << t.targetX << " " << t.targetY
<< " " << pathR << " " << deltaR << "\n";
}
}<|endoftext|> |
<commit_before>// -----------------------------------------------------------------
// libpion: a C++ framework for building lightweight HTTP interfaces
// -----------------------------------------------------------------
// Copyright (C) 2007 Atomic Labs, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
#include <libpion/PionConfig.hpp>
#include <libpion/PionPlugin.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#ifdef WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#endif
namespace pion { // begin namespace pion
// static members of PionEngine
const std::string PionPlugin::PION_PLUGIN_CREATE("pion_create_");
const std::string PionPlugin::PION_PLUGIN_DESTROY("pion_destroy_");
#ifdef WIN32
const std::string PionPlugin::PION_PLUGIN_EXTENSION(".dll");
#else
const std::string PionPlugin::PION_PLUGIN_EXTENSION(".so");
#endif
const std::string PionPlugin::PION_CONFIG_EXTENSION(".conf");
std::vector<std::string> PionPlugin::m_plugin_dirs;
boost::mutex PionPlugin::m_plugin_mutex;
// PionEngine member functions
void PionPlugin::addPluginDirectory(const std::string& dir)
{
#ifdef WIN32
// work around bug in boost::filesystem on Windows -> do not plugin directories
// basically, if you create a path object on Windows, then convert it to
// native_directory_string() or native_file_string(), then try to construct
// a new path object based on the string, it throws an exception (ugh!!!)
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
m_plugin_dirs.push_back(dir);
#else
boost::filesystem::path plugin_path(dir, &boost::filesystem::no_check);
checkCygwinPath(plugin_path, dir);
if (! boost::filesystem::exists(plugin_path) )
throw DirectoryNotFoundException(dir);
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
m_plugin_dirs.push_back(plugin_path.native_directory_string());
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
m_plugin_dirs.push_back(plugin_path.native_directory_string());
#endif
}
void PionPlugin::resetPluginDirectories(void)
{
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
m_plugin_dirs.clear();
}
void PionPlugin::checkCygwinPath(boost::filesystem::path& final_path,
const std::string& start_path)
{
#if defined(WIN32) && defined(PION_CYGWIN_DIRECTORY)
// try prepending PION_CYGWIN_DIRECTORY if not complete
if (! final_path.is_complete() && final_path.has_root_directory())
{
final_path = boost::filesystem::path(std::string(PION_CYGWIN_DIRECTORY) + start_path,
&boost::filesystem::no_check);
}
#endif
}
bool PionPlugin::findFile(std::string& path_to_file, const std::string& name,
const std::string& extension)
{
// first, try the name as-is
if (checkForFile(path_to_file, name, "", extension))
return true;
// nope, check search paths
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
for (std::vector<std::string>::iterator i = m_plugin_dirs.begin();
i != m_plugin_dirs.end(); ++i)
{
if (checkForFile(path_to_file, *i, name, extension))
return true;
}
// no plug-in file found
return false;
}
bool PionPlugin::checkForFile(std::string& final_path, const std::string& start_path,
const std::string& name, const std::string& extension)
{
// check for cygwin path oddities
boost::filesystem::path cygwin_safe_path(start_path, &boost::filesystem::no_check);
checkCygwinPath(cygwin_safe_path, start_path);
boost::filesystem::path test_path(cygwin_safe_path);
// if a name is specified, append it to the test path
if (! name.empty())
test_path /= boost::filesystem::path(name, &boost::filesystem::no_check);
// check for existence of plug-in (without extension)
if (boost::filesystem::exists(test_path)) {
final_path = test_path.native_file_string();
return true;
}
// next, try appending the plug-in extension
if (name.empty()) {
// no "name" specified -> append it directly to start_path
test_path = boost::filesystem::path(start_path + extension,
&boost::filesystem::no_check);
// in this case, we need to re-check for the cygwin oddities
checkCygwinPath(test_path, start_path + extension);
} else {
// name is specified, so we can just re-use cygwin_safe_path
test_path = cygwin_safe_path /
boost::filesystem::path(name + extension,
&boost::filesystem::no_check);
}
// re-check for existence of plug-in (after adding extension)
if (boost::filesystem::exists(test_path)) {
final_path = test_path.native_file_string();
return true;
}
// no plug-in file found
return false;
}
std::string PionPlugin::getPluginName(const std::string& plugin_file)
{
// strip path
#ifdef WIN32
std::string::size_type pos = plugin_file.find_last_of('\\');
#else
std::string::size_type pos = plugin_file.find_last_of('/');
#endif
std::string plugin_name = (pos == std::string::npos ?
plugin_file : plugin_file.substr(pos+1));
pos = plugin_name.find('.');
// truncate extension
if (pos != std::string::npos)
plugin_name.resize(pos);
return plugin_name;
}
void *PionPlugin::loadDynamicLibrary(const std::string& plugin_file)
{
#ifdef WIN32
return LoadLibrary(plugin_file.c_str());
#else
return dlopen(plugin_file.c_str(), RTLD_LAZY);
#endif
}
void PionPlugin::closeDynamicLibrary(void *lib_handle)
{
#ifdef WIN32
FreeLibrary((HINSTANCE) lib_handle);
#else
dlclose(lib_handle);
#endif
}
void *PionPlugin::getLibrarySymbol(void *lib_handle, const std::string& symbol)
{
#ifdef WIN32
return (void*)GetProcAddress((HINSTANCE) lib_handle, symbol.c_str());
#else
return dlsym(lib_handle, symbol.c_str());
#endif
}
} // end namespace pion
<commit_msg>Oops too much cut and pasting<commit_after>// -----------------------------------------------------------------
// libpion: a C++ framework for building lightweight HTTP interfaces
// -----------------------------------------------------------------
// Copyright (C) 2007 Atomic Labs, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
#include <libpion/PionConfig.hpp>
#include <libpion/PionPlugin.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#ifdef WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#endif
namespace pion { // begin namespace pion
// static members of PionEngine
const std::string PionPlugin::PION_PLUGIN_CREATE("pion_create_");
const std::string PionPlugin::PION_PLUGIN_DESTROY("pion_destroy_");
#ifdef WIN32
const std::string PionPlugin::PION_PLUGIN_EXTENSION(".dll");
#else
const std::string PionPlugin::PION_PLUGIN_EXTENSION(".so");
#endif
const std::string PionPlugin::PION_CONFIG_EXTENSION(".conf");
std::vector<std::string> PionPlugin::m_plugin_dirs;
boost::mutex PionPlugin::m_plugin_mutex;
// PionEngine member functions
void PionPlugin::addPluginDirectory(const std::string& dir)
{
#ifdef WIN32
// work around bug in boost::filesystem on Windows -> do not plugin directories
// basically, if you create a path object on Windows, then convert it to
// native_directory_string() or native_file_string(), then try to construct
// a new path object based on the string, it throws an exception (ugh!!!)
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
m_plugin_dirs.push_back(dir);
#else
boost::filesystem::path plugin_path(dir, &boost::filesystem::no_check);
checkCygwinPath(plugin_path, dir);
if (! boost::filesystem::exists(plugin_path) )
throw DirectoryNotFoundException(dir);
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
m_plugin_dirs.push_back(plugin_path.native_directory_string());
#endif
}
void PionPlugin::resetPluginDirectories(void)
{
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
m_plugin_dirs.clear();
}
void PionPlugin::checkCygwinPath(boost::filesystem::path& final_path,
const std::string& start_path)
{
#if defined(WIN32) && defined(PION_CYGWIN_DIRECTORY)
// try prepending PION_CYGWIN_DIRECTORY if not complete
if (! final_path.is_complete() && final_path.has_root_directory())
{
final_path = boost::filesystem::path(std::string(PION_CYGWIN_DIRECTORY) + start_path,
&boost::filesystem::no_check);
}
#endif
}
bool PionPlugin::findFile(std::string& path_to_file, const std::string& name,
const std::string& extension)
{
// first, try the name as-is
if (checkForFile(path_to_file, name, "", extension))
return true;
// nope, check search paths
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
for (std::vector<std::string>::iterator i = m_plugin_dirs.begin();
i != m_plugin_dirs.end(); ++i)
{
if (checkForFile(path_to_file, *i, name, extension))
return true;
}
// no plug-in file found
return false;
}
bool PionPlugin::checkForFile(std::string& final_path, const std::string& start_path,
const std::string& name, const std::string& extension)
{
// check for cygwin path oddities
boost::filesystem::path cygwin_safe_path(start_path, &boost::filesystem::no_check);
checkCygwinPath(cygwin_safe_path, start_path);
boost::filesystem::path test_path(cygwin_safe_path);
// if a name is specified, append it to the test path
if (! name.empty())
test_path /= boost::filesystem::path(name, &boost::filesystem::no_check);
// check for existence of plug-in (without extension)
if (boost::filesystem::exists(test_path)) {
final_path = test_path.native_file_string();
return true;
}
// next, try appending the plug-in extension
if (name.empty()) {
// no "name" specified -> append it directly to start_path
test_path = boost::filesystem::path(start_path + extension,
&boost::filesystem::no_check);
// in this case, we need to re-check for the cygwin oddities
checkCygwinPath(test_path, start_path + extension);
} else {
// name is specified, so we can just re-use cygwin_safe_path
test_path = cygwin_safe_path /
boost::filesystem::path(name + extension,
&boost::filesystem::no_check);
}
// re-check for existence of plug-in (after adding extension)
if (boost::filesystem::exists(test_path)) {
final_path = test_path.native_file_string();
return true;
}
// no plug-in file found
return false;
}
std::string PionPlugin::getPluginName(const std::string& plugin_file)
{
// strip path
#ifdef WIN32
std::string::size_type pos = plugin_file.find_last_of('\\');
#else
std::string::size_type pos = plugin_file.find_last_of('/');
#endif
std::string plugin_name = (pos == std::string::npos ?
plugin_file : plugin_file.substr(pos+1));
pos = plugin_name.find('.');
// truncate extension
if (pos != std::string::npos)
plugin_name.resize(pos);
return plugin_name;
}
void *PionPlugin::loadDynamicLibrary(const std::string& plugin_file)
{
#ifdef WIN32
return LoadLibrary(plugin_file.c_str());
#else
return dlopen(plugin_file.c_str(), RTLD_LAZY);
#endif
}
void PionPlugin::closeDynamicLibrary(void *lib_handle)
{
#ifdef WIN32
FreeLibrary((HINSTANCE) lib_handle);
#else
dlclose(lib_handle);
#endif
}
void *PionPlugin::getLibrarySymbol(void *lib_handle, const std::string& symbol)
{
#ifdef WIN32
return (void*)GetProcAddress((HINSTANCE) lib_handle, symbol.c_str());
#else
return dlsym(lib_handle, symbol.c_str());
#endif
}
} // end namespace pion
<|endoftext|> |
<commit_before>#include "Rcpp_datatypes.h"
#include <Rcpp.h>
#include <s2/s2cap.h>
using namespace Rcpp;
// Wrap an S2Cap as a list in R with:
// [[1]] The axis as a 3D unit vector
// [[2]] The height as a numeric
List S2CapWrapForR(const S2Cap& cap){
NumericVector axis(3);
S2Point a = cap.axis();
axis[0] = a.x();
axis[1] = a.y();
axis[2] = a.z();
double height = cap.height();
auto rslt = List::create(Named("axis") = axis, Named("height") = height);
rslt.attr( "class" ) = "S2Cap" ;
return rslt;
}
//' Construct a S2Cap using axis and height
//'
//' Constructs a S2Cap from axis and height
//'
//' @param axis A numeric vector with three entries represtenting the direction axis.
//' @param height Single numeric representing the height of the cap.
//' @export S2CapFromAxisHeight
//[[Rcpp::export]]
List S2CapFromAxisHeight(NumericVector axis, double height){
S2Point a = S2Point(axis[0], axis[1], axis[2]);
return S2CapWrapForR(S2Cap::FromAxisHeight(a, height));
}
S2Cap R_S2CapFromList(List list){
NumericVector axis = list["axis"];
double height = list["height"];
S2Point a = S2Point(axis[0], axis[1], axis[2]);
return S2Cap::FromAxisHeight(a, height);
}
//[[Rcpp::export]]
LogicalVector S2Cap_contains_point(NumericMatrix points, List cap){
S2Cap c = R_S2CapFromList(cap);
auto s2points = S2PointVecFromR(points);
int n = s2points.size();
LogicalVector rslt(n);
for(int i = 0; i < n; i++){
rslt(i) = c.Contains(s2points[i]);
}
return rslt;
}
//' Area of s2cap
//'
//' Area of a cap
//'
//' @param cap Named list containing axis and height of cap.
//' @export S2Cap_area
//[[Rcpp::export]]
double S2Cap_area(List cap){
S2Cap c = R_S2CapFromList(cap);
return c.area();
}<commit_msg>Renamed cap wrapper.<commit_after>#include "Rcpp_datatypes.h"
#include <Rcpp.h>
#include <s2/s2cap.h>
using namespace Rcpp;
// Wrap an S2Cap as a list in R with:
// [[1]] The axis as a 3D unit vector
// [[2]] The height as a numeric
List S2CapToR(const S2Cap& cap){
NumericVector axis(3);
S2Point a = cap.axis();
axis[0] = a.x();
axis[1] = a.y();
axis[2] = a.z();
double height = cap.height();
auto rslt = List::create(Named("axis") = axis, Named("height") = height);
rslt.attr( "class" ) = "S2Cap" ;
return rslt;
}
//' Construct a S2Cap using axis and height
//'
//' Constructs a S2Cap from axis and height
//'
//' @param axis A numeric vector with three entries represtenting the direction axis.
//' @param height Single numeric representing the height of the cap.
//' @export S2CapFromAxisHeight
//[[Rcpp::export]]
List S2CapFromAxisHeight(NumericVector axis, double height){
S2Point a = S2Point(axis[0], axis[1], axis[2]);
return S2CapToR(S2Cap::FromAxisHeight(a, height));
}
S2Cap R_S2CapFromList(List list){
NumericVector axis = list["axis"];
double height = list["height"];
S2Point a = S2Point(axis[0], axis[1], axis[2]);
return S2Cap::FromAxisHeight(a, height);
}
//[[Rcpp::export]]
LogicalVector S2Cap_contains_point(NumericMatrix points, List cap){
S2Cap c = R_S2CapFromList(cap);
auto s2points = S2PointVecFromR(points);
int n = s2points.size();
LogicalVector rslt(n);
for(int i = 0; i < n; i++){
rslt(i) = c.Contains(s2points[i]);
}
return rslt;
}
//' Area of s2cap
//'
//' Area of a cap
//'
//' @param cap Named list containing axis and height of cap.
//' @export S2Cap_area
//[[Rcpp::export]]
double S2Cap_area(List cap){
S2Cap c = R_S2CapFromList(cap);
return c.area();
}<|endoftext|> |
<commit_before>#include <Refal2.h>
namespace Refal2 {
//-----------------------------------------------------------------------------
CRuleParser::CRuleParser( IErrorHandler* errorHandler ):
CQualifierParser( errorHandler )
{
Reset();
}
void CRuleParser::Reset()
{
CQualifierParser::Reset();
SetWrong();
}
void CRuleParser::BeginFunction()
{
functionName = token;
BeginRule();
}
void CRuleParser::EndFunction()
{
//assert( IsFinished() );
if( !functionName.word.empty() ) {
CRulePtr firstRule;
CFunctionBuilder::Export( firstRule );
if( static_cast<bool>( firstRule ) ) {
CModuleBuilder::SetOrdinary( functionName, firstRule );
} else {
CModuleBuilder::SetEmpty( functionName );
}
functionName.word.clear();
}
}
void CRuleParser::BeginRule()
{
//assert( IsFinished() );
CParsingElementState::Reset();
state = &CRuleParser::direction;
}
void CRuleParser::AddToken()
{
assert( !IsFinished() );
( this->*state )();
}
void CRuleParser::error( const std::string& message )
{
SetWrong();
CErrorsHelper::Error( message );
}
void CRuleParser::direction()
{
if( token.type == TT_Blank ) {
return;
}
state = &CRuleParser::afterDirection;
if( token.type == TT_Word && token.word.length() == 1 ) {
switch( token.word[0] ) {
case 'r':
case 'R':
CFunctionBuilder::SetRightDirection();
return;
case 'l':
case 'L':
return;
default:
break;
}
}
AddToken();
}
void CRuleParser::afterDirection()
{
switch( token.type ) {
case TT_Blank:
break;
case TT_Equal:
CFunctionBuilder::AddEndOfLeft();
break;
case TT_Comma:
error( "unexpected token in the function rule" );
break;
case TT_Label:
CFunctionBuilder::AddLabel( CModuleBuilder::Declare( token ) );
break;
case TT_Number:
CFunctionBuilder::AddNumber( token.number );
break;
case TT_String:
for( std::string::size_type i = 0; i < token.word.length(); i++ ) {
CFunctionBuilder::AddChar( token.word[i] );
}
break;
case TT_Qualifier:
error( "unexpected qualifier in the function rule" );
break;
case TT_LeftParen:
CFunctionBuilder::AddLeftParen();
break;
case TT_RightParen:
CFunctionBuilder::AddRightParen();
break;
case TT_LeftBracket:
state = &CRuleParser::afterLeftBracket;
CFunctionBuilder::AddLeftBracket();
break;
case TT_RightBracket:
CFunctionBuilder::AddRightBracket();
break;
case TT_Word:
wordAfterDirection();
break;
case TT_LineFeed:
CFunctionBuilder::AddEndOfRight();
SetCorrect();
break;
default:
assert( false );
break;
}
}
void CRuleParser::wordAfterDirection()
{
assert( token.type == TT_Word );
while( !token.word.empty() ) {
if( token.word[0] == 'k' ) {
CFunctionBuilder::AddLeftBracket();
token.position++;
token.word.erase( 0, 1 );
} else {
variableType = token.word[0];
if( token.word.length() > 1 ) {
CFunctionBuilder::AddVariable( variableType, token.word[1] );
token.position += 2;
token.word.erase( 0, 2 );
} else {
state = &CRuleParser::afterVariableType;
return;
}
}
}
}
void CRuleParser::afterLeftBracket()
{
state = &CRuleParser::afterDirection;
if( token.type == TT_Word ) {
CFunctionBuilder::AddLabel( CModuleBuilder::Declare( token ) );
} else {
AddToken();
}
}
void CRuleParser::afterVariableType()
{
if( token.type == TT_LeftParen ) {
CQualifierParser::StartQualifer();
state = &CRuleParser::variableQualifier;
} else if( token.type == TT_Qualifier ) {
if( CModuleBuilder::GetNamedQualifier( token, qualifier ) ) {
state = &CRuleParser::afterVariableQualifier;
} else {
SetWrong();
}
} else {
error( "unexpected token after variable type" );
}
}
void CRuleParser::variableQualifier()
{
CQualifierParser::AddToken();
if( IsCorrect() ) {
CQualifierParser::GetQualifier( qualifier );
CParsingElementState::Reset();
state = &CRuleParser::afterVariableQualifier;
}
}
void CRuleParser::afterVariableQualifier()
{
if( token.type == TT_Word ) {
state = &CRuleParser::afterDirection;
CFunctionBuilder::AddVariable( variableType, token.word[0], &qualifier );
token.word.erase( 0, 1 );
token.position++;
wordAfterDirection();
} else {
error( "missing variable name" );
}
}
//-----------------------------------------------------------------------------
} // end of namespace Refal2
<commit_msg>refactoring<commit_after>#include <Refal2.h>
namespace Refal2 {
//-----------------------------------------------------------------------------
const char* const RuleLeftMatchingDirectionTag = "l";
const char* const RuleRightMatchingDirectionTag = "r";
const char RuleLeftBracketTag = 'k';
CRuleParser::CRuleParser( IErrorHandler* errorHandler ):
CQualifierParser( errorHandler )
{
Reset();
}
void CRuleParser::Reset()
{
CQualifierParser::Reset();
SetWrong();
}
void CRuleParser::BeginFunction()
{
assert( token.type == TT_Word && !token.word.empty() );
functionName = token;
BeginRule();
}
void CRuleParser::EndFunction()
{
if( !functionName.IsNone() ) {
assert( !token.word.empty() );
CRulePtr firstRule;
CFunctionBuilder::Export( firstRule );
if( static_cast<bool>( firstRule ) ) {
CModuleBuilder::SetOrdinary( functionName, firstRule );
} else {
CModuleBuilder::SetEmpty( functionName );
}
functionName = CToken();
}
}
void CRuleParser::BeginRule()
{
CParsingElementState::Reset();
state = &CRuleParser::direction;
}
void CRuleParser::AddToken()
{
assert( !IsFinished() );
( this->*state )();
}
void CRuleParser::error( const std::string& message )
{
SetWrong();
CErrorsHelper::Error( message );
}
void CRuleParser::direction()
{
if( token.type == TT_Blank ) {
return;
}
state = &CRuleParser::afterDirection;
if( token.type == TT_Word ) {
if( CompareNoCase( token.word, RuleRightMatchingDirectionTag ) ) {
CFunctionBuilder::SetRightDirection();
return;
} else if( CompareNoCase( token.word, RuleLeftMatchingDirectionTag ) ) {
return;
}
}
AddToken();
}
void CRuleParser::afterDirection()
{
switch( token.type ) {
case TT_Blank:
break;
case TT_Equal:
CFunctionBuilder::AddEndOfLeft();
break;
case TT_Comma:
error( "unexpected token in the function rule" );
break;
case TT_Label:
CFunctionBuilder::AddLabel( CModuleBuilder::Declare( token ) );
break;
case TT_Number:
CFunctionBuilder::AddNumber( token.number );
break;
case TT_String:
for( std::string::size_type i = 0; i < token.word.length(); i++ ) {
CFunctionBuilder::AddChar( token.word[i] );
}
break;
case TT_Qualifier:
error( "unexpected qualifier in the function rule" );
break;
case TT_LeftParen:
CFunctionBuilder::AddLeftParen();
break;
case TT_RightParen:
CFunctionBuilder::AddRightParen();
break;
case TT_LeftBracket:
state = &CRuleParser::afterLeftBracket;
CFunctionBuilder::AddLeftBracket();
break;
case TT_RightBracket:
CFunctionBuilder::AddRightBracket();
break;
case TT_Word:
wordAfterDirection();
break;
case TT_LineFeed:
CFunctionBuilder::AddEndOfRight();
SetCorrect();
break;
default:
assert( false );
break;
}
}
void CRuleParser::wordAfterDirection()
{
assert( token.type == TT_Word );
while( !token.word.empty() ) {
if( CompareCharNoCase( token.word[0], 'k' ) ) {
CFunctionBuilder::AddLeftBracket();
token.position++;
token.word.erase( 0, 1 );
} else {
variableType = token.word[0];
if( token.word.length() > 1 ) {
CFunctionBuilder::AddVariable( variableType, token.word[1] );
token.position += 2;
token.word.erase( 0, 2 );
} else {
state = &CRuleParser::afterVariableType;
return;
}
}
}
}
void CRuleParser::afterLeftBracket()
{
state = &CRuleParser::afterDirection;
if( token.type == TT_Word ) {
CFunctionBuilder::AddLabel( CModuleBuilder::Declare( token ) );
} else {
AddToken();
}
}
void CRuleParser::afterVariableType()
{
if( token.type == TT_LeftParen ) {
CQualifierParser::StartQualifer();
state = &CRuleParser::variableQualifier;
} else if( token.type == TT_Qualifier ) {
if( CModuleBuilder::GetNamedQualifier( token, qualifier ) ) {
state = &CRuleParser::afterVariableQualifier;
} else {
SetWrong();
}
} else {
error( "unexpected token after variable type" );
}
}
void CRuleParser::variableQualifier()
{
CQualifierParser::AddToken();
if( IsCorrect() ) {
CQualifierParser::GetQualifier( qualifier );
CParsingElementState::Reset();
state = &CRuleParser::afterVariableQualifier;
}
}
void CRuleParser::afterVariableQualifier()
{
if( token.type == TT_Word ) {
state = &CRuleParser::afterDirection;
CFunctionBuilder::AddVariable( variableType, token.word[0], &qualifier );
token.word.erase( 0, 1 );
token.position++;
wordAfterDirection();
} else {
error( "missing variable name" );
}
}
//-----------------------------------------------------------------------------
} // end of namespace Refal2
<|endoftext|> |
<commit_before>//
// ogles_gpgpu project - GPGPU for mobile devices and embedded systems using OpenGL ES 2.0
//
// Author: Markus Konrad <[email protected]>, Winter 2014/2015
// http://www.mkonrad.net
//
// See LICENSE file in project repository root for the license.
//
#include "../../common_includes.h"
#include "gauss_opt_pass.h"
#include <cmath>
using namespace ogles_gpgpu;
void getOptimizedGaussian(int blurRadius, float sigma, std::vector<GLfloat> &weights, std::vector<GLfloat> &offsets)
{
std::vector<GLfloat> standardGaussianWeights(blurRadius + 1);
GLfloat sumOfWeights = 0.0;
GLfloat sigma2 = sigma*sigma;
GLfloat norm = (1.0 / std::sqrt(2.0 * M_PI * sigma2));
for (int currentGaussianWeightIndex = 0; currentGaussianWeightIndex < (blurRadius + 1); currentGaussianWeightIndex++)
{
standardGaussianWeights[currentGaussianWeightIndex] = norm * std::exp(-std::pow(currentGaussianWeightIndex, 2.0) / (2.0 * sigma2));
if (currentGaussianWeightIndex == 0)
{
sumOfWeights += standardGaussianWeights[currentGaussianWeightIndex];
}
else
{
sumOfWeights += 2.0 * standardGaussianWeights[currentGaussianWeightIndex];
}
}
// Next, normalize these weights to prevent the clipping of the Gaussian curve at the end of the discrete samples from reducing luminance
for (int currentGaussianWeightIndex = 0; currentGaussianWeightIndex < (blurRadius + 1); currentGaussianWeightIndex++)
{
standardGaussianWeights[currentGaussianWeightIndex] = standardGaussianWeights[currentGaussianWeightIndex] / sumOfWeights;
}
// From these weights we calculate the offsets to read interpolated values from
int numberOfOptimizedOffsets = std::min(blurRadius / 2 + (blurRadius % 2), 7);
std::vector<GLfloat> optimizedGaussianOffsets(numberOfOptimizedOffsets);
for (int currentOptimizedOffset = 0; currentOptimizedOffset < numberOfOptimizedOffsets; currentOptimizedOffset++)
{
GLfloat firstWeight = standardGaussianWeights[currentOptimizedOffset*2 + 1];
GLfloat secondWeight = standardGaussianWeights[currentOptimizedOffset*2 + 2];
GLfloat optimizedWeight = firstWeight + secondWeight;
optimizedGaussianOffsets[currentOptimizedOffset] = (firstWeight * (currentOptimizedOffset*2 + 1) + secondWeight * (currentOptimizedOffset*2 + 2)) / optimizedWeight;
}
weights = standardGaussianWeights;
offsets = optimizedGaussianOffsets;
}
std::string fragmentShaderForOptimizedBlur(int blurRadius, float sigma, bool doNorm = false, int pass = 1, float normConst=0.005f)
{
std::vector<GLfloat> standardGaussianWeights;
std::vector<GLfloat> optimizedGaussianOffsets;
getOptimizedGaussian(blurRadius, sigma, standardGaussianWeights, optimizedGaussianOffsets);
// From these weights we calculate the offsets to read interpolated values from
int numberOfOptimizedOffsets = std::min(blurRadius / 2 + (blurRadius % 2), 7);
int trueNumberOfOptimizedOffsets = blurRadius / 2 + (blurRadius % 2);
std::stringstream ss;
ss << "uniform sampler2D inputImageTexture;\n";
ss << "uniform float texelWidthOffset;\n";
ss << "uniform float texelHeightOffset;\n\n";
ss << "varying vec2 blurCoordinates[" << (1 + (numberOfOptimizedOffsets * 2)) << "];\n\n";
ss << "void main()\n";
ss << "{\n";
ss << " vec4 sum = vec4(0.0);\n";
ss << " vec4 center = texture2D(inputImageTexture, blurCoordinates[0]);\n";
ss << " sum += center * " << standardGaussianWeights[0] << ";\n";
for (int currentBlurCoordinateIndex = 0; currentBlurCoordinateIndex < numberOfOptimizedOffsets; currentBlurCoordinateIndex++)
{
GLfloat firstWeight = standardGaussianWeights[currentBlurCoordinateIndex * 2 + 1];
GLfloat secondWeight = standardGaussianWeights[currentBlurCoordinateIndex * 2 + 2];
GLfloat optimizedWeight = firstWeight + secondWeight;
int index1 = (unsigned long)((currentBlurCoordinateIndex * 2) + 1);
int index2 = (unsigned long)((currentBlurCoordinateIndex * 2) + 2);
ss << " sum += texture2D(inputImageTexture, blurCoordinates[" << index1 << "]) * " << optimizedWeight <<";\n";
ss << " sum += texture2D(inputImageTexture, blurCoordinates[" << index2 << "]) * " << optimizedWeight <<";\n";
}
// If the number of required samples exceeds the amount we can pass in via varyings, we have to do dependent texture reads in the fragment shader
if (trueNumberOfOptimizedOffsets > numberOfOptimizedOffsets)
{
ss << " vec2 singleStepOffset = vec2(texelWidthOffset, texelHeightOffset);\n";
for (int currentOverlowTextureRead = numberOfOptimizedOffsets; currentOverlowTextureRead < trueNumberOfOptimizedOffsets; currentOverlowTextureRead++)
{
GLfloat firstWeight = standardGaussianWeights[currentOverlowTextureRead * 2 + 1];
GLfloat secondWeight = standardGaussianWeights[currentOverlowTextureRead * 2 + 2];
GLfloat optimizedWeight = firstWeight + secondWeight;
GLfloat optimizedOffset = (firstWeight * (currentOverlowTextureRead * 2 + 1) + secondWeight * (currentOverlowTextureRead * 2 + 2)) / optimizedWeight;
ss << " sum += texture2D(inputImageTexture, blurCoordinates[0] + singleStepOffset * " << optimizedOffset << ") * " << optimizedWeight << ";\n";
ss << " sum += texture2D(inputImageTexture, blurCoordinates[0] - singleStepOffset * " << optimizedOffset << ") * " << optimizedWeight << ";\n";
}
}
if(doNorm)
{
if(pass == 1)
{
ss << " gl_FragColor = vec4(center.rgb, sum.r);\n";
}
else
{
ss << " gl_FragColor = vec4( center.r/(sum.a + " << std::fixed << normConst << "), center.gb, 1.0);\n";
}
}
else
{
ss << " gl_FragColor = sum;\n";
}
ss << "}\n";
return ss.str();
}
std::string vertexShaderForOptimizedBlur(int blurRadius, float sigma)
{
std::vector<GLfloat> standardGaussianWeights;
std::vector<GLfloat> optimizedGaussianOffsets;
getOptimizedGaussian(blurRadius, sigma, standardGaussianWeights, optimizedGaussianOffsets);
int numberOfOptimizedOffsets = optimizedGaussianOffsets.size();
std::stringstream ss;
ss << "attribute vec4 position;\n";
ss << "attribute vec4 inputTextureCoordinate;\n";
ss << "uniform float texelWidthOffset;\n";
ss << "uniform float texelHeightOffset;\n\n";
ss << "varying vec2 blurCoordinates[" << (unsigned long)(1 + (numberOfOptimizedOffsets * 2)) << "];\n\n";
ss << "void main()\n";
ss << "{\n";
ss << " gl_Position = position;\n";
ss << " vec2 singleStepOffset = vec2(texelWidthOffset, texelHeightOffset);\n";
ss << " blurCoordinates[0] = inputTextureCoordinate.xy;\n";
for (int currentOptimizedOffset = 0; currentOptimizedOffset < numberOfOptimizedOffsets; currentOptimizedOffset++)
{
int x1 = (unsigned long)((currentOptimizedOffset * 2) + 1);
int x2 = (unsigned long)((currentOptimizedOffset * 2) + 2);
const auto &optOffset = optimizedGaussianOffsets[currentOptimizedOffset];
ss << " blurCoordinates[" << x1 << "] = inputTextureCoordinate.xy + singleStepOffset * " << optOffset << ";\n";
ss << " blurCoordinates[" << x2 << "] = inputTextureCoordinate.xy + singleStepOffset * " << optOffset << ";\n";
}
ss << "}\n";
return ss.str();
}
void GaussOptProcPass::setRadius(float newValue)
{
if (std::round(newValue) != _blurRadiusInPixels)
{
_blurRadiusInPixels = std::round(newValue); // For now, only do integral sigmas
int calculatedSampleRadius = 0;
if (_blurRadiusInPixels >= 1) // Avoid a divide-by-zero error here
{
// Calculate the number of pixels to sample from by setting a bottom limit for the contribution of the outermost pixel
float minimumWeightToFindEdgeOfSamplingArea = 1.0/256.0;
float radius2 = std::pow(_blurRadiusInPixels, 2.0) ;
calculatedSampleRadius = std::floor(std::sqrt(-2.0 * radius2 * std::log(minimumWeightToFindEdgeOfSamplingArea * std::sqrt(2.0 * M_PI * radius2))));
calculatedSampleRadius += calculatedSampleRadius % 2; // There's nothing to gain from handling odd radius sizes, due to the optimizations I use
}
//std::cout << "Blur radius " << _blurRadiusInPixels << " calculated sample radius " << calculatedSampleRadius << std::endl;
//std::cout << "===" << std::endl;
vshaderGaussSrc = vertexShaderForOptimizedBlur(calculatedSampleRadius, _blurRadiusInPixels);
fshaderGaussSrc = fragmentShaderForOptimizedBlur(calculatedSampleRadius, _blurRadiusInPixels, doNorm, renderPass, normConst);
std::cout << vshaderGaussSrc << std::endl;
std::cout << fshaderGaussSrc << std::endl;
}
}
// TODO: We need to override this if we are using the GPUImage shaders
void GaussOptProcPass::filterShaderSetup(const char *vShaderSrc, const char *fShaderSrc, GLenum target)
{
// create shader object
ProcBase::createShader(vShaderSrc, fShaderSrc, target);
// get shader params
shParamAPos = shader->getParam(ATTR, "position");
shParamATexCoord = shader->getParam(ATTR, "inputTextureCoordinate");
Tools::checkGLErr(getProcName(), "filterShaderSetup");
}
void GaussOptProcPass::setUniforms()
{
FilterProcBase::setUniforms();
glUniform1f(shParamUTexelWidthOffset, (renderPass == 1) * pxDx);
glUniform1f(shParamUTexelHeightOffset, (renderPass == 2) * pxDy);
}
void GaussOptProcPass::getUniforms()
{
FilterProcBase::getUniforms();
// calculate pixel delta values
pxDx = 1.0f / (float)outFrameW; // input or output?
pxDy = 1.0f / (float)outFrameH;
shParamUInputTex = shader->getParam(UNIF, "inputImageTexture");
shParamUTexelWidthOffset = shader->getParam(UNIF, "texelWidthOffset");
shParamUTexelHeightOffset = shader->getParam(UNIF, "texelHeightOffset");
}
const char *GaussOptProcPass::getFragmentShaderSource()
{
return fshaderGaussSrc.c_str();
}
const char *GaussOptProcPass::getVertexShaderSource()
{
return vshaderGaussSrc.c_str();
}
<commit_msg>Don't print the shader source<commit_after>//
// ogles_gpgpu project - GPGPU for mobile devices and embedded systems using OpenGL ES 2.0
//
// Author: Markus Konrad <[email protected]>, Winter 2014/2015
// http://www.mkonrad.net
//
// See LICENSE file in project repository root for the license.
//
#include "../../common_includes.h"
#include "gauss_opt_pass.h"
#include <cmath>
using namespace ogles_gpgpu;
void getOptimizedGaussian(int blurRadius, float sigma, std::vector<GLfloat> &weights, std::vector<GLfloat> &offsets)
{
std::vector<GLfloat> standardGaussianWeights(blurRadius + 1);
GLfloat sumOfWeights = 0.0;
GLfloat sigma2 = sigma*sigma;
GLfloat norm = (1.0 / std::sqrt(2.0 * M_PI * sigma2));
for (int currentGaussianWeightIndex = 0; currentGaussianWeightIndex < (blurRadius + 1); currentGaussianWeightIndex++)
{
standardGaussianWeights[currentGaussianWeightIndex] = norm * std::exp(-std::pow(currentGaussianWeightIndex, 2.0) / (2.0 * sigma2));
if (currentGaussianWeightIndex == 0)
{
sumOfWeights += standardGaussianWeights[currentGaussianWeightIndex];
}
else
{
sumOfWeights += 2.0 * standardGaussianWeights[currentGaussianWeightIndex];
}
}
// Next, normalize these weights to prevent the clipping of the Gaussian curve at the end of the discrete samples from reducing luminance
for (int currentGaussianWeightIndex = 0; currentGaussianWeightIndex < (blurRadius + 1); currentGaussianWeightIndex++)
{
standardGaussianWeights[currentGaussianWeightIndex] = standardGaussianWeights[currentGaussianWeightIndex] / sumOfWeights;
}
// From these weights we calculate the offsets to read interpolated values from
int numberOfOptimizedOffsets = std::min(blurRadius / 2 + (blurRadius % 2), 7);
std::vector<GLfloat> optimizedGaussianOffsets(numberOfOptimizedOffsets);
for (int currentOptimizedOffset = 0; currentOptimizedOffset < numberOfOptimizedOffsets; currentOptimizedOffset++)
{
GLfloat firstWeight = standardGaussianWeights[currentOptimizedOffset*2 + 1];
GLfloat secondWeight = standardGaussianWeights[currentOptimizedOffset*2 + 2];
GLfloat optimizedWeight = firstWeight + secondWeight;
optimizedGaussianOffsets[currentOptimizedOffset] = (firstWeight * (currentOptimizedOffset*2 + 1) + secondWeight * (currentOptimizedOffset*2 + 2)) / optimizedWeight;
}
weights = standardGaussianWeights;
offsets = optimizedGaussianOffsets;
}
std::string fragmentShaderForOptimizedBlur(int blurRadius, float sigma, bool doNorm = false, int pass = 1, float normConst=0.005f)
{
std::vector<GLfloat> standardGaussianWeights;
std::vector<GLfloat> optimizedGaussianOffsets;
getOptimizedGaussian(blurRadius, sigma, standardGaussianWeights, optimizedGaussianOffsets);
// From these weights we calculate the offsets to read interpolated values from
int numberOfOptimizedOffsets = std::min(blurRadius / 2 + (blurRadius % 2), 7);
int trueNumberOfOptimizedOffsets = blurRadius / 2 + (blurRadius % 2);
std::stringstream ss;
ss << "uniform sampler2D inputImageTexture;\n";
ss << "uniform float texelWidthOffset;\n";
ss << "uniform float texelHeightOffset;\n\n";
ss << "varying vec2 blurCoordinates[" << (1 + (numberOfOptimizedOffsets * 2)) << "];\n\n";
ss << "void main()\n";
ss << "{\n";
ss << " vec4 sum = vec4(0.0);\n";
ss << " vec4 center = texture2D(inputImageTexture, blurCoordinates[0]);\n";
ss << " sum += center * " << standardGaussianWeights[0] << ";\n";
for (int currentBlurCoordinateIndex = 0; currentBlurCoordinateIndex < numberOfOptimizedOffsets; currentBlurCoordinateIndex++)
{
GLfloat firstWeight = standardGaussianWeights[currentBlurCoordinateIndex * 2 + 1];
GLfloat secondWeight = standardGaussianWeights[currentBlurCoordinateIndex * 2 + 2];
GLfloat optimizedWeight = firstWeight + secondWeight;
int index1 = (unsigned long)((currentBlurCoordinateIndex * 2) + 1);
int index2 = (unsigned long)((currentBlurCoordinateIndex * 2) + 2);
ss << " sum += texture2D(inputImageTexture, blurCoordinates[" << index1 << "]) * " << optimizedWeight <<";\n";
ss << " sum += texture2D(inputImageTexture, blurCoordinates[" << index2 << "]) * " << optimizedWeight <<";\n";
}
// If the number of required samples exceeds the amount we can pass in via varyings, we have to do dependent texture reads in the fragment shader
if (trueNumberOfOptimizedOffsets > numberOfOptimizedOffsets)
{
ss << " vec2 singleStepOffset = vec2(texelWidthOffset, texelHeightOffset);\n";
for (int currentOverlowTextureRead = numberOfOptimizedOffsets; currentOverlowTextureRead < trueNumberOfOptimizedOffsets; currentOverlowTextureRead++)
{
GLfloat firstWeight = standardGaussianWeights[currentOverlowTextureRead * 2 + 1];
GLfloat secondWeight = standardGaussianWeights[currentOverlowTextureRead * 2 + 2];
GLfloat optimizedWeight = firstWeight + secondWeight;
GLfloat optimizedOffset = (firstWeight * (currentOverlowTextureRead * 2 + 1) + secondWeight * (currentOverlowTextureRead * 2 + 2)) / optimizedWeight;
ss << " sum += texture2D(inputImageTexture, blurCoordinates[0] + singleStepOffset * " << optimizedOffset << ") * " << optimizedWeight << ";\n";
ss << " sum += texture2D(inputImageTexture, blurCoordinates[0] - singleStepOffset * " << optimizedOffset << ") * " << optimizedWeight << ";\n";
}
}
if(doNorm)
{
if(pass == 1)
{
ss << " gl_FragColor = vec4(center.rgb, sum.r);\n";
}
else
{
ss << " gl_FragColor = vec4( center.r/(sum.a + " << std::fixed << normConst << "), center.gb, 1.0);\n";
}
}
else
{
ss << " gl_FragColor = sum;\n";
}
ss << "}\n";
return ss.str();
}
std::string vertexShaderForOptimizedBlur(int blurRadius, float sigma)
{
std::vector<GLfloat> standardGaussianWeights;
std::vector<GLfloat> optimizedGaussianOffsets;
getOptimizedGaussian(blurRadius, sigma, standardGaussianWeights, optimizedGaussianOffsets);
int numberOfOptimizedOffsets = optimizedGaussianOffsets.size();
std::stringstream ss;
ss << "attribute vec4 position;\n";
ss << "attribute vec4 inputTextureCoordinate;\n";
ss << "uniform float texelWidthOffset;\n";
ss << "uniform float texelHeightOffset;\n\n";
ss << "varying vec2 blurCoordinates[" << (unsigned long)(1 + (numberOfOptimizedOffsets * 2)) << "];\n\n";
ss << "void main()\n";
ss << "{\n";
ss << " gl_Position = position;\n";
ss << " vec2 singleStepOffset = vec2(texelWidthOffset, texelHeightOffset);\n";
ss << " blurCoordinates[0] = inputTextureCoordinate.xy;\n";
for (int currentOptimizedOffset = 0; currentOptimizedOffset < numberOfOptimizedOffsets; currentOptimizedOffset++)
{
int x1 = (unsigned long)((currentOptimizedOffset * 2) + 1);
int x2 = (unsigned long)((currentOptimizedOffset * 2) + 2);
const auto &optOffset = optimizedGaussianOffsets[currentOptimizedOffset];
ss << " blurCoordinates[" << x1 << "] = inputTextureCoordinate.xy + singleStepOffset * " << optOffset << ";\n";
ss << " blurCoordinates[" << x2 << "] = inputTextureCoordinate.xy + singleStepOffset * " << optOffset << ";\n";
}
ss << "}\n";
return ss.str();
}
void GaussOptProcPass::setRadius(float newValue)
{
if (std::round(newValue) != _blurRadiusInPixels)
{
_blurRadiusInPixels = std::round(newValue); // For now, only do integral sigmas
int calculatedSampleRadius = 0;
if (_blurRadiusInPixels >= 1) // Avoid a divide-by-zero error here
{
// Calculate the number of pixels to sample from by setting a bottom limit for the contribution of the outermost pixel
float minimumWeightToFindEdgeOfSamplingArea = 1.0/256.0;
float radius2 = std::pow(_blurRadiusInPixels, 2.0) ;
calculatedSampleRadius = std::floor(std::sqrt(-2.0 * radius2 * std::log(minimumWeightToFindEdgeOfSamplingArea * std::sqrt(2.0 * M_PI * radius2))));
calculatedSampleRadius += calculatedSampleRadius % 2; // There's nothing to gain from handling odd radius sizes, due to the optimizations I use
}
//std::cout << "Blur radius " << _blurRadiusInPixels << " calculated sample radius " << calculatedSampleRadius << std::endl;
//std::cout << "===" << std::endl;
vshaderGaussSrc = vertexShaderForOptimizedBlur(calculatedSampleRadius, _blurRadiusInPixels);
fshaderGaussSrc = fragmentShaderForOptimizedBlur(calculatedSampleRadius, _blurRadiusInPixels, doNorm, renderPass, normConst);
//std::cout << vshaderGaussSrc << std::endl;
//std::cout << fshaderGaussSrc << std::endl;
}
}
// TODO: We need to override this if we are using the GPUImage shaders
void GaussOptProcPass::filterShaderSetup(const char *vShaderSrc, const char *fShaderSrc, GLenum target)
{
// create shader object
ProcBase::createShader(vShaderSrc, fShaderSrc, target);
// get shader params
shParamAPos = shader->getParam(ATTR, "position");
shParamATexCoord = shader->getParam(ATTR, "inputTextureCoordinate");
Tools::checkGLErr(getProcName(), "filterShaderSetup");
}
void GaussOptProcPass::setUniforms()
{
FilterProcBase::setUniforms();
glUniform1f(shParamUTexelWidthOffset, (renderPass == 1) * pxDx);
glUniform1f(shParamUTexelHeightOffset, (renderPass == 2) * pxDy);
}
void GaussOptProcPass::getUniforms()
{
FilterProcBase::getUniforms();
// calculate pixel delta values
pxDx = 1.0f / (float)outFrameW; // input or output?
pxDy = 1.0f / (float)outFrameH;
shParamUInputTex = shader->getParam(UNIF, "inputImageTexture");
shParamUTexelWidthOffset = shader->getParam(UNIF, "texelWidthOffset");
shParamUTexelHeightOffset = shader->getParam(UNIF, "texelHeightOffset");
}
const char *GaussOptProcPass::getFragmentShaderSource()
{
return fshaderGaussSrc.c_str();
}
const char *GaussOptProcPass::getVertexShaderSource()
{
return vshaderGaussSrc.c_str();
}
<|endoftext|> |
<commit_before>#include "TextWidget.hpp"
#include <iostream>
gsf::TextWidget::TextWidget()
{
}
gsf::TextWidget::TextWidget(std::string text, sf::Font &font)
{
init(text, font, 12, sf::Color::Black);
}
gsf::TextWidget::TextWidget(std::string text, sf::Font &font, int characterSize)
{
init(text, font, characterSize, sf::Color::Black);
}
gsf::TextWidget::TextWidget(std::string text, sf::Font &font, int characterSize, sf::Color color)
{
init(text, font, characterSize, color);
}
void gsf::TextWidget::init(std::string text, sf::Font &font, int characterSize, sf::Color color)
{
m_text.setString(text);
m_text.setFont(font);
m_text.setCharacterSize(characterSize);
m_text.setColor(color);
calculateSize();
}
gsf::TextWidget::~TextWidget()
{
}
/*
sf::Text& gsf::TextWidget::getText()
{
return m_text;
}
*/
void gsf::TextWidget::setText(const std::string text)
{
m_text.setString(text);
}
std::string gsf::TextWidget::getText() const
{
return m_text.getString().toAnsiString();
}
void gsf::TextWidget::setCharacterSize(const unsigned int size)
{
m_text.setCharacterSize(size);
calculateSize();
centerOrigin();
}
unsigned int gsf::TextWidget::getCharacterSize() const
{
return m_text.getCharacterSize();
}
void gsf::TextWidget::setTextColor(const sf::Color color)
{
m_text.setColor(color);
}
sf::Color gsf::TextWidget::getTextColor() const
{
return m_text.getColor();
}
void gsf::TextWidget::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
states.transform *= getTransform();
// Draw background
sf::RectangleShape bgShape({ m_width, m_height });
bgShape.setFillColor(m_bgColor);
target.draw(bgShape, states);
// Draw text
target.draw(m_text, states);
}
void gsf::TextWidget::update(float dt)
{
// Do nothing by default
}
bool gsf::TextWidget::handleEvent(sf::Event &event)
{
bool handled = Widget::handleEvent(event);
/*
if (event.type == sf::Event::MouseButtonPressed)
{
if (event.mouseButton.button == sf::Mouse::Left && isIntersecting(sf::Vector2f(event.mouseButton.x , event.mouseButton.y)))
{
std::cout << "TextWidget: Left Mouse Button Clicked. Text: " << m_text.getString().toAnsiString() << std::endl;
return true;
}
}
*/
return handled;
}
void gsf::TextWidget::calculateSize()
{
sf::FloatRect localBounds = { m_text.getLocalBounds() };
// Top and left of the bounds are not allways 0, so we add the twice amound of this,
// So the text is centered in the widget
setHeight(localBounds.height + localBounds.top * 2);
setWidth(localBounds.width + localBounds.left * 2);
}
<commit_msg>Adjust size after text change<commit_after>#include "TextWidget.hpp"
#include <iostream>
gsf::TextWidget::TextWidget()
{
}
gsf::TextWidget::TextWidget(std::string text, sf::Font &font)
{
init(text, font, 12, sf::Color::Black);
}
gsf::TextWidget::TextWidget(std::string text, sf::Font &font, int characterSize)
{
init(text, font, characterSize, sf::Color::Black);
}
gsf::TextWidget::TextWidget(std::string text, sf::Font &font, int characterSize, sf::Color color)
{
init(text, font, characterSize, color);
}
void gsf::TextWidget::init(std::string text, sf::Font &font, int characterSize, sf::Color color)
{
m_text.setString(text);
m_text.setFont(font);
m_text.setCharacterSize(characterSize);
m_text.setColor(color);
calculateSize();
}
gsf::TextWidget::~TextWidget()
{
}
/*
sf::Text& gsf::TextWidget::getText()
{
return m_text;
}
*/
void gsf::TextWidget::setText(const std::string text)
{
m_text.setString(text);
calculateSize();
centerOrigin();
}
std::string gsf::TextWidget::getText() const
{
return m_text.getString().toAnsiString();
}
void gsf::TextWidget::setCharacterSize(const unsigned int size)
{
m_text.setCharacterSize(size);
calculateSize();
centerOrigin();
}
unsigned int gsf::TextWidget::getCharacterSize() const
{
return m_text.getCharacterSize();
}
void gsf::TextWidget::setTextColor(const sf::Color color)
{
m_text.setColor(color);
}
sf::Color gsf::TextWidget::getTextColor() const
{
return m_text.getColor();
}
void gsf::TextWidget::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
states.transform *= getTransform();
// Draw background
sf::RectangleShape bgShape({ m_width, m_height });
bgShape.setFillColor(m_bgColor);
target.draw(bgShape, states);
// Draw text
target.draw(m_text, states);
}
void gsf::TextWidget::update(float dt)
{
// Do nothing by default
}
bool gsf::TextWidget::handleEvent(sf::Event &event)
{
bool handled = Widget::handleEvent(event);
/*
if (event.type == sf::Event::MouseButtonPressed)
{
if (event.mouseButton.button == sf::Mouse::Left && isIntersecting(sf::Vector2f(event.mouseButton.x , event.mouseButton.y)))
{
std::cout << "TextWidget: Left Mouse Button Clicked. Text: " << m_text.getString().toAnsiString() << std::endl;
return true;
}
}
*/
return handled;
}
void gsf::TextWidget::calculateSize()
{
sf::FloatRect localBounds = { m_text.getLocalBounds() };
// Top and left of the bounds are not allways 0, so we add the twice amound of this,
// So the text is centered in the widget
setHeight(localBounds.height + localBounds.top * 2);
setWidth(localBounds.width + localBounds.left * 2);
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
*
* Authors: Hugo Beauzée-Luyssen <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "VideoGroup.h"
#include "Media.h"
#include "medialibrary/IMediaLibrary.h"
#include "database/SqliteQuery.h"
namespace medialibrary
{
const std::string VideoGroup::Table::Name = "VideoGroup";
VideoGroup::VideoGroup( MediaLibraryPtr ml, sqlite::Row& row )
: m_ml( ml )
, m_name( row.extract<decltype(m_name)>() )
, m_count( row.extract<decltype(m_count)>() )
{
assert( row.hasRemainingColumns() == false );
}
const std::string& VideoGroup::name() const
{
return m_name;
}
size_t VideoGroup::count() const
{
return m_count;
}
Query<IMedia> VideoGroup::media( const QueryParameters* params ) const
{
return Media::fromGroup( m_ml, m_name, params );
}
Query<IVideoGroup> VideoGroup::listAll( MediaLibraryPtr ml, const QueryParameters* params )
{
auto sort = params != nullptr ? params->sort : SortingCriteria::Default;
auto desc = params != nullptr ? params->desc : false;
std::string req = "SELECT * FROM " + Table::Name;
const std::string countReq = "SELECT COUNT() FROM " + Table::Name;
switch ( sort )
{
default:
LOG_INFO( "Unsupported sorting criteria for media groups, falling "
"back to default" );
/* fall-through */
case SortingCriteria::Alpha:
case SortingCriteria::Default:
req += " ORDER BY grp";
break;
case SortingCriteria::NbMedia:
case SortingCriteria::NbVideo:
req += " ORDER BY cnt";
break;
}
if ( desc == true )
req += " DESC";
return make_query_with_count<VideoGroup, IVideoGroup>( ml, countReq, req);
}
VideoGroupPtr VideoGroup::fromName( MediaLibraryPtr ml, const std::string& name )
{
const std::string req = "SELECT * FROM " + Table::Name +
" WHERE grp = LOWER(?)";
return fetch( ml, req, name );
}
std::string VideoGroup::schema( const std::string& tableName, uint32_t )
{
assert( tableName == Table::Name );
return "CREATE VIEW " + Table::Name + " AS"
" SELECT "
"LOWER(SUBSTR("
"CASE "
"WHEN title LIKE 'The %' THEN SUBSTR(title, 5) "
"ELSE title "
"END, "
"1, (SELECT video_groups_prefix_length FROM Settings)))"
" as grp, COUNT() as cnt"
" FROM Media "
" WHERE type = " +
std::to_string( static_cast<std::underlying_type_t<IMedia::Type>>(
IMedia::Type::Video ) ) +
" GROUP BY grp";
}
void VideoGroup::createView( sqlite::Connection* dbConn )
{
std::string reqs[] = {
schema( Table::Name, Settings::DbModelVersion ),
};
for ( const auto& req : reqs )
sqlite::Tools::executeRequest( dbConn, req );
}
}
<commit_msg>VideoGroup: Don't include the missing media in the count<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
*
* Authors: Hugo Beauzée-Luyssen <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "VideoGroup.h"
#include "Media.h"
#include "medialibrary/IMediaLibrary.h"
#include "database/SqliteQuery.h"
namespace medialibrary
{
const std::string VideoGroup::Table::Name = "VideoGroup";
VideoGroup::VideoGroup( MediaLibraryPtr ml, sqlite::Row& row )
: m_ml( ml )
, m_name( row.extract<decltype(m_name)>() )
, m_count( row.extract<decltype(m_count)>() )
{
assert( row.hasRemainingColumns() == false );
}
const std::string& VideoGroup::name() const
{
return m_name;
}
size_t VideoGroup::count() const
{
return m_count;
}
Query<IMedia> VideoGroup::media( const QueryParameters* params ) const
{
return Media::fromGroup( m_ml, m_name, params );
}
Query<IVideoGroup> VideoGroup::listAll( MediaLibraryPtr ml, const QueryParameters* params )
{
auto sort = params != nullptr ? params->sort : SortingCriteria::Default;
auto desc = params != nullptr ? params->desc : false;
std::string req = "SELECT * FROM " + Table::Name;
const std::string countReq = "SELECT COUNT() FROM " + Table::Name;
switch ( sort )
{
default:
LOG_INFO( "Unsupported sorting criteria for media groups, falling "
"back to default" );
/* fall-through */
case SortingCriteria::Alpha:
case SortingCriteria::Default:
req += " ORDER BY grp";
break;
case SortingCriteria::NbMedia:
case SortingCriteria::NbVideo:
req += " ORDER BY cnt";
break;
}
if ( desc == true )
req += " DESC";
return make_query_with_count<VideoGroup, IVideoGroup>( ml, countReq, req);
}
VideoGroupPtr VideoGroup::fromName( MediaLibraryPtr ml, const std::string& name )
{
const std::string req = "SELECT * FROM " + Table::Name +
" WHERE grp = LOWER(?)";
return fetch( ml, req, name );
}
std::string VideoGroup::schema( const std::string& tableName, uint32_t )
{
assert( tableName == Table::Name );
return "CREATE VIEW " + Table::Name + " AS"
" SELECT "
"LOWER(SUBSTR("
"CASE "
"WHEN title LIKE 'The %' THEN SUBSTR(title, 5) "
"ELSE title "
"END, "
"1, (SELECT video_groups_prefix_length FROM Settings)))"
" as grp, COUNT() as cnt"
" FROM Media "
" WHERE type = " +
std::to_string( static_cast<std::underlying_type_t<IMedia::Type>>(
IMedia::Type::Video ) ) +
" AND is_present != 0"
" GROUP BY grp";
}
void VideoGroup::createView( sqlite::Connection* dbConn )
{
std::string reqs[] = {
schema( Table::Name, Settings::DbModelVersion ),
};
for ( const auto& req : reqs )
sqlite::Tools::executeRequest( dbConn, req );
}
}
<|endoftext|> |
<commit_before>//
// File: Actor.cpp
// Class: Actor
// Author: John Barbero Unenge
// All code is my own except where credited to others.
//
// Copyright (c) 2012 Catch22. All Rights Reserved.
//
// Date: 2/10/12
//
// License: The following code is licensed under the Catch22-License
//
#include "Actor.hpp"
#include "../Helper/Logger.hpp"
#include "../Helper/Constants.hpp"
Actor::Actor(AnimationArray* animations, Animation* currentAnimation, Vector2d* halfSize, OffsetMatrix* offsetMatrix)
{
CreateActor(animations, currentAnimation, halfSize, offsetMatrix);
}
Actor::Actor(AnimationArray* animations, Animation* currentAnimation, Vector2d* halfSize)
{
CreateActor(animations, currentAnimation, halfSize, new OffsetMatrix(new Vector2d(0.f, 0.f), new Vector2d(0.f, 0.f), new Vector2d(0.f, 0.f), new Vector2d(0.f, 0.f)));
}
Actor::Actor(Actor* actor)
{
CreateActor(new AnimationArray(actor->m_animations), new Animation(actor->m_currentAnimation), new Vector2d(actor->m_halfSize), new OffsetMatrix(actor->m_offset));
}
void Actor::CreateActor(AnimationArray* animations, Animation* currentAnimation, Vector2d* halfSize, OffsetMatrix* offsetMatrix)
{
m_pBody = 0;
m_animations = animations;
m_currentAnimation = currentAnimation;
m_halfSize = halfSize;
m_offset = offsetMatrix;
}
void Actor::setPBody(PBody* pBody)
{
m_pBody = pBody;
}
const Vertex* Actor::getVertexData()
{
if (m_pBody != 0) {
const Vertex* v = new const Vertex[4]
{
Vertex(m_pBody->getBody()->GetPosition().x - m_offset->m_topLeft->m_x,
m_pBody->getBody()->GetPosition().y + m_halfSize->m_y * 2 + m_offset->m_topLeft->m_y),
Vertex(m_pBody->getBody()->GetPosition().x + m_halfSize->m_x * 2 + m_offset->m_topRight->m_x,
m_pBody->getBody()->GetPosition().y + m_halfSize->m_y * 2 + m_offset->m_topRight->m_y),
Vertex(m_pBody->getBody()->GetPosition().x + m_halfSize->m_x * 2 + m_offset->m_bottomRight->m_x,
m_pBody->getBody()->GetPosition().y - m_offset->m_bottomRight->m_y),
Vertex(m_pBody->getBody()->GetPosition().x - m_offset->m_bottomLeft->m_x,
m_pBody->getBody()->GetPosition().y - m_offset->m_bottomLeft->m_y),
};
return v;
}
return 0;
}
const Vertex* Actor::getTextureVertexData()
{
if (m_currentAnimation == 0) {
Log(LOG_ERROR, "Actor", "Current animation null!");
return 0;
}
return m_currentAnimation->getTextureVertexData();
}
int Actor::getTextureID()
{
return m_currentAnimation->getTextureID();
}
void Actor::update(float dt){
m_currentAnimation->update(dt);
}
float Actor::getAngle()
{
return this->m_pBody->getBody()->GetAngle();
}
<commit_msg>Changed how offset works<commit_after>//
// File: Actor.cpp
// Class: Actor
// Author: John Barbero Unenge
// All code is my own except where credited to others.
//
// Copyright (c) 2012 Catch22. All Rights Reserved.
//
// Date: 2/10/12
//
// License: The following code is licensed under the Catch22-License
//
#include "Actor.hpp"
#include "../Helper/Logger.hpp"
#include "../Helper/Constants.hpp"
Actor::Actor(AnimationArray* animations, Animation* currentAnimation, Vector2d* halfSize, OffsetMatrix* offsetMatrix)
{
CreateActor(animations, currentAnimation, halfSize, offsetMatrix);
}
Actor::Actor(AnimationArray* animations, Animation* currentAnimation, Vector2d* halfSize)
{
CreateActor(animations, currentAnimation, halfSize, new OffsetMatrix(new Vector2d(0.f, 0.f), new Vector2d(0.f, 0.f), new Vector2d(0.f, 0.f), new Vector2d(0.f, 0.f)));
}
Actor::Actor(Actor* actor)
{
CreateActor(new AnimationArray(actor->m_animations), new Animation(actor->m_currentAnimation), new Vector2d(actor->m_halfSize), new OffsetMatrix(actor->m_offset));
}
void Actor::CreateActor(AnimationArray* animations, Animation* currentAnimation, Vector2d* halfSize, OffsetMatrix* offsetMatrix)
{
m_pBody = 0;
m_animations = animations;
m_currentAnimation = currentAnimation;
m_halfSize = halfSize;
m_offset = offsetMatrix;
}
void Actor::setPBody(PBody* pBody)
{
m_pBody = pBody;
}
const Vertex* Actor::getVertexData()
{
if (m_pBody != 0) {
const Vertex* v = new const Vertex[4]
{
/* Top right point */
Vertex(m_pBody->getBody()->GetPosition().x + m_offset->m_topRight->m_x,
m_pBody->getBody()->GetPosition().y + m_halfSize->m_y * 2 + m_offset->m_topRight->m_y),
/* Top left point */
Vertex(m_pBody->getBody()->GetPosition().x + m_halfSize->m_x * 2 + m_offset->m_topLeft->m_x,
m_pBody->getBody()->GetPosition().y + m_halfSize->m_y * 2 + m_offset->m_topLeft->m_y),
/* Bottom left point */
Vertex(m_pBody->getBody()->GetPosition().x + m_halfSize->m_x * 2 + m_offset->m_bottomLeft->m_x,
m_pBody->getBody()->GetPosition().y + m_offset->m_bottomLeft->m_y),
/* Bottom right point */
Vertex(m_pBody->getBody()->GetPosition().x + m_offset->m_bottomRight->m_x,
m_pBody->getBody()->GetPosition().y + m_offset->m_bottomRight->m_y),
};
return v;
}
return 0;
}
const Vertex* Actor::getTextureVertexData()
{
if (m_currentAnimation == 0) {
Log(LOG_ERROR, "Actor", "Current animation null!");
return 0;
}
return m_currentAnimation->getTextureVertexData();
}
int Actor::getTextureID()
{
return m_currentAnimation->getTextureID();
}
void Actor::update(float dt){
m_currentAnimation->update(dt);
}
float Actor::getAngle()
{
return this->m_pBody->getBody()->GetAngle();
}
<|endoftext|> |
<commit_before>// @(#)root/base:$Id$
// Author: G. Ganis 2012
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TStatistic //
// //
// Statistical variable, defined by its mean and RMS. //
// Named, streamable, storable and mergeable. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TStatistic.h"
templateClassImp(TStatistic)
//______________________________________________________________________________
TStatistic::TStatistic(const char *name, Int_t n, const Double_t *val, const Double_t *w)
: fName(name), fN(0), fW(0.), fW2(0.), fMean(0.), fM2(0.)
{
// Constructor from a vector of values
if (n > 0) {
for (Int_t i = 0; i < n; i++) {
if (w) {
Fill(val[i], w[i]);
} else {
Fill(val[i]);
}
}
}
}<commit_msg>Add trailing newline (silence warning)<commit_after>// @(#)root/base:$Id$
// Author: G. Ganis 2012
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TStatistic //
// //
// Statistical variable, defined by its mean and RMS. //
// Named, streamable, storable and mergeable. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TStatistic.h"
templateClassImp(TStatistic)
//______________________________________________________________________________
TStatistic::TStatistic(const char *name, Int_t n, const Double_t *val, const Double_t *w)
: fName(name), fN(0), fW(0.), fW2(0.), fMean(0.), fM2(0.)
{
// Constructor from a vector of values
if (n > 0) {
for (Int_t i = 0; i < n; i++) {
if (w) {
Fill(val[i], w[i]);
} else {
Fill(val[i]);
}
}
}
}
<|endoftext|> |
<commit_before>// test using 1D Distribution object interface
// and compare results and CPU performances using TF1::GetRandom
//
// run within ROOT (.x unuranDistr.cxx+) or pass any extra parameter in the command line to get
// a graphics output
#include "TStopwatch.h"
#include "TUnuran.h"
#include "TUnuranContDist.h"
#include "TH1.h"
#include "TF1.h"
#include "TRandom3.h"
#include "TSystem.h"
#include "TStyle.h"
#include "TApplication.h"
#include "TCanvas.h"
#include "Math/DistFunc.h"
#include <cmath>
#include <cassert>
#include "TError.h"
#include <iostream>
using std::cout;
using std::endl;
int n = 5000000;
bool useRandomSeed = false; // to use a random seed different every time
double par[1] = {1}; // function parameters
double norm(double *x, double *p) {
return ROOT::Math::normal_pdf(x[0],p[0]);
}
double cdf(double *x, double *p) {
return ROOT::Math::normal_cdf(x[0],p[0]);
}
double cdf_trunc(double *x, double *p) {
double a1 = ROOT::Math::normal_cdf(p[1],p[0]);
double a2 = ROOT::Math::normal_cdf(p[2],p[0]);
return ( ROOT::Math::normal_cdf(x[0],p[0]) - a1 )/(a2-a1);
}
class DistTest {
public:
DistTest(TF1 * f) :
fCdf(f),
fHref(0)
{
// generate reference histo for distribution using cdf
// make ref histo (uniform histo between 0,1
fHref = new TH1D("Href","uniform ref histo",100,0,1);
for (int i = 0; i < n; ++i)
fHref->Fill(gRandom->Rndm() );
}
void SetCdf(TF1 *f) {
fCdf = f;
}
int testUnuran(TUnuran & unr) {
assert(fHref != 0);
assert(fCdf != 0);
// test first the time
TStopwatch w;
w.Start();
for (int i = 0; i < n; ++i)
unr.Sample();
w.Stop();
double time = w.CpuTime()*1.E9/n;
TH1D htmp("htmp","gaussian generated cdf",100,0,1.);
// test quality (use cdf to avoid zero bins)
int n2 = n/100;
double x;
for (int i = 0; i<n2; ++i) {
x = unr.Sample();
htmp.Fill( fCdf->Eval(x) );
}
double prob = fHref->Chi2Test(&htmp,"UU");
std::cout << "Time using Unuran " << unr.MethodName() << " \t=\t " << time << "\tns/call \t\tChi2 Prob = "<< prob << std::endl;
if (prob < 1E-06) {
std::cout << "Chi2 Test failed ! " << std::endl;
fHref->Chi2Test(&htmp,"UUP"); // print all chi2 test info
return 1;
}
return 0;
}
int testGetRandom(TF1 * f) {
assert(fHref != 0);
assert(fCdf != 0);
// test first the time
TStopwatch w;
w.Start();
for (int i = 0; i < n; ++i) {
f->GetRandom();
}
w.Stop();
double time = w.CpuTime()*1.E9/n;
TH1D htmp("htmp","gaussian generated cdf",100,0,1.);
// test quality (use cdf to avoid zero bins)
int n2 = n/100;
for (int i = 0; i<n2; ++i) {
double x = f->GetRandom();
htmp.Fill( fCdf->Eval(x) );
}
double prob = fHref->Chi2Test(&htmp,"UU");
std::cout << "Time using TF1::GetRandom() \t=\t " << time << "\tns/call \t\tChi2 Prob = "<< prob << std::endl;
if (prob < 1E-06) {
std::cout << "Chi2 Test failed ! " << std::endl;
fHref->Chi2Test(&htmp,"UUP"); // print all chi2 test info
return 2;
}
return 0;
}
private:
TF1 * fCdf; // cumulative distribution
TH1 * fHref; // reference histo
};
int unuranDistr() {
int iret = 0;
// switch off printing of info messages from chi2 test
gErrorIgnoreLevel = 1001;
// check if using a random seed
if (useRandomSeed) gRandom->SetSeed(0);
gSystem->Load("libUnuran");
// simple test of unuran
TH1D * h1 = new TH1D("h1","gaussian distribution",100,-10,10);
TH1D * h2 = new TH1D("h2","gaussian distribution",100,-10,10);
TH1D * h1u = new TH1D("h1u","test gaussian dist",100,0,1);
TH1D * h2u = new TH1D("h2u","test gaussian dist",100,0,1);
TF1 * f = new TF1("n",norm,-10,10,1);
f->SetParameters(par);
TF1 * fc = new TF1("c",cdf,0,1,1);
fc->SetParameters(par);
// tester class
DistTest t(fc);
// create unuran 1D distribution
TUnuranContDist dist(f);
// create unuran class
TUnuran unr(gRandom,2);
// test all unuran methods
bool ret = false;
// arou: needs pdf and dpdf (estimated numerically in dist class)
ret = unr.Init(dist,"arou");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -1;
}
else
iret |= t.testUnuran(unr);
// nrou (needs only pdf , mode is an option)
ret = unr.Init(dist,"nrou");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -2;
}
else
iret |= t.testUnuran(unr);
// tdr: needs pdf and dpdf (estimated numerically in dist class)
ret = unr.Init(dist,"tdr");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -3;
}
else
iret |= t.testUnuran(unr);
dist.SetCdf(fc);
// hinv (needs cdf , pdf and dpdf are optionally)
ret = unr.Init(dist,"hinv");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -4;
}
else
iret |= t.testUnuran(unr);
// ninv (needs cdf, pdf is an option)
ret = unr.Init(dist,"ninv");
n/= 10; // method is too slow
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -5;
}
else
iret |= t.testUnuran(unr);
dist.SetMode( 0.0 );
dist.SetPdfArea(1. );
// srou (need pdf mode sand area)
ret = unr.Init(dist,"srou");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -6;
}
else
iret |= t.testUnuran(unr);
// srou (need pdf mode sand area)
ret = unr.Init(dist,"ssr");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -7;
}
else
iret |= t.testUnuran(unr);
n*= 10;
ret = unr.Init(dist,"utdr");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -8;
}
else
iret |= t.testUnuran(unr);
// test with TF1::GetRandom
std::cout << "\n";
iret |= t.testGetRandom(f);
std::cout << "\nTest truncated distribution:\n\n";
dist.SetDomain(-1.,1.);
// change cdf for tester
TF1 * fc2 = new TF1("fc2",cdf_trunc,-1,1,3);
fc2->SetParameters(par[0],-1,1.);
t.SetCdf(fc2);
ret = unr.Init(dist,"auto");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -10;
}
else
iret |= t.testUnuran(unr);
f->SetRange(-1,1);
iret |= t.testGetRandom(f);
TCanvas * c1 = new TCanvas("c1_unuran1D","Onedimensional distribution",10,10,1000,1000);
c1->Divide(2,2);
gStyle->SetOptFit();
// remove the domain
dist.SetDomain(0,0);
//f->SetRange(1,-1);
f->SetRange(-10,10); // set verly low and large values is enough
// show now some plots
ret = unr.Init(dist,"auto");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -20;
}
int n2 = n/10;
for (int i = 0; i < n2; ++i) {
double x1 = unr.Sample();
h1->Fill( x1 );
h1u->Fill( fc->Eval( x1 ) );
double x2 = f->GetRandom();
h2->Fill( x2 );
h2u->Fill( fc->Eval( x2 ) );
}
c1->cd(1);
h1->Draw();
h1->Fit("gaus","Q");
std::cout << "\nFit result on data with unuran: " << std::endl;
TF1 * f1 = h1->GetFunction("gaus");
std::cout << "Gaus Fit chi2 = " << f1->GetChisquare() << " ndf = " << f1->GetNDF() << std::endl;
std::cout << "Gaus Fit Prob = " << f1->GetProb() << std::endl;
if ( f1->GetProb() < 1.E-6) iret = 11;
c1->cd(2);
h1u->Draw("Error");
h1u->Fit("pol0","Q");
TF1 * f1u = h1u->GetFunction("pol0");
std::cout << "CDF Fit chi2 = " << f1u->GetChisquare() << " ndf = " << f1u->GetNDF() << std::endl;
std::cout << "CDF Fit Prob = " << f1u->GetProb() << std::endl;
if ( f1u->GetProb() < 1.E-6) iret = 12;
c1->cd(3);
h2->Draw("same");
h2->Fit("gaus","Q");
std::cout << "\nFit result on data with GetRandom: " << std::endl;
f1 = h2->GetFunction("gaus");
std::cout << "Gaus Fit chi2 = " << f1->GetChisquare() << " ndf = " << f1->GetNDF() << std::endl;
std::cout << "Gaus Fit Prob = " << f1->GetProb() << std::endl;
if ( f1->GetProb() < 1.E-6) iret = 13;
c1->cd(4);
h2u->Draw("Error");
h2u->Fit("pol0","Q");
f1 = h2u->GetFunction("pol0");
std::cout << "Fit chi2 = " << f1->GetChisquare() << " ndf = " << f1->GetNDF() << std::endl;
std::cout << "Fit Prob = " << f1->GetProb() << std::endl;
if ( f1->GetProb() < 1.E-6) iret = 14;
std::cout << "Chi2 test Gaussian histograms :\t";
h1->Chi2Test(h2,"UUP");
std::cout << "Chi2 test Uniform histograms :\t";
h1u->Chi2Test(h2u,"UUP");
if (iret != 0)
std::cerr <<"\n\nUnuRan Continous Distribution Test:\t Failed !!!!!!!\n" << std::endl;
else
std::cerr << "\n\nUnuRan Continous Distribution Test:\t OK\n" << std::endl;
return iret;
return iret;
}
#ifndef __CINT__
int main(int argc, char **argv)
{
int iret = 0;
if (argc > 1) {
TApplication theApp("App",&argc,argv);
iret = unuranDistr();
theApp.Run();
}
else
iret = unuranDistr();
}
#endif
<commit_msg>avoids too generic of a name as a global variable<commit_after>// test using 1D Distribution object interface
// and compare results and CPU performances using TF1::GetRandom
//
// run within ROOT (.x unuranDistr.cxx+) or pass any extra parameter in the command line to get
// a graphics output
#include "TStopwatch.h"
#include "TUnuran.h"
#include "TUnuranContDist.h"
#include "TH1.h"
#include "TF1.h"
#include "TRandom3.h"
#include "TSystem.h"
#include "TStyle.h"
#include "TApplication.h"
#include "TCanvas.h"
#include "Math/DistFunc.h"
#include <cmath>
#include <cassert>
#include "TError.h"
#include <iostream>
using std::cout;
using std::endl;
int sampleSize = 5000000;
bool useRandomSeed = false; // to use a random seed different every time
double par[1] = {1}; // function parameters
double norm(double *x, double *p) {
return ROOT::Math::normal_pdf(x[0],p[0]);
}
double cdf(double *x, double *p) {
return ROOT::Math::normal_cdf(x[0],p[0]);
}
double cdf_trunc(double *x, double *p) {
double a1 = ROOT::Math::normal_cdf(p[1],p[0]);
double a2 = ROOT::Math::normal_cdf(p[2],p[0]);
return ( ROOT::Math::normal_cdf(x[0],p[0]) - a1 )/(a2-a1);
}
class DistTest {
public:
DistTest(TF1 * f) :
fCdf(f),
fHref(0)
{
// generate reference histo for distribution using cdf
// make ref histo (uniform histo between 0,1
fHref = new TH1D("Href","uniform ref histo",100,0,1);
for (int i = 0; i < sampleSize; ++i)
fHref->Fill(gRandom->Rndm() );
}
void SetCdf(TF1 *f) {
fCdf = f;
}
int testUnuran(TUnuran & unr) {
assert(fHref != 0);
assert(fCdf != 0);
// test first the time
TStopwatch w;
w.Start();
for (int i = 0; i < sampleSize; ++i)
unr.Sample();
w.Stop();
double time = w.CpuTime()*1.E9/sampleSize;
TH1D htmp("htmp","gaussian generated cdf",100,0,1.);
// test quality (use cdf to avoid zero bins)
int n2 = sampleSize/100;
double x;
for (int i = 0; i<n2; ++i) {
x = unr.Sample();
htmp.Fill( fCdf->Eval(x) );
}
double prob = fHref->Chi2Test(&htmp,"UU");
std::cout << "Time using Unuran " << unr.MethodName() << " \t=\t " << time << "\tns/call \t\tChi2 Prob = "<< prob << std::endl;
if (prob < 1E-06) {
std::cout << "Chi2 Test failed ! " << std::endl;
fHref->Chi2Test(&htmp,"UUP"); // print all chi2 test info
return 1;
}
return 0;
}
int testGetRandom(TF1 * f) {
assert(fHref != 0);
assert(fCdf != 0);
// test first the time
TStopwatch w;
w.Start();
for (int i = 0; i < sampleSize; ++i) {
f->GetRandom();
}
w.Stop();
double time = w.CpuTime()*1.E9/sampleSize;
TH1D htmp("htmp","gaussian generated cdf",100,0,1.);
// test quality (use cdf to avoid zero bins)
int n2 = sampleSize/100;
for (int i = 0; i<n2; ++i) {
double x = f->GetRandom();
htmp.Fill( fCdf->Eval(x) );
}
double prob = fHref->Chi2Test(&htmp,"UU");
std::cout << "Time using TF1::GetRandom() \t=\t " << time << "\tns/call \t\tChi2 Prob = "<< prob << std::endl;
if (prob < 1E-06) {
std::cout << "Chi2 Test failed ! " << std::endl;
fHref->Chi2Test(&htmp,"UUP"); // print all chi2 test info
return 2;
}
return 0;
}
private:
TF1 * fCdf; // cumulative distribution
TH1 * fHref; // reference histo
};
int unuranDistr() {
int iret = 0;
// switch off printing of info messages from chi2 test
gErrorIgnoreLevel = 1001;
// check if using a random seed
if (useRandomSeed) gRandom->SetSeed(0);
gSystem->Load("libUnuran");
// simple test of unuran
TH1D * h1 = new TH1D("h1","gaussian distribution",100,-10,10);
TH1D * h2 = new TH1D("h2","gaussian distribution",100,-10,10);
TH1D * h1u = new TH1D("h1u","test gaussian dist",100,0,1);
TH1D * h2u = new TH1D("h2u","test gaussian dist",100,0,1);
TF1 * f = new TF1("n",norm,-10,10,1);
f->SetParameters(par);
TF1 * fc = new TF1("c",cdf,0,1,1);
fc->SetParameters(par);
// tester class
DistTest t(fc);
// create unuran 1D distribution
TUnuranContDist dist(f);
// create unuran class
TUnuran unr(gRandom,2);
// test all unuran methods
bool ret = false;
// arou: needs pdf and dpdf (estimated numerically in dist class)
ret = unr.Init(dist,"arou");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -1;
}
else
iret |= t.testUnuran(unr);
// nrou (needs only pdf , mode is an option)
ret = unr.Init(dist,"nrou");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -2;
}
else
iret |= t.testUnuran(unr);
// tdr: needs pdf and dpdf (estimated numerically in dist class)
ret = unr.Init(dist,"tdr");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -3;
}
else
iret |= t.testUnuran(unr);
dist.SetCdf(fc);
// hinv (needs cdf , pdf and dpdf are optionally)
ret = unr.Init(dist,"hinv");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -4;
}
else
iret |= t.testUnuran(unr);
// ninv (needs cdf, pdf is an option)
ret = unr.Init(dist,"ninv");
sampleSize /= 10; // method is too slow
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -5;
}
else
iret |= t.testUnuran(unr);
dist.SetMode( 0.0 );
dist.SetPdfArea(1. );
// srou (need pdf mode sand area)
ret = unr.Init(dist,"srou");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -6;
}
else
iret |= t.testUnuran(unr);
// srou (need pdf mode sand area)
ret = unr.Init(dist,"ssr");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -7;
}
else
iret |= t.testUnuran(unr);
sampleSize *= 10;
ret = unr.Init(dist,"utdr");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -8;
}
else
iret |= t.testUnuran(unr);
// test with TF1::GetRandom
std::cout << "\n";
iret |= t.testGetRandom(f);
std::cout << "\nTest truncated distribution:\n\n";
dist.SetDomain(-1.,1.);
// change cdf for tester
TF1 * fc2 = new TF1("fc2",cdf_trunc,-1,1,3);
fc2->SetParameters(par[0],-1,1.);
t.SetCdf(fc2);
ret = unr.Init(dist,"auto");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -10;
}
else
iret |= t.testUnuran(unr);
f->SetRange(-1,1);
iret |= t.testGetRandom(f);
TCanvas * c1 = new TCanvas("c1_unuran1D","Onedimensional distribution",10,10,1000,1000);
c1->Divide(2,2);
gStyle->SetOptFit();
// remove the domain
dist.SetDomain(0,0);
//f->SetRange(1,-1);
f->SetRange(-10,10); // set verly low and large values is enough
// show now some plots
ret = unr.Init(dist,"auto");
if (!ret) {
std::cerr << "Error initializing unuran with method " << unr.MethodName() << std::endl;
iret = -20;
}
int n2 = sampleSize/10;
for (int i = 0; i < n2; ++i) {
double x1 = unr.Sample();
h1->Fill( x1 );
h1u->Fill( fc->Eval( x1 ) );
double x2 = f->GetRandom();
h2->Fill( x2 );
h2u->Fill( fc->Eval( x2 ) );
}
c1->cd(1);
h1->Draw();
h1->Fit("gaus","Q");
std::cout << "\nFit result on data with unuran: " << std::endl;
TF1 * f1 = h1->GetFunction("gaus");
std::cout << "Gaus Fit chi2 = " << f1->GetChisquare() << " ndf = " << f1->GetNDF() << std::endl;
std::cout << "Gaus Fit Prob = " << f1->GetProb() << std::endl;
if ( f1->GetProb() < 1.E-6) iret = 11;
c1->cd(2);
h1u->Draw("Error");
h1u->Fit("pol0","Q");
TF1 * f1u = h1u->GetFunction("pol0");
std::cout << "CDF Fit chi2 = " << f1u->GetChisquare() << " ndf = " << f1u->GetNDF() << std::endl;
std::cout << "CDF Fit Prob = " << f1u->GetProb() << std::endl;
if ( f1u->GetProb() < 1.E-6) iret = 12;
c1->cd(3);
h2->Draw("same");
h2->Fit("gaus","Q");
std::cout << "\nFit result on data with GetRandom: " << std::endl;
f1 = h2->GetFunction("gaus");
std::cout << "Gaus Fit chi2 = " << f1->GetChisquare() << " ndf = " << f1->GetNDF() << std::endl;
std::cout << "Gaus Fit Prob = " << f1->GetProb() << std::endl;
if ( f1->GetProb() < 1.E-6) iret = 13;
c1->cd(4);
h2u->Draw("Error");
h2u->Fit("pol0","Q");
f1 = h2u->GetFunction("pol0");
std::cout << "Fit chi2 = " << f1->GetChisquare() << " ndf = " << f1->GetNDF() << std::endl;
std::cout << "Fit Prob = " << f1->GetProb() << std::endl;
if ( f1->GetProb() < 1.E-6) iret = 14;
std::cout << "Chi2 test Gaussian histograms :\t";
h1->Chi2Test(h2,"UUP");
std::cout << "Chi2 test Uniform histograms :\t";
h1u->Chi2Test(h2u,"UUP");
if (iret != 0)
std::cerr <<"\n\nUnuRan Continous Distribution Test:\t Failed !!!!!!!\n" << std::endl;
else
std::cerr << "\n\nUnuRan Continous Distribution Test:\t OK\n" << std::endl;
return iret;
return iret;
}
#ifndef __CINT__
int main(int argc, char **argv)
{
int iret = 0;
if (argc > 1) {
TApplication theApp("App",&argc,argv);
iret = unuranDistr();
theApp.Run();
}
else
iret = unuranDistr();
}
#endif
<|endoftext|> |
<commit_before>/*
* Access logging.
*
* author: Max Kellermann <[email protected]>
*/
#include "access_log.hxx"
#ifndef NO_ACCESS_LOG
#include "http_server/Request.hxx"
#include "access_log/Glue.hxx"
#include <daemon/log.h>
#include <time.h>
static const char *
optional_string(const char *p)
{
if (p == nullptr)
return "-";
return p;
}
void
access_log(HttpServerRequest *request, const char *site,
const char *referer, const char *user_agent,
http_status_t status, int64_t content_length,
uint64_t bytes_received, uint64_t bytes_sent,
std::chrono::steady_clock::duration duration)
{
assert(request != nullptr);
assert(http_method_is_valid(request->method));
assert(http_status_is_valid(status));
const auto duration_us = std::chrono::duration_cast<std::chrono::microseconds>(duration);
if (log_global_enabled()) {
log_http_request(time(nullptr) * 1000000,
request->method, request->uri,
request->remote_host,
request->headers.Get("host"),
site,
referer, user_agent,
status, content_length,
bytes_received, bytes_sent,
duration_us.count());
return;
}
time_t now = time(nullptr);
char stamp[32];
if (site == nullptr)
site = "-";
strftime(stamp, sizeof(stamp),
"%d/%b/%Y:%H:%M:%S %z", localtime(&now));
char length_buffer[32];
const char *length;
if (content_length < 0)
length = "-";
else {
snprintf(length_buffer, sizeof(length_buffer), "%llu",
(unsigned long long)content_length);
length = length_buffer;
}
daemon_log(1, "%s %s - - [%s] \"%s %s HTTP/1.1\" %u %s \"%s\" \"%s\" %llu\n",
site, optional_string(request->remote_host), stamp,
http_method_to_string(request->method),
request->uri,
status, length,
optional_string(referer),
optional_string(user_agent),
(unsigned long long)duration_us.count());
}
#endif
<commit_msg>access_log: don't use daemon_log(), print directly to STDERR<commit_after>/*
* Access logging.
*
* author: Max Kellermann <[email protected]>
*/
#include "access_log.hxx"
#ifndef NO_ACCESS_LOG
#include "http_server/Request.hxx"
#include "access_log/Glue.hxx"
#include <stdio.h>
#include <time.h>
static const char *
optional_string(const char *p)
{
if (p == nullptr)
return "-";
return p;
}
void
access_log(HttpServerRequest *request, const char *site,
const char *referer, const char *user_agent,
http_status_t status, int64_t content_length,
uint64_t bytes_received, uint64_t bytes_sent,
std::chrono::steady_clock::duration duration)
{
assert(request != nullptr);
assert(http_method_is_valid(request->method));
assert(http_status_is_valid(status));
const auto duration_us = std::chrono::duration_cast<std::chrono::microseconds>(duration);
if (log_global_enabled()) {
log_http_request(time(nullptr) * 1000000,
request->method, request->uri,
request->remote_host,
request->headers.Get("host"),
site,
referer, user_agent,
status, content_length,
bytes_received, bytes_sent,
duration_us.count());
return;
}
time_t now = time(nullptr);
char stamp[32];
if (site == nullptr)
site = "-";
strftime(stamp, sizeof(stamp),
"%d/%b/%Y:%H:%M:%S %z", localtime(&now));
char length_buffer[32];
const char *length;
if (content_length < 0)
length = "-";
else {
snprintf(length_buffer, sizeof(length_buffer), "%llu",
(unsigned long long)content_length);
length = length_buffer;
}
printf("%s %s - - [%s] \"%s %s HTTP/1.1\" %u %s \"%s\" \"%s\" %llu\n",
site, optional_string(request->remote_host), stamp,
http_method_to_string(request->method),
request->uri,
status, length,
optional_string(referer),
optional_string(user_agent),
(unsigned long long)duration_us.count());
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2012 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 <string.h>
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "media/mp4/box_reader.h"
#include "media/mp4/rcheck.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace media {
namespace mp4 {
static const uint8 kSkipBox[] = {
// Top-level test box containing three children
0x00, 0x00, 0x00, 0x40, 's', 'k', 'i', 'p',
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0xf9, 0x0a, 0x0b, 0x0c, 0xfd, 0x0e, 0x0f, 0x10,
// Ordinary (8-byte header) child box
0x00, 0x00, 0x00, 0x0c, 'p', 's', 's', 'h', 0xde, 0xad, 0xbe, 0xef,
// Extended-size header child box
0x00, 0x00, 0x00, 0x01, 'p', 's', 's', 'h',
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14,
0xfa, 0xce, 0xca, 0xfe,
// Empty free box
0x00, 0x00, 0x00, 0x08, 'f', 'r', 'e', 'e',
// Trailing garbage
0x00 };
struct FreeBox : Box {
virtual bool Parse(BoxReader* reader) OVERRIDE {
return true;
}
virtual FourCC BoxType() const OVERRIDE { return FOURCC_FREE; }
};
struct PsshBox : Box {
uint32 val;
virtual bool Parse(BoxReader* reader) OVERRIDE {
return reader->Read4(&val);
}
virtual FourCC BoxType() const OVERRIDE { return FOURCC_PSSH; }
};
struct SkipBox : Box {
uint8 a, b;
uint16 c;
int32 d;
int64 e;
std::vector<PsshBox> kids;
FreeBox mpty;
virtual bool Parse(BoxReader* reader) OVERRIDE {
RCHECK(reader->ReadFullBoxHeader() &&
reader->Read1(&a) &&
reader->Read1(&b) &&
reader->Read2(&c) &&
reader->Read4s(&d) &&
reader->Read4sInto8s(&e));
return reader->ScanChildren() &&
reader->ReadChildren(&kids) &&
reader->MaybeReadChild(&mpty);
}
virtual FourCC BoxType() const OVERRIDE { return FOURCC_SKIP; }
SkipBox();
~SkipBox();
};
SkipBox::SkipBox() {}
SkipBox::~SkipBox() {}
class BoxReaderTest : public testing::Test {
protected:
std::vector<uint8> GetBuf() {
return std::vector<uint8>(kSkipBox, kSkipBox + sizeof(kSkipBox));
}
};
TEST_F(BoxReaderTest, ExpectedOperationTest) {
std::vector<uint8> buf = GetBuf();
bool err;
scoped_ptr<BoxReader> reader(
BoxReader::ReadTopLevelBox(&buf[0], buf.size(), LogCB(), &err));
EXPECT_FALSE(err);
EXPECT_TRUE(reader.get());
SkipBox box;
EXPECT_TRUE(box.Parse(reader.get()));
EXPECT_EQ(0x01, reader->version());
EXPECT_EQ(0x020304u, reader->flags());
EXPECT_EQ(0x05, box.a);
EXPECT_EQ(0x06, box.b);
EXPECT_EQ(0x0708, box.c);
EXPECT_EQ(static_cast<int32>(0xf90a0b0c), box.d);
EXPECT_EQ(static_cast<int32>(0xfd0e0f10), box.e);
EXPECT_EQ(2u, box.kids.size());
EXPECT_EQ(0xdeadbeef, box.kids[0].val);
EXPECT_EQ(0xfacecafe, box.kids[1].val);
// Accounting for the extra byte outside of the box above
EXPECT_EQ(buf.size(), static_cast<uint64>(reader->size() + 1));
}
TEST_F(BoxReaderTest, OuterTooShortTest) {
std::vector<uint8> buf = GetBuf();
bool err;
// Create a soft failure by truncating the outer box.
scoped_ptr<BoxReader> r(
BoxReader::ReadTopLevelBox(&buf[0], buf.size() - 2, LogCB(), &err));
EXPECT_FALSE(err);
EXPECT_FALSE(r.get());
}
TEST_F(BoxReaderTest, InnerTooLongTest) {
std::vector<uint8> buf = GetBuf();
bool err;
// Make an inner box too big for its outer box.
buf[25] = 1;
scoped_ptr<BoxReader> reader(
BoxReader::ReadTopLevelBox(&buf[0], buf.size(), LogCB(), &err));
SkipBox box;
EXPECT_FALSE(box.Parse(reader.get()));
}
TEST_F(BoxReaderTest, WrongFourCCTest) {
std::vector<uint8> buf = GetBuf();
bool err;
// Set an unrecognized top-level FourCC.
buf[5] = 1;
scoped_ptr<BoxReader> reader(
BoxReader::ReadTopLevelBox(&buf[0], buf.size(), LogCB(), &err));
EXPECT_FALSE(reader.get());
EXPECT_TRUE(err);
}
TEST_F(BoxReaderTest, ScanChildrenTest) {
std::vector<uint8> buf = GetBuf();
bool err;
scoped_ptr<BoxReader> reader(
BoxReader::ReadTopLevelBox(&buf[0], buf.size(), LogCB(), &err));
EXPECT_TRUE(reader->SkipBytes(16) && reader->ScanChildren());
FreeBox free;
EXPECT_TRUE(reader->ReadChild(&free));
EXPECT_FALSE(reader->ReadChild(&free));
EXPECT_TRUE(reader->MaybeReadChild(&free));
std::vector<PsshBox> kids;
EXPECT_TRUE(reader->ReadChildren(&kids));
EXPECT_EQ(2u, kids.size());
kids.clear();
EXPECT_FALSE(reader->ReadChildren(&kids));
EXPECT_TRUE(reader->MaybeReadChildren(&kids));
}
TEST_F(BoxReaderTest, ReadAllChildrenTest) {
std::vector<uint8> buf = GetBuf();
// Modify buffer to exclude its last 'free' box
buf[3] = 0x38;
bool err;
scoped_ptr<BoxReader> reader(
BoxReader::ReadTopLevelBox(&buf[0], buf.size(), LogCB(), &err));
std::vector<PsshBox> kids;
EXPECT_TRUE(reader->SkipBytes(16) && reader->ReadAllChildren(&kids));
EXPECT_EQ(2u, kids.size());
EXPECT_EQ(kids[0].val, 0xdeadbeef); // Ensure order is preserved
}
TEST_F(BoxReaderTest, TestSkippingBloc) {
static const uint8 kData[] = {
0x00, 0x00, 0x00, 0x09, 'b', 'l', 'o', 'c', 0x00
};
std::vector<uint8> buf(kData, kData + sizeof(kData));
bool err;
scoped_ptr<BoxReader> reader(
BoxReader::ReadTopLevelBox(&buf[0], buf.size(), LogCB(), &err));
EXPECT_FALSE(err);
EXPECT_TRUE(reader);
EXPECT_EQ(FOURCC_BLOC, reader->type());
}
} // namespace mp4
} // namespace media
<commit_msg>Fix missing virtual keyword in BoxReaderTest.<commit_after>// Copyright (c) 2012 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 <string.h>
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "media/mp4/box_reader.h"
#include "media/mp4/rcheck.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace media {
namespace mp4 {
static const uint8 kSkipBox[] = {
// Top-level test box containing three children
0x00, 0x00, 0x00, 0x40, 's', 'k', 'i', 'p',
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0xf9, 0x0a, 0x0b, 0x0c, 0xfd, 0x0e, 0x0f, 0x10,
// Ordinary (8-byte header) child box
0x00, 0x00, 0x00, 0x0c, 'p', 's', 's', 'h', 0xde, 0xad, 0xbe, 0xef,
// Extended-size header child box
0x00, 0x00, 0x00, 0x01, 'p', 's', 's', 'h',
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14,
0xfa, 0xce, 0xca, 0xfe,
// Empty free box
0x00, 0x00, 0x00, 0x08, 'f', 'r', 'e', 'e',
// Trailing garbage
0x00 };
struct FreeBox : Box {
virtual bool Parse(BoxReader* reader) OVERRIDE {
return true;
}
virtual FourCC BoxType() const OVERRIDE { return FOURCC_FREE; }
};
struct PsshBox : Box {
uint32 val;
virtual bool Parse(BoxReader* reader) OVERRIDE {
return reader->Read4(&val);
}
virtual FourCC BoxType() const OVERRIDE { return FOURCC_PSSH; }
};
struct SkipBox : Box {
uint8 a, b;
uint16 c;
int32 d;
int64 e;
std::vector<PsshBox> kids;
FreeBox mpty;
virtual bool Parse(BoxReader* reader) OVERRIDE {
RCHECK(reader->ReadFullBoxHeader() &&
reader->Read1(&a) &&
reader->Read1(&b) &&
reader->Read2(&c) &&
reader->Read4s(&d) &&
reader->Read4sInto8s(&e));
return reader->ScanChildren() &&
reader->ReadChildren(&kids) &&
reader->MaybeReadChild(&mpty);
}
virtual FourCC BoxType() const OVERRIDE { return FOURCC_SKIP; }
SkipBox();
virtual ~SkipBox();
};
SkipBox::SkipBox() {}
SkipBox::~SkipBox() {}
class BoxReaderTest : public testing::Test {
protected:
std::vector<uint8> GetBuf() {
return std::vector<uint8>(kSkipBox, kSkipBox + sizeof(kSkipBox));
}
};
TEST_F(BoxReaderTest, ExpectedOperationTest) {
std::vector<uint8> buf = GetBuf();
bool err;
scoped_ptr<BoxReader> reader(
BoxReader::ReadTopLevelBox(&buf[0], buf.size(), LogCB(), &err));
EXPECT_FALSE(err);
EXPECT_TRUE(reader.get());
SkipBox box;
EXPECT_TRUE(box.Parse(reader.get()));
EXPECT_EQ(0x01, reader->version());
EXPECT_EQ(0x020304u, reader->flags());
EXPECT_EQ(0x05, box.a);
EXPECT_EQ(0x06, box.b);
EXPECT_EQ(0x0708, box.c);
EXPECT_EQ(static_cast<int32>(0xf90a0b0c), box.d);
EXPECT_EQ(static_cast<int32>(0xfd0e0f10), box.e);
EXPECT_EQ(2u, box.kids.size());
EXPECT_EQ(0xdeadbeef, box.kids[0].val);
EXPECT_EQ(0xfacecafe, box.kids[1].val);
// Accounting for the extra byte outside of the box above
EXPECT_EQ(buf.size(), static_cast<uint64>(reader->size() + 1));
}
TEST_F(BoxReaderTest, OuterTooShortTest) {
std::vector<uint8> buf = GetBuf();
bool err;
// Create a soft failure by truncating the outer box.
scoped_ptr<BoxReader> r(
BoxReader::ReadTopLevelBox(&buf[0], buf.size() - 2, LogCB(), &err));
EXPECT_FALSE(err);
EXPECT_FALSE(r.get());
}
TEST_F(BoxReaderTest, InnerTooLongTest) {
std::vector<uint8> buf = GetBuf();
bool err;
// Make an inner box too big for its outer box.
buf[25] = 1;
scoped_ptr<BoxReader> reader(
BoxReader::ReadTopLevelBox(&buf[0], buf.size(), LogCB(), &err));
SkipBox box;
EXPECT_FALSE(box.Parse(reader.get()));
}
TEST_F(BoxReaderTest, WrongFourCCTest) {
std::vector<uint8> buf = GetBuf();
bool err;
// Set an unrecognized top-level FourCC.
buf[5] = 1;
scoped_ptr<BoxReader> reader(
BoxReader::ReadTopLevelBox(&buf[0], buf.size(), LogCB(), &err));
EXPECT_FALSE(reader.get());
EXPECT_TRUE(err);
}
TEST_F(BoxReaderTest, ScanChildrenTest) {
std::vector<uint8> buf = GetBuf();
bool err;
scoped_ptr<BoxReader> reader(
BoxReader::ReadTopLevelBox(&buf[0], buf.size(), LogCB(), &err));
EXPECT_TRUE(reader->SkipBytes(16) && reader->ScanChildren());
FreeBox free;
EXPECT_TRUE(reader->ReadChild(&free));
EXPECT_FALSE(reader->ReadChild(&free));
EXPECT_TRUE(reader->MaybeReadChild(&free));
std::vector<PsshBox> kids;
EXPECT_TRUE(reader->ReadChildren(&kids));
EXPECT_EQ(2u, kids.size());
kids.clear();
EXPECT_FALSE(reader->ReadChildren(&kids));
EXPECT_TRUE(reader->MaybeReadChildren(&kids));
}
TEST_F(BoxReaderTest, ReadAllChildrenTest) {
std::vector<uint8> buf = GetBuf();
// Modify buffer to exclude its last 'free' box
buf[3] = 0x38;
bool err;
scoped_ptr<BoxReader> reader(
BoxReader::ReadTopLevelBox(&buf[0], buf.size(), LogCB(), &err));
std::vector<PsshBox> kids;
EXPECT_TRUE(reader->SkipBytes(16) && reader->ReadAllChildren(&kids));
EXPECT_EQ(2u, kids.size());
EXPECT_EQ(kids[0].val, 0xdeadbeef); // Ensure order is preserved
}
TEST_F(BoxReaderTest, TestSkippingBloc) {
static const uint8 kData[] = {
0x00, 0x00, 0x00, 0x09, 'b', 'l', 'o', 'c', 0x00
};
std::vector<uint8> buf(kData, kData + sizeof(kData));
bool err;
scoped_ptr<BoxReader> reader(
BoxReader::ReadTopLevelBox(&buf[0], buf.size(), LogCB(), &err));
EXPECT_FALSE(err);
EXPECT_TRUE(reader);
EXPECT_EQ(FOURCC_BLOC, reader->type());
}
} // namespace mp4
} // namespace media
<|endoftext|> |
<commit_before>// apt_signs.cxx -- build airport signs on the fly
//
// Written by Curtis Olson, started July 2001.
//
// Copyright (C) 2001 Curtis L. Olson - http://www.flightgear.org/~curt
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// $Id$
#ifdef HAVE_CONFIG_H
# include <simgear_config.h>
#endif
#include <vector>
#include <simgear/debug/logstream.hxx>
#include <simgear/math/sg_types.hxx>
#include <simgear/scene/tgdb/leaf.hxx>
#include <simgear/scene/material/mat.hxx>
#include <simgear/scene/material/matlib.hxx>
#include "apt_signs.hxx"
#define SIGN "OBJECT_SIGN: "
#define RWY "OBJECT_RUNWAY_SIGN: "
SG_USING_STD(vector);
// for temporary storage of sign elements
struct element_info {
element_info(SGMaterial *m, ssgSimpleState *s, SGMaterialGlyph *g, double h)
: material(m), state(s), glyph(g), height(h)
{
scale = h * m->get_xsize()
/ (m->get_ysize() < 0.001 ? 1.0 : m->get_ysize());
}
SGMaterial *material;
ssgSimpleState *state;
SGMaterialGlyph *glyph;
double height;
double scale;
};
// standard panel height sizes
const double HT[5] = {0.460, 0.610, 0.760, 1.220, 0.760};
// translation table for "command" to "glyph name"
struct pair {
const char *keyword;
const char *glyph_name;
} cmds[] = {
{"@u", "up"},
{"@d", "down"},
{"@l", "left"},
{"@lu", "left-up"},
{"@ul", "left-up"},
{"@ld", "left-down"},
{"@dl", "left-down"},
{"@r", "right"},
{"@ru", "right-up"},
{"@ur", "right-up"},
{"@rd", "right-down"},
{"@dr", "right-down"},
{0, 0},
};
// see $FG_ROOT/Docs/README.scenery
//
ssgBranch *sgMakeSign(SGMaterialLib *matlib, const string path, const string content)
{
double sign_height = 1.0; // meter
bool lighted = true;
string newmat = "BlackSign";
vector<element_info *> elements;
element_info *close = 0;
double total_width = 0.0;
bool cmd = false;
int size = -1;
char oldtype = 0, newtype = 0;
ssgBranch *object = new ssgBranch();
object->setName((char *)content.c_str());
SGMaterial *material;
ssgSimpleState *lighted_state;
ssgSimpleState *unlighted_state;
// Part I: parse & measure
for (const char *s = content.data(); *s; s++) {
string name;
string value;
if (*s == '{') {
if (cmd)
SG_LOG(SG_TERRAIN, SG_ALERT, SIGN "unexpected { in sign contents");
cmd = true;
continue;
} else if (*s == '}') {
if (!cmd)
SG_LOG(SG_TERRAIN, SG_ALERT, SIGN "unexpected } in sign contents");
cmd = false;
continue;
} else if (!cmd) {
name = *s;
} else {
if (*s == ',')
continue;
for (; *s; s++) {
name += *s;
if (s[1] == ',' || s[1] == '}' || s[1] == '=')
break;
}
if (!*s) {
SG_LOG(SG_TERRAIN, SG_ALERT, SIGN "unclosed { in sign contents");
} else if (s[1] == '=') {
for (s += 2; *s; s++) {
value += *s;
if (s[1] == ',' || s[1] == '}')
break;
}
if (!*s)
SG_LOG(SG_TERRAIN, SG_ALERT, SIGN "unclosed { in sign contents");
}
if (name == "@size") {
sign_height = strtod(value.data(), 0);
continue;
}
if (name == "@light") {
lighted = (value != "0" && value != "no" && value != "off" && value != "false");
continue;
}
if (name == "@material") {
newmat = value.data();
continue;
} else if (name.size() == 2 || name.size() == 3) {
string n = name;
if (n.size() == 3 && n[2] >= '1' && n[2] <= '5') {
size = n[2] - '1';
n = n.substr(0, 2);
}
if (n == "@Y") {
if (size < 3) {
sign_height = HT[size < 0 ? 2 : size];
newmat = "YellowSign";
newtype = 'Y';
continue;
}
} else if (n == "@R") {
if (size < 3) {
sign_height = HT[size < 0 ? 2 : size];
newmat = "RedSign";
newtype = 'R';
continue;
}
} else if (n == "@L") {
if (size < 3) {
sign_height = HT[size < 0 ? 2 : size];
newmat = "FramedSign";
newtype = 'L';
continue;
}
} else if (n == "@B") {
if (size < 0 || size == 3 || size == 4) {
sign_height = HT[size < 0 ? 3 : size];
newmat = "BlackSign";
newtype = 'B';
continue;
}
}
}
for (int i = 0; cmds[i].keyword; i++) {
if (name == cmds[i].keyword) {
name = cmds[i].glyph_name;
break;
}
}
if (name[0] == '@') {
SG_LOG(SG_TERRAIN, SG_ALERT, SIGN "ignoring unknown command `" << name << '\'');
continue;
}
}
if (newmat.size()) {
material = matlib->find(newmat);
if (!material) {
SG_LOG(SG_TERRAIN, SG_ALERT, SIGN "ignoring unknown material `" << newmat << '\'');
continue;
}
// set material states (lighted & unlighted)
lighted_state = material->get_state();
string u = newmat + ".unlighted";
SGMaterial *m = matlib->find(u);
if (m) {
unlighted_state = (ssgSimpleState *)m->get_state()->clone(SSG_CLONE_STATE);
unlighted_state->setTexture(lighted_state->getTexture());
} else {
SG_LOG(SG_TERRAIN, SG_ALERT, SIGN "ignoring unknown material `" << u << '\'');
unlighted_state = lighted_state;
}
newmat = "";
}
SGMaterialGlyph *glyph = material->get_glyph(name);
if (!glyph) {
SG_LOG( SG_TERRAIN, SG_ALERT, SIGN "unsupported glyph `" << *s << '\'');
continue;
}
// in managed mode push frame stop and frame start first
ssgSimpleState *state = lighted ? lighted_state : unlighted_state;
element_info *e;
if (newtype && newtype != oldtype) {
if (close) {
elements.push_back(close);
total_width += close->glyph->get_width() * close->scale;
close = 0;
}
oldtype = newtype;
SGMaterialGlyph *g = material->get_glyph("stop-frame");
if (g)
close = new element_info(material, state, g, sign_height);
g = material->get_glyph("start-frame");
if (g) {
e = new element_info(material, state, g, sign_height);
elements.push_back(e);
total_width += e->glyph->get_width() * e->scale;
}
}
// now the actually requested glyph
e = new element_info(material, state, glyph, sign_height);
elements.push_back(e);
total_width += e->glyph->get_width() * e->scale;
}
// in managed mode close frame
if (close) {
elements.push_back(close);
total_width += close->glyph->get_width() * close->scale;
close = 0;
}
// Part II: typeset
double hpos = -total_width / 2;
const double dist = 0.25; // hard-code distance from surface for now
sgVec3 normal;
sgSetVec3(normal, 0, -1, 0);
sgVec4 color;
sgSetVec4(color, 1.0, 1.0, 1.0, 1.0);
for (unsigned int i = 0; i < elements.size(); i++) {
element_info *element = elements[i];
double xoffset = element->glyph->get_left();
double height = element->height;
double width = element->glyph->get_width();
double abswidth = width * element->scale;
// vertices
ssgVertexArray *vl = new ssgVertexArray(4);
vl->add(0, hpos, dist);
vl->add(0, hpos + abswidth, dist);
vl->add(0, hpos, dist + height);
vl->add(0, hpos + abswidth, dist + height);
// texture coordinates
ssgTexCoordArray *tl = new ssgTexCoordArray(4);
tl->add(xoffset, 0);
tl->add(xoffset + width, 0);
tl->add(xoffset, 1);
tl->add(xoffset + width, 1);
// normals
ssgNormalArray *nl = new ssgNormalArray(1);
nl->add(normal);
// colors
ssgColourArray *cl = new ssgColourArray(1);
cl->add(color);
ssgLeaf *leaf = new ssgVtxTable(GL_TRIANGLE_STRIP, vl, nl, tl, cl);
leaf->setState(element->state);
object->addKid(leaf);
hpos += abswidth;
delete element;
}
// minimalistic backside
ssgVertexArray *vl = new ssgVertexArray(4);
vl->add(0, hpos, dist);
vl->add(0, hpos - total_width, dist);
vl->add(0, hpos, dist + sign_height);
vl->add(0, hpos - total_width, dist + sign_height);
ssgNormalArray *nl = new ssgNormalArray(1);
nl->add(0, 1, 0);
ssgLeaf *leaf = new ssgVtxTable(GL_TRIANGLE_STRIP, vl, nl, 0, 0);
SGMaterial *mat = matlib->find("BlackSign");
if (mat)
leaf->setState(mat->get_state());
object->addKid(leaf);
return object;
}
ssgBranch *sgMakeRunwaySign( SGMaterialLib *matlib,
const string path, const string name )
{
// for demo purposes we assume each element (letter) is 1x1 meter.
// Sign is placed 0.25 meters above the ground
ssgBranch *object = new ssgBranch();
object->setName( (char *)name.c_str() );
double width = name.length() / 3.0;
string material = name;
point_list nodes;
point_list normals;
point_list texcoords;
int_list vertex_index;
int_list normal_index;
int_list tex_index;
nodes.push_back( Point3D( -width, 0, 0.25 ) );
nodes.push_back( Point3D( width + 1, 0, 0.25 ) );
nodes.push_back( Point3D( -width, 0, 1.25 ) );
nodes.push_back( Point3D( width + 1, 0, 1.25 ) );
normals.push_back( Point3D( 0, -1, 0 ) );
texcoords.push_back( Point3D( 0, 0, 0 ) );
texcoords.push_back( Point3D( 1, 0, 0 ) );
texcoords.push_back( Point3D( 0, 1, 0 ) );
texcoords.push_back( Point3D( 1, 1, 0 ) );
vertex_index.push_back( 0 );
vertex_index.push_back( 1 );
vertex_index.push_back( 2 );
vertex_index.push_back( 3 );
normal_index.push_back( 0 );
normal_index.push_back( 0 );
normal_index.push_back( 0 );
normal_index.push_back( 0 );
tex_index.push_back( 0 );
tex_index.push_back( 1 );
tex_index.push_back( 2 );
tex_index.push_back( 3 );
ssgLeaf *leaf = sgMakeLeaf( path, GL_TRIANGLE_STRIP, matlib, material,
nodes, normals, texcoords,
vertex_index, normal_index, tex_index,
false, NULL );
object->addKid( leaf );
return object;
}
<commit_msg>thanks to Erik's texture map I can now drop empty.rgb altogether and just specify the same texture in the "foo.lighted" and "foo.unlighted" material entry. This also allows to drop the state cloning and thereby solves the most urgent apt_signs.cxx TODO. :-)<commit_after>// apt_signs.cxx -- build airport signs on the fly
//
// Written by Curtis Olson, started July 2001.
//
// Copyright (C) 2001 Curtis L. Olson - http://www.flightgear.org/~curt
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// $Id$
#ifdef HAVE_CONFIG_H
# include <simgear_config.h>
#endif
#include <vector>
#include <simgear/debug/logstream.hxx>
#include <simgear/math/sg_types.hxx>
#include <simgear/scene/tgdb/leaf.hxx>
#include <simgear/scene/material/mat.hxx>
#include <simgear/scene/material/matlib.hxx>
#include "apt_signs.hxx"
#define SIGN "OBJECT_SIGN: "
#define RWY "OBJECT_RUNWAY_SIGN: "
SG_USING_STD(vector);
// for temporary storage of sign elements
struct element_info {
element_info(SGMaterial *m, ssgSimpleState *s, SGMaterialGlyph *g, double h)
: material(m), state(s), glyph(g), height(h)
{
scale = h * m->get_xsize()
/ (m->get_ysize() < 0.001 ? 1.0 : m->get_ysize());
}
SGMaterial *material;
ssgSimpleState *state;
SGMaterialGlyph *glyph;
double height;
double scale;
};
// standard panel height sizes
const double HT[5] = {0.460, 0.610, 0.760, 1.220, 0.760};
// translation table for "command" to "glyph name"
struct pair {
const char *keyword;
const char *glyph_name;
} cmds[] = {
{"@u", "up"},
{"@d", "down"},
{"@l", "left"},
{"@lu", "left-up"},
{"@ul", "left-up"},
{"@ld", "left-down"},
{"@dl", "left-down"},
{"@r", "right"},
{"@ru", "right-up"},
{"@ur", "right-up"},
{"@rd", "right-down"},
{"@dr", "right-down"},
{0, 0},
};
// see $FG_ROOT/Docs/README.scenery
//
ssgBranch *sgMakeSign(SGMaterialLib *matlib, const string path, const string content)
{
double sign_height = 1.0; // meter
bool lighted = true;
string newmat = "BlackSign";
vector<element_info *> elements;
element_info *close = 0;
double total_width = 0.0;
bool cmd = false;
int size = -1;
char oldtype = 0, newtype = 0;
ssgBranch *object = new ssgBranch();
object->setName((char *)content.c_str());
SGMaterial *material;
ssgSimpleState *lighted_state;
ssgSimpleState *unlighted_state;
// Part I: parse & measure
for (const char *s = content.data(); *s; s++) {
string name;
string value;
if (*s == '{') {
if (cmd)
SG_LOG(SG_TERRAIN, SG_ALERT, SIGN "unexpected { in sign contents");
cmd = true;
continue;
} else if (*s == '}') {
if (!cmd)
SG_LOG(SG_TERRAIN, SG_ALERT, SIGN "unexpected } in sign contents");
cmd = false;
continue;
} else if (!cmd) {
name = *s;
} else {
if (*s == ',')
continue;
for (; *s; s++) {
name += *s;
if (s[1] == ',' || s[1] == '}' || s[1] == '=')
break;
}
if (!*s) {
SG_LOG(SG_TERRAIN, SG_ALERT, SIGN "unclosed { in sign contents");
} else if (s[1] == '=') {
for (s += 2; *s; s++) {
value += *s;
if (s[1] == ',' || s[1] == '}')
break;
}
if (!*s)
SG_LOG(SG_TERRAIN, SG_ALERT, SIGN "unclosed { in sign contents");
}
if (name == "@size") {
sign_height = strtod(value.data(), 0);
continue;
}
if (name == "@light") {
lighted = (value != "0" && value != "no" && value != "off" && value != "false");
continue;
}
if (name == "@material") {
newmat = value.data();
continue;
} else if (name.size() == 2 || name.size() == 3) {
string n = name;
if (n.size() == 3 && n[2] >= '1' && n[2] <= '5') {
size = n[2] - '1';
n = n.substr(0, 2);
}
if (n == "@Y") {
if (size < 3) {
sign_height = HT[size < 0 ? 2 : size];
newmat = "YellowSign";
newtype = 'Y';
continue;
}
} else if (n == "@R") {
if (size < 3) {
sign_height = HT[size < 0 ? 2 : size];
newmat = "RedSign";
newtype = 'R';
continue;
}
} else if (n == "@L") {
if (size < 3) {
sign_height = HT[size < 0 ? 2 : size];
newmat = "FramedSign";
newtype = 'L';
continue;
}
} else if (n == "@B") {
if (size < 0 || size == 3 || size == 4) {
sign_height = HT[size < 0 ? 3 : size];
newmat = "BlackSign";
newtype = 'B';
continue;
}
}
}
for (int i = 0; cmds[i].keyword; i++) {
if (name == cmds[i].keyword) {
name = cmds[i].glyph_name;
break;
}
}
if (name[0] == '@') {
SG_LOG(SG_TERRAIN, SG_ALERT, SIGN "ignoring unknown command `" << name << '\'');
continue;
}
}
if (newmat.size()) {
material = matlib->find(newmat);
if (!material) {
SG_LOG(SG_TERRAIN, SG_ALERT, SIGN "ignoring unknown material `" << newmat << '\'');
continue;
}
// set material states (lighted & unlighted)
lighted_state = material->get_state();
string u = newmat + ".unlighted";
SGMaterial *m = matlib->find(u);
if (m) {
unlighted_state = m->get_state();
} else {
SG_LOG(SG_TERRAIN, SG_ALERT, SIGN "ignoring unknown material `" << u << '\'');
unlighted_state = lighted_state;
}
newmat = "";
}
SGMaterialGlyph *glyph = material->get_glyph(name);
if (!glyph) {
SG_LOG( SG_TERRAIN, SG_ALERT, SIGN "unsupported glyph `" << *s << '\'');
continue;
}
// in managed mode push frame stop and frame start first
ssgSimpleState *state = lighted ? lighted_state : unlighted_state;
element_info *e;
if (newtype && newtype != oldtype) {
if (close) {
elements.push_back(close);
total_width += close->glyph->get_width() * close->scale;
close = 0;
}
oldtype = newtype;
SGMaterialGlyph *g = material->get_glyph("stop-frame");
if (g)
close = new element_info(material, state, g, sign_height);
g = material->get_glyph("start-frame");
if (g) {
e = new element_info(material, state, g, sign_height);
elements.push_back(e);
total_width += e->glyph->get_width() * e->scale;
}
}
// now the actually requested glyph
e = new element_info(material, state, glyph, sign_height);
elements.push_back(e);
total_width += e->glyph->get_width() * e->scale;
}
// in managed mode close frame
if (close) {
elements.push_back(close);
total_width += close->glyph->get_width() * close->scale;
close = 0;
}
// Part II: typeset
double hpos = -total_width / 2;
const double dist = 0.25; // hard-code distance from surface for now
sgVec3 normal;
sgSetVec3(normal, 0, -1, 0);
sgVec4 color;
sgSetVec4(color, 1.0, 1.0, 1.0, 1.0);
for (unsigned int i = 0; i < elements.size(); i++) {
element_info *element = elements[i];
double xoffset = element->glyph->get_left();
double height = element->height;
double width = element->glyph->get_width();
double abswidth = width * element->scale;
// vertices
ssgVertexArray *vl = new ssgVertexArray(4);
vl->add(0, hpos, dist);
vl->add(0, hpos + abswidth, dist);
vl->add(0, hpos, dist + height);
vl->add(0, hpos + abswidth, dist + height);
// texture coordinates
ssgTexCoordArray *tl = new ssgTexCoordArray(4);
tl->add(xoffset, 0);
tl->add(xoffset + width, 0);
tl->add(xoffset, 1);
tl->add(xoffset + width, 1);
// normals
ssgNormalArray *nl = new ssgNormalArray(1);
nl->add(normal);
// colors
ssgColourArray *cl = new ssgColourArray(1);
cl->add(color);
ssgLeaf *leaf = new ssgVtxTable(GL_TRIANGLE_STRIP, vl, nl, tl, cl);
leaf->setState(element->state);
object->addKid(leaf);
hpos += abswidth;
delete element;
}
// minimalistic backside
ssgVertexArray *vl = new ssgVertexArray(4);
vl->add(0, hpos, dist);
vl->add(0, hpos - total_width, dist);
vl->add(0, hpos, dist + sign_height);
vl->add(0, hpos - total_width, dist + sign_height);
ssgNormalArray *nl = new ssgNormalArray(1);
nl->add(0, 1, 0);
ssgLeaf *leaf = new ssgVtxTable(GL_TRIANGLE_STRIP, vl, nl, 0, 0);
SGMaterial *mat = matlib->find("BlackSign");
if (mat)
leaf->setState(mat->get_state());
object->addKid(leaf);
return object;
}
ssgBranch *sgMakeRunwaySign( SGMaterialLib *matlib,
const string path, const string name )
{
// for demo purposes we assume each element (letter) is 1x1 meter.
// Sign is placed 0.25 meters above the ground
ssgBranch *object = new ssgBranch();
object->setName( (char *)name.c_str() );
double width = name.length() / 3.0;
string material = name;
point_list nodes;
point_list normals;
point_list texcoords;
int_list vertex_index;
int_list normal_index;
int_list tex_index;
nodes.push_back( Point3D( -width, 0, 0.25 ) );
nodes.push_back( Point3D( width + 1, 0, 0.25 ) );
nodes.push_back( Point3D( -width, 0, 1.25 ) );
nodes.push_back( Point3D( width + 1, 0, 1.25 ) );
normals.push_back( Point3D( 0, -1, 0 ) );
texcoords.push_back( Point3D( 0, 0, 0 ) );
texcoords.push_back( Point3D( 1, 0, 0 ) );
texcoords.push_back( Point3D( 0, 1, 0 ) );
texcoords.push_back( Point3D( 1, 1, 0 ) );
vertex_index.push_back( 0 );
vertex_index.push_back( 1 );
vertex_index.push_back( 2 );
vertex_index.push_back( 3 );
normal_index.push_back( 0 );
normal_index.push_back( 0 );
normal_index.push_back( 0 );
normal_index.push_back( 0 );
tex_index.push_back( 0 );
tex_index.push_back( 1 );
tex_index.push_back( 2 );
tex_index.push_back( 3 );
ssgLeaf *leaf = sgMakeLeaf( path, GL_TRIANGLE_STRIP, matlib, material,
nodes, normals, texcoords,
vertex_index, normal_index, tex_index,
false, NULL );
object->addKid( leaf );
return object;
}
<|endoftext|> |
<commit_before>#include "drape/vertex_array_buffer.hpp"
#include "drape/glfunctions.hpp"
#include "drape/glextensions_list.hpp"
#include "drape/index_storage.hpp"
#include "drape/support_manager.hpp"
#include "base/stl_add.hpp"
#include "base/assert.hpp"
namespace dp
{
VertexArrayBuffer::VertexArrayBuffer(uint32_t indexBufferSize, uint32_t dataBufferSize)
: m_VAO(0)
, m_dataBufferSize(dataBufferSize)
, m_program()
, m_isPreflushed(false)
, m_moveToGpuOnBuild(false)
, m_isChanged(false)
{
m_indexBuffer = make_unique_dp<IndexBuffer>(indexBufferSize);
// Adreno 200 GPUs aren't able to share OpenGL resources between 2 OGL-contexts correctly,
// so we have to create and destroy VBO on one context.
m_moveToGpuOnBuild = SupportManager::Instance().IsAdreno200Device();
}
VertexArrayBuffer::~VertexArrayBuffer()
{
m_indexBuffer.reset();
m_staticBuffers.clear();
m_dynamicBuffers.clear();
if (m_VAO != 0)
{
/// Build called only when VertexArrayBuffer fulled and transfer to FrontendRenderer
/// but if user move screen before all geometry readed from MWM we delete VertexArrayBuffer on BackendRenderer
/// in this case m_VAO will be equal a 0
/// also m_VAO == 0 will be on device that not support OES_vertex_array_object extension
GLFunctions::glDeleteVertexArray(m_VAO);
}
}
void VertexArrayBuffer::Preflush()
{
if (!m_moveToGpuOnBuild)
PreflushImpl();
}
void VertexArrayBuffer::PreflushImpl()
{
ASSERT(!m_isPreflushed, ());
// Buffers are ready, so moving them from CPU to GPU.
for(auto & buffer : m_staticBuffers)
buffer.second->MoveToGPU(GPUBuffer::ElementBuffer);
for(auto & buffer : m_dynamicBuffers)
buffer.second->MoveToGPU(GPUBuffer::ElementBuffer);
ASSERT(m_indexBuffer != nullptr, ());
m_indexBuffer->MoveToGPU(GPUBuffer::IndexBuffer);
GLFunctions::glBindBuffer(0, gl_const::GLElementArrayBuffer);
GLFunctions::glBindBuffer(0, gl_const::GLArrayBuffer);
m_isPreflushed = true;
}
void VertexArrayBuffer::Render()
{
RenderRange(IndicesRange(0, GetIndexBuffer()->GetCurrentSize()));
}
void VertexArrayBuffer::RenderRange(IndicesRange const & range)
{
if (!(m_staticBuffers.empty() && m_dynamicBuffers.empty()) && GetIndexCount() > 0)
{
ASSERT(m_program != nullptr, ("Somebody not call Build. It's very bad. Very very bad"));
/// if OES_vertex_array_object is supported than all bindings already saved in VAO
/// and we need only bind VAO.
if (GLExtensionsList::Instance().IsSupported(GLExtensionsList::VertexArrayObject))
Bind();
else
BindStaticBuffers();
BindDynamicBuffers();
GetIndexBuffer()->Bind();
GLFunctions::glDrawElements(dp::IndexStorage::SizeOfIndex(), range.m_idxCount, range.m_idxStart);
}
}
void VertexArrayBuffer::Build(ref_ptr<GpuProgram> program)
{
if (m_moveToGpuOnBuild && !m_isPreflushed)
PreflushImpl();
if (m_VAO != 0 && m_program == program)
return;
m_program = program;
/// if OES_vertex_array_object not supported, than buffers will be bind on each Render call
if (!GLExtensionsList::Instance().IsSupported(GLExtensionsList::VertexArrayObject))
return;
if (m_staticBuffers.empty())
return;
if (m_VAO != 0)
GLFunctions::glDeleteVertexArray(m_VAO);
m_VAO = GLFunctions::glGenVertexArray();
Bind();
BindStaticBuffers();
}
void VertexArrayBuffer::UploadData(BindingInfo const & bindingInfo, void const * data, uint32_t count)
{
ref_ptr<DataBuffer> buffer;
if (!bindingInfo.IsDynamic())
buffer = GetOrCreateStaticBuffer(bindingInfo);
else
buffer = GetOrCreateDynamicBuffer(bindingInfo);
if (count > 0)
m_isChanged = true;
buffer->GetBuffer()->UploadData(data, count);
}
ref_ptr<DataBuffer> VertexArrayBuffer::GetOrCreateDynamicBuffer(BindingInfo const & bindingInfo)
{
return GetOrCreateBuffer(bindingInfo, true);
}
ref_ptr<DataBuffer> VertexArrayBuffer::GetDynamicBuffer(BindingInfo const & bindingInfo) const
{
return GetBuffer(bindingInfo, true);
}
ref_ptr<DataBuffer> VertexArrayBuffer::GetOrCreateStaticBuffer(BindingInfo const & bindingInfo)
{
return GetOrCreateBuffer(bindingInfo, false);
}
ref_ptr<DataBuffer> VertexArrayBuffer::GetBuffer(BindingInfo const & bindingInfo, bool isDynamic) const
{
TBuffersMap const * buffers = nullptr;
if (isDynamic)
buffers = &m_dynamicBuffers;
else
buffers = &m_staticBuffers;
TBuffersMap::const_iterator it = buffers->find(bindingInfo);
if (it == buffers->end())
return nullptr;
return make_ref(it->second);
}
ref_ptr<DataBuffer> VertexArrayBuffer::GetOrCreateBuffer(BindingInfo const & bindingInfo, bool isDynamic)
{
TBuffersMap * buffers = nullptr;
if (isDynamic)
buffers = &m_dynamicBuffers;
else
buffers = &m_staticBuffers;
TBuffersMap::iterator it = buffers->find(bindingInfo);
if (it == buffers->end())
{
drape_ptr<DataBuffer> dataBuffer = make_unique_dp<DataBuffer>(bindingInfo.GetElementSize(), m_dataBufferSize);
ref_ptr<DataBuffer> result = make_ref(dataBuffer);
(*buffers).insert(make_pair(bindingInfo, move(dataBuffer)));
return result;
}
return make_ref(it->second);
}
uint32_t VertexArrayBuffer::GetAvailableIndexCount() const
{
return GetIndexBuffer()->GetAvailableSize();
}
uint32_t VertexArrayBuffer::GetAvailableVertexCount() const
{
if (m_staticBuffers.empty())
return m_dataBufferSize;
#ifdef DEBUG
TBuffersMap::const_iterator it = m_staticBuffers.begin();
uint32_t prev = it->second->GetBuffer()->GetAvailableSize();
for (; it != m_staticBuffers.end(); ++it)
ASSERT_EQUAL(prev, it->second->GetBuffer()->GetAvailableSize(), ());
#endif
return m_staticBuffers.begin()->second->GetBuffer()->GetAvailableSize();
}
uint32_t VertexArrayBuffer::GetStartIndexValue() const
{
if (m_staticBuffers.empty())
return 0;
#ifdef DEBUG
TBuffersMap::const_iterator it = m_staticBuffers.begin();
uint32_t prev = it->second->GetBuffer()->GetCurrentSize();
for (; it != m_staticBuffers.end(); ++it)
ASSERT(prev == it->second->GetBuffer()->GetCurrentSize(), ());
#endif
return m_staticBuffers.begin()->second->GetBuffer()->GetCurrentSize();
}
uint32_t VertexArrayBuffer::GetDynamicBufferOffset(BindingInfo const & bindingInfo)
{
return GetOrCreateDynamicBuffer(bindingInfo)->GetBuffer()->GetCurrentSize();
}
uint32_t VertexArrayBuffer::GetIndexCount() const
{
return GetIndexBuffer()->GetCurrentSize();
}
void VertexArrayBuffer::UploadIndexes(void const * data, uint32_t count)
{
ASSERT(count <= GetIndexBuffer()->GetAvailableSize(), ());
GetIndexBuffer()->UploadData(data, count);
}
void VertexArrayBuffer::ApplyMutation(ref_ptr<IndexBufferMutator> indexMutator,
ref_ptr<AttributeBufferMutator> attrMutator)
{
/// If OES_vertex_array_object is supported than we need to bind current VAO before call glBindBuffer,
/// otherwise we could affect previously binded VAO.
if (GLExtensionsList::Instance().IsSupported(GLExtensionsList::VertexArrayObject))
Bind();
if (indexMutator != nullptr)
{
ASSERT(m_indexBuffer != nullptr, ());
if (indexMutator->GetCapacity() > m_indexBuffer->GetBuffer()->GetCapacity())
{
m_indexBuffer = make_unique_dp<IndexBuffer>(indexMutator->GetCapacity());
m_indexBuffer->MoveToGPU(GPUBuffer::IndexBuffer);
}
m_indexBuffer->UpdateData(indexMutator->GetIndexes(), indexMutator->GetIndexCount());
}
if (attrMutator == nullptr)
return;
typedef AttributeBufferMutator::TMutateData TMutateData;
typedef AttributeBufferMutator::TMutateNodes TMutateNodes;
TMutateData const & data = attrMutator->GetMutateData();
for (TMutateData::const_iterator it = data.begin(); it != data.end(); ++it)
{
ref_ptr<DataBuffer> buffer = GetDynamicBuffer(it->first);
ASSERT(buffer != nullptr, ());
DataBufferMapper mapper(buffer);
TMutateNodes const & nodes = it->second;
for (size_t i = 0; i < nodes.size(); ++i)
{
MutateNode const & node = nodes[i];
ASSERT_GREATER(node.m_region.m_count, 0, ());
mapper.UpdateData(node.m_data.get(), node.m_region.m_offset, node.m_region.m_count);
}
}
}
void VertexArrayBuffer::Bind() const
{
ASSERT(m_VAO != 0, ("You need to call Build method before bind it and render"));
GLFunctions::glBindVertexArray(m_VAO);
}
void VertexArrayBuffer::BindStaticBuffers() const
{
BindBuffers(m_staticBuffers);
}
void VertexArrayBuffer::BindDynamicBuffers() const
{
BindBuffers(m_dynamicBuffers);
}
void VertexArrayBuffer::BindBuffers(TBuffersMap const & buffers) const
{
TBuffersMap::const_iterator it = buffers.begin();
for (; it != buffers.end(); ++it)
{
BindingInfo const & binding = it->first;
ref_ptr<DataBuffer> buffer = make_ref(it->second);
buffer->GetBuffer()->Bind();
for (uint16_t i = 0; i < binding.GetCount(); ++i)
{
BindingDecl const & decl = binding.GetBindingDecl(i);
int8_t attributeLocation = m_program->GetAttributeLocation(decl.m_attributeName);
assert(attributeLocation != -1);
GLFunctions::glEnableVertexAttribute(attributeLocation);
GLFunctions::glVertexAttributePointer(attributeLocation,
decl.m_componentCount,
decl.m_componentType,
false,
decl.m_stride,
decl.m_offset);
}
}
}
ref_ptr<DataBufferBase> VertexArrayBuffer::GetIndexBuffer() const
{
ASSERT(m_indexBuffer != nullptr, ());
return m_indexBuffer->GetBuffer();
}
} // namespace dp
<commit_msg>Review fix.<commit_after>#include "drape/vertex_array_buffer.hpp"
#include "drape/glfunctions.hpp"
#include "drape/glextensions_list.hpp"
#include "drape/index_storage.hpp"
#include "drape/support_manager.hpp"
#include "base/stl_add.hpp"
#include "base/assert.hpp"
namespace dp
{
VertexArrayBuffer::VertexArrayBuffer(uint32_t indexBufferSize, uint32_t dataBufferSize)
: m_VAO(0)
, m_dataBufferSize(dataBufferSize)
, m_program()
, m_isPreflushed(false)
, m_moveToGpuOnBuild(false)
, m_isChanged(false)
{
m_indexBuffer = make_unique_dp<IndexBuffer>(indexBufferSize);
// Adreno 200 GPUs aren't able to share OpenGL resources between 2 OGL-contexts correctly,
// so we have to create and destroy VBO on one context.
m_moveToGpuOnBuild = SupportManager::Instance().IsAdreno200Device();
}
VertexArrayBuffer::~VertexArrayBuffer()
{
m_indexBuffer.reset();
m_staticBuffers.clear();
m_dynamicBuffers.clear();
if (m_VAO != 0)
{
/// Build called only when VertexArrayBuffer fulled and transfer to FrontendRenderer
/// but if user move screen before all geometry readed from MWM we delete VertexArrayBuffer on BackendRenderer
/// in this case m_VAO will be equal a 0
/// also m_VAO == 0 will be on device that not support OES_vertex_array_object extension
GLFunctions::glDeleteVertexArray(m_VAO);
}
}
void VertexArrayBuffer::Preflush()
{
if (!m_moveToGpuOnBuild)
PreflushImpl();
}
void VertexArrayBuffer::PreflushImpl()
{
ASSERT(!m_isPreflushed, ());
// Buffers are ready, so moving them from CPU to GPU.
for(auto & buffer : m_staticBuffers)
buffer.second->MoveToGPU(GPUBuffer::ElementBuffer);
for(auto & buffer : m_dynamicBuffers)
buffer.second->MoveToGPU(GPUBuffer::ElementBuffer);
ASSERT(m_indexBuffer != nullptr, ());
m_indexBuffer->MoveToGPU(GPUBuffer::IndexBuffer);
GLFunctions::glBindBuffer(0, gl_const::GLElementArrayBuffer);
GLFunctions::glBindBuffer(0, gl_const::GLArrayBuffer);
m_isPreflushed = true;
}
void VertexArrayBuffer::Render()
{
RenderRange(IndicesRange(0, GetIndexBuffer()->GetCurrentSize()));
}
void VertexArrayBuffer::RenderRange(IndicesRange const & range)
{
if (!(m_staticBuffers.empty() && m_dynamicBuffers.empty()) && GetIndexCount() > 0)
{
ASSERT(m_program != nullptr, ("Somebody not call Build. It's very bad. Very very bad"));
/// if OES_vertex_array_object is supported than all bindings already saved in VAO
/// and we need only bind VAO.
if (GLExtensionsList::Instance().IsSupported(GLExtensionsList::VertexArrayObject))
Bind();
else
BindStaticBuffers();
BindDynamicBuffers();
GetIndexBuffer()->Bind();
GLFunctions::glDrawElements(dp::IndexStorage::SizeOfIndex(), range.m_idxCount, range.m_idxStart);
}
}
void VertexArrayBuffer::Build(ref_ptr<GpuProgram> program)
{
if (m_moveToGpuOnBuild && !m_isPreflushed)
PreflushImpl();
if (m_VAO != 0 && m_program == program)
return;
m_program = program;
/// if OES_vertex_array_object not supported, than buffers will be bind on each Render call
if (!GLExtensionsList::Instance().IsSupported(GLExtensionsList::VertexArrayObject))
return;
if (m_staticBuffers.empty())
return;
if (m_VAO != 0)
GLFunctions::glDeleteVertexArray(m_VAO);
m_VAO = GLFunctions::glGenVertexArray();
Bind();
BindStaticBuffers();
}
void VertexArrayBuffer::UploadData(BindingInfo const & bindingInfo, void const * data, uint32_t count)
{
ref_ptr<DataBuffer> buffer;
if (!bindingInfo.IsDynamic())
buffer = GetOrCreateStaticBuffer(bindingInfo);
else
buffer = GetOrCreateDynamicBuffer(bindingInfo);
if (count > 0)
m_isChanged = true;
buffer->GetBuffer()->UploadData(data, count);
}
ref_ptr<DataBuffer> VertexArrayBuffer::GetOrCreateDynamicBuffer(BindingInfo const & bindingInfo)
{
return GetOrCreateBuffer(bindingInfo, true);
}
ref_ptr<DataBuffer> VertexArrayBuffer::GetDynamicBuffer(BindingInfo const & bindingInfo) const
{
return GetBuffer(bindingInfo, true);
}
ref_ptr<DataBuffer> VertexArrayBuffer::GetOrCreateStaticBuffer(BindingInfo const & bindingInfo)
{
return GetOrCreateBuffer(bindingInfo, false);
}
ref_ptr<DataBuffer> VertexArrayBuffer::GetBuffer(BindingInfo const & bindingInfo, bool isDynamic) const
{
TBuffersMap const * buffers = nullptr;
if (isDynamic)
buffers = &m_dynamicBuffers;
else
buffers = &m_staticBuffers;
TBuffersMap::const_iterator it = buffers->find(bindingInfo);
if (it == buffers->end())
return nullptr;
return make_ref(it->second);
}
ref_ptr<DataBuffer> VertexArrayBuffer::GetOrCreateBuffer(BindingInfo const & bindingInfo, bool isDynamic)
{
TBuffersMap * buffers = nullptr;
if (isDynamic)
buffers = &m_dynamicBuffers;
else
buffers = &m_staticBuffers;
TBuffersMap::iterator it = buffers->find(bindingInfo);
if (it == buffers->end())
{
drape_ptr<DataBuffer> dataBuffer = make_unique_dp<DataBuffer>(bindingInfo.GetElementSize(), m_dataBufferSize);
ref_ptr<DataBuffer> result = make_ref(dataBuffer);
(*buffers).insert(make_pair(bindingInfo, move(dataBuffer)));
return result;
}
return make_ref(it->second);
}
uint32_t VertexArrayBuffer::GetAvailableIndexCount() const
{
return GetIndexBuffer()->GetAvailableSize();
}
uint32_t VertexArrayBuffer::GetAvailableVertexCount() const
{
if (m_staticBuffers.empty())
return m_dataBufferSize;
#ifdef DEBUG
TBuffersMap::const_iterator it = m_staticBuffers.begin();
uint32_t prev = it->second->GetBuffer()->GetAvailableSize();
for (; it != m_staticBuffers.end(); ++it)
ASSERT_EQUAL(prev, it->second->GetBuffer()->GetAvailableSize(), ());
#endif
return m_staticBuffers.begin()->second->GetBuffer()->GetAvailableSize();
}
uint32_t VertexArrayBuffer::GetStartIndexValue() const
{
if (m_staticBuffers.empty())
return 0;
#ifdef DEBUG
TBuffersMap::const_iterator it = m_staticBuffers.begin();
uint32_t prev = it->second->GetBuffer()->GetCurrentSize();
for (; it != m_staticBuffers.end(); ++it)
ASSERT(prev == it->second->GetBuffer()->GetCurrentSize(), ());
#endif
return m_staticBuffers.begin()->second->GetBuffer()->GetCurrentSize();
}
uint32_t VertexArrayBuffer::GetDynamicBufferOffset(BindingInfo const & bindingInfo)
{
return GetOrCreateDynamicBuffer(bindingInfo)->GetBuffer()->GetCurrentSize();
}
uint32_t VertexArrayBuffer::GetIndexCount() const
{
return GetIndexBuffer()->GetCurrentSize();
}
void VertexArrayBuffer::UploadIndexes(void const * data, uint32_t count)
{
ASSERT(count <= GetIndexBuffer()->GetAvailableSize(), ());
GetIndexBuffer()->UploadData(data, count);
}
void VertexArrayBuffer::ApplyMutation(ref_ptr<IndexBufferMutator> indexMutator,
ref_ptr<AttributeBufferMutator> attrMutator)
{
/// We need to bind current VAO before calling glBindBuffer if OES_vertex_array_object is supported.
/// Otherwise we risk affecting a previously binded VAO.
if (GLExtensionsList::Instance().IsSupported(GLExtensionsList::VertexArrayObject))
Bind();
if (indexMutator != nullptr)
{
ASSERT(m_indexBuffer != nullptr, ());
if (indexMutator->GetCapacity() > m_indexBuffer->GetBuffer()->GetCapacity())
{
m_indexBuffer = make_unique_dp<IndexBuffer>(indexMutator->GetCapacity());
m_indexBuffer->MoveToGPU(GPUBuffer::IndexBuffer);
}
m_indexBuffer->UpdateData(indexMutator->GetIndexes(), indexMutator->GetIndexCount());
}
if (attrMutator == nullptr)
return;
typedef AttributeBufferMutator::TMutateData TMutateData;
typedef AttributeBufferMutator::TMutateNodes TMutateNodes;
TMutateData const & data = attrMutator->GetMutateData();
for (TMutateData::const_iterator it = data.begin(); it != data.end(); ++it)
{
ref_ptr<DataBuffer> buffer = GetDynamicBuffer(it->first);
ASSERT(buffer != nullptr, ());
DataBufferMapper mapper(buffer);
TMutateNodes const & nodes = it->second;
for (size_t i = 0; i < nodes.size(); ++i)
{
MutateNode const & node = nodes[i];
ASSERT_GREATER(node.m_region.m_count, 0, ());
mapper.UpdateData(node.m_data.get(), node.m_region.m_offset, node.m_region.m_count);
}
}
}
void VertexArrayBuffer::Bind() const
{
ASSERT(m_VAO != 0, ("You need to call Build method before bind it and render"));
GLFunctions::glBindVertexArray(m_VAO);
}
void VertexArrayBuffer::BindStaticBuffers() const
{
BindBuffers(m_staticBuffers);
}
void VertexArrayBuffer::BindDynamicBuffers() const
{
BindBuffers(m_dynamicBuffers);
}
void VertexArrayBuffer::BindBuffers(TBuffersMap const & buffers) const
{
TBuffersMap::const_iterator it = buffers.begin();
for (; it != buffers.end(); ++it)
{
BindingInfo const & binding = it->first;
ref_ptr<DataBuffer> buffer = make_ref(it->second);
buffer->GetBuffer()->Bind();
for (uint16_t i = 0; i < binding.GetCount(); ++i)
{
BindingDecl const & decl = binding.GetBindingDecl(i);
int8_t attributeLocation = m_program->GetAttributeLocation(decl.m_attributeName);
assert(attributeLocation != -1);
GLFunctions::glEnableVertexAttribute(attributeLocation);
GLFunctions::glVertexAttributePointer(attributeLocation,
decl.m_componentCount,
decl.m_componentType,
false,
decl.m_stride,
decl.m_offset);
}
}
}
ref_ptr<DataBufferBase> VertexArrayBuffer::GetIndexBuffer() const
{
ASSERT(m_indexBuffer != nullptr, ());
return m_indexBuffer->GetBuffer();
}
} // namespace dp
<|endoftext|> |
<commit_before>#include "simdjson/jsonstream.h"
#include "simdjson/isadetection.h"
#include <map>
using namespace simdjson;
void find_the_best_supported_implementation();
typedef int (*stage1_functype)(const char *buf, size_t len, ParsedJson &pj, bool streaming);
typedef int (*stage2_functype)(const char *buf, size_t len, ParsedJson &pj, size_t &next_json);
stage1_functype best_stage1;
stage2_functype best_stage2;
JsonStream::JsonStream(const char *buf, size_t len, size_t batchSize)
: _buf(buf), _len(len), _batch_size(batchSize) {
find_the_best_supported_implementation();
}
void JsonStream::set_new_buffer(const char *buf, size_t len) {
this->_buf = buf;
this->_len = len;
_batch_size = 0;
_batch_size = 0;
next_json = 0;
current_buffer_loc = 0;
n_parsed_docs = 0;
error_on_last_attempt= false;
load_next_batch = true;
}
int JsonStream::json_parse(ParsedJson &pj) {
if (pj.byte_capacity == 0) {
const bool allocok = pj.allocate_capacity(_batch_size, _batch_size);
const bool allocok_thread = pj_thread.allocate_capacity(_batch_size, _batch_size);
if (!allocok || !allocok_thread) {
std::cerr << "can't allocate memory" << std::endl;
return false;
}
}
else if (pj.byte_capacity < _batch_size) {
return simdjson::CAPACITY;
}
#ifdef SIMDJSON_THREADS_ENABLED
if(current_buffer_loc == last_json_buffer_loc)
load_next_batch = true;
#endif
if (load_next_batch){
#ifdef SIMDJSON_THREADS_ENABLED
//First time loading
if(!stage_1_thread.joinable()){
_buf = &_buf[current_buffer_loc];
_len -= current_buffer_loc;
n_bytes_parsed += current_buffer_loc;
_batch_size = std::min(_batch_size, _len);
int stage1_is_ok = (*best_stage1)(_buf, _batch_size, pj, true);
if (stage1_is_ok != simdjson::SUCCESS) {
pj.error_code = stage1_is_ok;
return pj.error_code;
}
}
//the second thread is running or done.
else{
stage_1_thread.join();
std::swap(pj.structural_indexes, pj_thread.structural_indexes);
pj.n_structural_indexes = pj_thread.n_structural_indexes;
_buf = &_buf[last_json_buffer_loc];
_len -= last_json_buffer_loc;
n_bytes_parsed += last_json_buffer_loc;
last_json_buffer_loc = 0; //because we want to use it in the if above.
}
if(_len-_batch_size > 0) {
last_json_buffer_loc = find_last_json_buf_loc(pj);
_batch_size = std::min(_batch_size, _len - last_json_buffer_loc);
if(_batch_size>0)
stage_1_thread = std::thread(
static_cast<stage1_functype>(*best_stage1),
&_buf[last_json_buffer_loc], _batch_size,
std::ref(pj_thread),
true);
}
#else
_buf = &_buf[current_buffer_loc];
_len -= current_buffer_loc;
n_bytes_parsed += current_buffer_loc;
_batch_size = std::min(_batch_size, _len);
int stage1_is_ok = (*best_stage1)(_buf, _batch_size, pj, true);
if (stage1_is_ok != simdjson::SUCCESS) {
pj.error_code = stage1_is_ok;
return pj.error_code;
}
#endif
load_next_batch = false;
//If we loaded a perfect amount of documents last time, we need to skip the first element,
// because it represents the end of the last document
next_json = next_json == 1;
}
int res = (*best_stage2)(_buf, _len, pj, next_json);
if (res == simdjson::SUCCESS_AND_HAS_MORE) {
error_on_last_attempt = false;
n_parsed_docs++;
//Check if we loaded a perfect amount of json documents and we are done parsing them.
//Since we don't know the position of the next json document yet, point the current_buffer_loc to the end
//of the last loaded document and start parsing at structural_index[1] for the next batch.
// It should point to the start of the first document in the new batch
if(next_json == pj.n_structural_indexes) {
current_buffer_loc = pj.structural_indexes[next_json - 1];
next_json = 1;
load_next_batch = true;
}
else {
current_buffer_loc = pj.structural_indexes[next_json];
}
}
//TODO: have a more precise error check
//Give it two chances for now. We assume the error is because the json was not loaded completely in this batch.
//Load a new batch and if the error persists, it's a genuine error.
else if ( res > 1 && !error_on_last_attempt) {
load_next_batch = true;
error_on_last_attempt = true;
res = json_parse(pj);
}
return res;
}
#ifdef SIMDJSON_THREADS_ENABLED
size_t JsonStream::find_last_json_buf_loc(const ParsedJson &pj) {
auto last_i = pj.n_structural_indexes - 1;
if (pj.structural_indexes[last_i] == _batch_size)
last_i = pj.n_structural_indexes - 2;
auto arr_cnt = 0;
auto obj_cnt = 0;
for (auto i = last_i; i > 0; i--) {
auto idxb = pj.structural_indexes[i];
switch (_buf[idxb]) {
case ':':
case ',':
continue;
case '}':
obj_cnt--;
continue;
case ']':
arr_cnt--;
continue;
case '{':
obj_cnt++;
break;
case '[':
arr_cnt++;
break;
}
auto idxa = pj.structural_indexes[i - 1];
switch (_buf[idxa]) {
case '{':
case '[':
case ':':
case ',':
continue;
}
if (!arr_cnt && !obj_cnt)
return pj.structural_indexes[last_i+1];
return idxb;
}
return 0;
}
#endif
size_t JsonStream::get_current_buffer_loc() const {
return current_buffer_loc;
}
size_t JsonStream::get_n_parsed_docs() const {
return n_parsed_docs;
}
size_t JsonStream::get_n_bytes_parsed() const {
return n_bytes_parsed;
}
//// TODO: generalize this set of functions. We don't want to have a copy in jsonparser.cpp
void find_the_best_supported_implementation() {
uint32_t supports = detect_supported_architectures();
// Order from best to worst (within architecture)
#ifdef IS_X86_64
constexpr uint32_t haswell_flags =
instruction_set::AVX2 | instruction_set::PCLMULQDQ |
instruction_set::BMI1 | instruction_set::BMI2;
constexpr uint32_t westmere_flags =
instruction_set::SSE42 | instruction_set::PCLMULQDQ;
if ((haswell_flags & supports) == haswell_flags) {
best_stage1 = simdjson::find_structural_bits<Architecture ::HASWELL>;
best_stage2 = simdjson::unified_machine<Architecture ::HASWELL>;
return;
}
if ((westmere_flags & supports) == westmere_flags) {
best_stage1 = simdjson::find_structural_bits<Architecture ::WESTMERE>;
best_stage2 = simdjson::unified_machine<Architecture ::WESTMERE>;
return;
}
#endif
#ifdef IS_ARM64
if (instruction_set::NEON) {
best_stage1 = simdjson::find_structural_bits<Architecture ::ARM64>;
best_stage2 = simdjson::unified_machine<Architecture ::ARM64>;
return;
}
#endif
std::cerr << "The processor is not supported by simdjson." << std::endl;
}
<commit_msg>Fix memory allocation of the max_depth in JsonStream.<commit_after>#include "simdjson/jsonstream.h"
#include "simdjson/isadetection.h"
#include <map>
using namespace simdjson;
void find_the_best_supported_implementation();
typedef int (*stage1_functype)(const char *buf, size_t len, ParsedJson &pj, bool streaming);
typedef int (*stage2_functype)(const char *buf, size_t len, ParsedJson &pj, size_t &next_json);
stage1_functype best_stage1;
stage2_functype best_stage2;
JsonStream::JsonStream(const char *buf, size_t len, size_t batchSize)
: _buf(buf), _len(len), _batch_size(batchSize) {
find_the_best_supported_implementation();
}
void JsonStream::set_new_buffer(const char *buf, size_t len) {
this->_buf = buf;
this->_len = len;
_batch_size = 0;
_batch_size = 0;
next_json = 0;
current_buffer_loc = 0;
n_parsed_docs = 0;
error_on_last_attempt= false;
load_next_batch = true;
}
int JsonStream::json_parse(ParsedJson &pj) {
if (pj.byte_capacity == 0) {
const bool allocok = pj.allocate_capacity(_batch_size);
const bool allocok_thread = pj_thread.allocate_capacity(_batch_size);
if (!allocok || !allocok_thread) {
std::cerr << "can't allocate memory" << std::endl;
return false;
}
}
else if (pj.byte_capacity < _batch_size) {
return simdjson::CAPACITY;
}
#ifdef SIMDJSON_THREADS_ENABLED
if(current_buffer_loc == last_json_buffer_loc)
load_next_batch = true;
#endif
if (load_next_batch){
#ifdef SIMDJSON_THREADS_ENABLED
//First time loading
if(!stage_1_thread.joinable()){
_buf = &_buf[current_buffer_loc];
_len -= current_buffer_loc;
n_bytes_parsed += current_buffer_loc;
_batch_size = std::min(_batch_size, _len);
int stage1_is_ok = (*best_stage1)(_buf, _batch_size, pj, true);
if (stage1_is_ok != simdjson::SUCCESS) {
pj.error_code = stage1_is_ok;
return pj.error_code;
}
}
//the second thread is running or done.
else{
stage_1_thread.join();
std::swap(pj.structural_indexes, pj_thread.structural_indexes);
pj.n_structural_indexes = pj_thread.n_structural_indexes;
_buf = &_buf[last_json_buffer_loc];
_len -= last_json_buffer_loc;
n_bytes_parsed += last_json_buffer_loc;
last_json_buffer_loc = 0; //because we want to use it in the if above.
}
if(_len-_batch_size > 0) {
last_json_buffer_loc = find_last_json_buf_loc(pj);
_batch_size = std::min(_batch_size, _len - last_json_buffer_loc);
if(_batch_size>0)
stage_1_thread = std::thread(
static_cast<stage1_functype>(*best_stage1),
&_buf[last_json_buffer_loc], _batch_size,
std::ref(pj_thread),
true);
}
#else
_buf = &_buf[current_buffer_loc];
_len -= current_buffer_loc;
n_bytes_parsed += current_buffer_loc;
_batch_size = std::min(_batch_size, _len);
int stage1_is_ok = (*best_stage1)(_buf, _batch_size, pj, true);
if (stage1_is_ok != simdjson::SUCCESS) {
pj.error_code = stage1_is_ok;
return pj.error_code;
}
#endif
load_next_batch = false;
//If we loaded a perfect amount of documents last time, we need to skip the first element,
// because it represents the end of the last document
next_json = next_json == 1;
}
int res = (*best_stage2)(_buf, _len, pj, next_json);
if (res == simdjson::SUCCESS_AND_HAS_MORE) {
error_on_last_attempt = false;
n_parsed_docs++;
//Check if we loaded a perfect amount of json documents and we are done parsing them.
//Since we don't know the position of the next json document yet, point the current_buffer_loc to the end
//of the last loaded document and start parsing at structural_index[1] for the next batch.
// It should point to the start of the first document in the new batch
if(next_json == pj.n_structural_indexes) {
current_buffer_loc = pj.structural_indexes[next_json - 1];
next_json = 1;
load_next_batch = true;
}
else {
current_buffer_loc = pj.structural_indexes[next_json];
}
}
//TODO: have a more precise error check
//Give it two chances for now. We assume the error is because the json was not loaded completely in this batch.
//Load a new batch and if the error persists, it's a genuine error.
else if ( res > 1 && !error_on_last_attempt) {
load_next_batch = true;
error_on_last_attempt = true;
res = json_parse(pj);
}
return res;
}
#ifdef SIMDJSON_THREADS_ENABLED
size_t JsonStream::find_last_json_buf_loc(const ParsedJson &pj) {
auto last_i = pj.n_structural_indexes - 1;
if (pj.structural_indexes[last_i] == _batch_size)
last_i = pj.n_structural_indexes - 2;
auto arr_cnt = 0;
auto obj_cnt = 0;
for (auto i = last_i; i > 0; i--) {
auto idxb = pj.structural_indexes[i];
switch (_buf[idxb]) {
case ':':
case ',':
continue;
case '}':
obj_cnt--;
continue;
case ']':
arr_cnt--;
continue;
case '{':
obj_cnt++;
break;
case '[':
arr_cnt++;
break;
}
auto idxa = pj.structural_indexes[i - 1];
switch (_buf[idxa]) {
case '{':
case '[':
case ':':
case ',':
continue;
}
if (!arr_cnt && !obj_cnt)
return pj.structural_indexes[last_i+1];
return idxb;
}
return 0;
}
#endif
size_t JsonStream::get_current_buffer_loc() const {
return current_buffer_loc;
}
size_t JsonStream::get_n_parsed_docs() const {
return n_parsed_docs;
}
size_t JsonStream::get_n_bytes_parsed() const {
return n_bytes_parsed;
}
//// TODO: generalize this set of functions. We don't want to have a copy in jsonparser.cpp
void find_the_best_supported_implementation() {
uint32_t supports = detect_supported_architectures();
// Order from best to worst (within architecture)
#ifdef IS_X86_64
constexpr uint32_t haswell_flags =
instruction_set::AVX2 | instruction_set::PCLMULQDQ |
instruction_set::BMI1 | instruction_set::BMI2;
constexpr uint32_t westmere_flags =
instruction_set::SSE42 | instruction_set::PCLMULQDQ;
if ((haswell_flags & supports) == haswell_flags) {
best_stage1 = simdjson::find_structural_bits<Architecture ::HASWELL>;
best_stage2 = simdjson::unified_machine<Architecture ::HASWELL>;
return;
}
if ((westmere_flags & supports) == westmere_flags) {
best_stage1 = simdjson::find_structural_bits<Architecture ::WESTMERE>;
best_stage2 = simdjson::unified_machine<Architecture ::WESTMERE>;
return;
}
#endif
#ifdef IS_ARM64
if (instruction_set::NEON) {
best_stage1 = simdjson::find_structural_bits<Architecture ::ARM64>;
best_stage2 = simdjson::unified_machine<Architecture ::ARM64>;
return;
}
#endif
std::cerr << "The processor is not supported by simdjson." << std::endl;
}
<|endoftext|> |
<commit_before>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/timerfd.h>
#include <fcntl.h>
#include <unistd.h>
#include <sched.h>
#include <stdio.h>
#include <errno.h>
#include <strings.h>
#include <new>
#include <algorithm>
#include "config.hpp"
#include "utils.hpp"
#include "event_queue.hpp"
// TODO: report event queue statistics.
// Some forward declarations
void queue_init_timer(event_queue_t *event_queue, time_t secs);
void queue_stop_timer(event_queue_t *event_queue);
void process_aio_notify(event_queue_t *self) {
int res, nevents;
eventfd_t nevents_total;
res = eventfd_read(self->aio_notify_fd, &nevents_total);
check("Could not read aio_notify_fd value", res != 0);
// Note: O(1) array allocators are hard. To avoid all the
// complexity, we'll use a fixed sized array and call io_getevents
// multiple times if we have to (which should be very unlikely,
// anyway).
io_event events[MAX_IO_EVENT_PROCESSING_BATCH_SIZE];
do {
// Grab the events. Note: we need to make sure we don't read
// more than nevents_total, otherwise we risk reading an io
// event and getting an eventfd for this read event later due
// to the way the kernel is structured. Better avoid this
// complexity (hence std::min below).
nevents = io_getevents(self->aio_context, 0,
std::min((int)nevents_total, MAX_IO_EVENT_PROCESSING_BATCH_SIZE),
events, NULL);
check("Waiting for AIO event failed", nevents < 1);
// Process the events
for(int i = 0; i < nevents; i++) {
if(self->event_handler) {
event_t qevent;
bzero((char*)&qevent, sizeof(qevent));
qevent.event_type = et_disk;
iocb *op = (iocb*)events[i].obj;
qevent.result = events[i].res;
qevent.buf = op->u.c.buf;
qevent.state = (event_state_t*)events[i].data;
if(op->aio_lio_opcode == IO_CMD_PREAD)
qevent.op = eo_read;
else
qevent.op = eo_write;
self->event_handler(self, &qevent);
}
self->alloc.free(events[i].obj);
}
nevents_total -= nevents;
} while(nevents_total > 0);
}
void process_timer_notify(event_queue_t *self) {
int res;
eventfd_t nexpirations;
res = eventfd_read(self->timer_fd, &nexpirations);
check("Could not read timer_fd value", res != 0);
self->total_expirations += nexpirations;
// Internal ops to perform on the timer
if(self->total_expirations % ALLOC_GC_IN_TICKS == 0) {
// Perform allocator gc
self->alloc.gc();
}
// Let queue user handle the event, if they wish
if(self->event_handler) {
event_t qevent;
bzero((char*)&qevent, sizeof(qevent));
qevent.event_type = et_timer;
qevent.state = (event_state_t*)&self->timer_fd;
qevent.result = nexpirations;
qevent.op = eo_read;
self->event_handler(self, &qevent);
}
}
int process_itc_notify(event_queue_t *self) {
int res;
itc_event_t event;
// Read the event
res = read(self->itc_pipe[0], &event, sizeof(event));
check("Could not read itc event", res != sizeof(event));
// Process the event
switch(event.event_type) {
case iet_shutdown:
return 1;
break;
case iet_new_socket:
// The state will be freed within the fsm when the socket is
// closed (or killed for a variety of possible reasons)
fsm_state_t *state = self->alloc.malloc<fsm_state_t>();
fsm_init_state(state);
state->source = event.data;
// TODO: what about when socket is ready to write?
queue_watch_resource(self, event.data, eo_read, state);
printf("Opened socket %d\n", event.data);
break;
}
return 0;
}
void* epoll_handler(void *arg) {
int res;
event_queue_t *self = (event_queue_t*)arg;
epoll_event events[MAX_IO_EVENT_PROCESSING_BATCH_SIZE];
do {
res = epoll_wait(self->epoll_fd, events, MAX_IO_EVENT_PROCESSING_BATCH_SIZE, -1);
// epoll_wait might return with EINTR in some cases (in
// particular under GDB), we just need to retry.
if(res == -1 && errno == EINTR) {
continue;
}
check("Waiting for epoll events failed", res == -1);
// TODO: instead of processing the events immediately, we
// might want to queue them up and then process the queue in
// bursts. This might reduce response time but increase
// overall throughput because it will minimize cache faults
// associated with instructions as well as data structures
// (see section 7 [CPU scheduling] in B-tree Indexes and CPU
// Caches by Goetz Graege and Pre-Ake Larson).
for(int i = 0; i < res; i++) {
resource_t source = ((event_state_t*)events[i].data.ptr)->source;
if(source == self->aio_notify_fd) {
process_aio_notify(self);
continue;
}
if(source == self->timer_fd) {
process_timer_notify(self);
continue;
}
if(source == self->itc_pipe[0]) {
if(process_itc_notify(self)) {
// We're shutting down
return NULL;
}
else {
continue;
}
}
if(events[i].events == EPOLLIN ||
events[i].events == EPOLLOUT)
{
if(self->event_handler) {
event_t qevent;
bzero((char*)&qevent, sizeof(qevent));
qevent.event_type = et_sock;
qevent.state = (event_state_t*)events[i].data.ptr;
if(events[i].events & EPOLLIN)
qevent.op = eo_read;
else
qevent.op = eo_write;
self->event_handler(self, &qevent);
}
} else if(events[i].events == EPOLLRDHUP ||
events[i].events == EPOLLERR ||
events[i].events == EPOLLHUP) {
// TODO: if the connection dies we leak resources
// (memory, etc). We need to establish a state machine
// for each connection. We also might need our own
// timeout before we close the connection.
queue_forget_resource(self, source);
close(source);
} else {
check("epoll_wait came back with an unhandled event", 1);
}
}
} while(1);
return NULL;
}
void create_event_queue(event_queue_t *event_queue, int queue_id, event_handler_t event_handler,
worker_pool_t *parent_pool) {
int res;
event_queue->queue_id = queue_id;
event_queue->event_handler = event_handler;
event_queue->parent_pool = parent_pool;
event_queue->timer_fd = -1;
event_queue->total_expirations = 0;
// Initialize the allocator using placement new
new ((void*)&event_queue->alloc) event_queue_t::small_obj_alloc_t();
// Create aio context
event_queue->aio_context = 0;
res = io_setup(MAX_CONCURRENT_IO_REQUESTS, &event_queue->aio_context);
check("Could not setup aio context", res != 0);
// Create a poll fd
event_queue->epoll_fd = epoll_create1(0);
check("Could not create epoll fd", event_queue->epoll_fd == -1);
// Start the epoll thread
res = pthread_create(&event_queue->epoll_thread, NULL, epoll_handler, (void*)event_queue);
check("Could not create epoll thread", res != 0);
// Create aio notify fd
event_queue->aio_notify_fd = eventfd(0, 0);
check("Could not create aio notification fd", event_queue->aio_notify_fd == -1);
res = fcntl(event_queue->aio_notify_fd, F_SETFL, O_NONBLOCK);
check("Could not make aio notify fd non-blocking", res != 0);
queue_watch_resource(event_queue, event_queue->aio_notify_fd, eo_read, (event_state_t*)&(event_queue->aio_notify_fd));
// Create ITC notify pipe
res = pipe(event_queue->itc_pipe);
check("Could not create itc pipe", res != 0);
res = fcntl(event_queue->itc_pipe[0], F_SETFL, O_NONBLOCK);
check("Could not make itc pipe non-blocking (read end)", res != 0);
res = fcntl(event_queue->itc_pipe[1], F_SETFL, O_NONBLOCK);
check("Could not make itc pipe non-blocking (write end)", res != 0);
queue_watch_resource(event_queue, event_queue->itc_pipe[0], eo_read, (event_state_t*)&(event_queue->itc_pipe[0]));
// Set thread affinity
int ncpus = get_cpu_count();
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(queue_id % ncpus, &mask);
res = pthread_setaffinity_np(event_queue->epoll_thread, sizeof(cpu_set_t), &mask);
check("Could not set thread affinity", res != 0);
// Start the timer
queue_init_timer(event_queue, TIMER_TICKS_IN_SECS);
}
void destroy_event_queue(event_queue_t *event_queue) {
int res;
// Kill the poll thread
itc_event_t event;
event.event_type = iet_shutdown;
post_itc_message(event_queue, &event);
// Wait for the poll thread to die
res = pthread_join(event_queue->epoll_thread, NULL);
check("Could not join with epoll thread", res != 0);
// Stop the timer
queue_stop_timer(event_queue);
// Cleanup resources
res = close(event_queue->epoll_fd);
check("Could not close epoll_fd", res != 0);
res = close(event_queue->itc_pipe[0]);
check("Could not close itc pipe (read end)", res != 0);
res = close(event_queue->itc_pipe[1]);
check("Could not close itc pipe (write end)", res != 0);
res = close(event_queue->aio_notify_fd);
check("Could not close aio_notify_fd", res != 0);
res = io_destroy(event_queue->aio_context);
check("Could not destroy aio_context", res != 0);
(&event_queue->alloc)->~object_static_alloc_t();
}
void queue_watch_resource(event_queue_t *event_queue, resource_t resource,
event_op_t watch_mode, event_state_t *state) {
assert(state);
epoll_event event;
// only trigger if new events come in
event.events = EPOLLET;
if(watch_mode == eo_read)
event.events |= EPOLLIN;
else
event.events |= EPOLLOUT;
event.data.ptr = (void*)state;
int res = epoll_ctl(event_queue->epoll_fd, EPOLL_CTL_ADD, resource, &event);
check("Could not pass socket to worker", res != 0);
}
void queue_forget_resource(event_queue_t *event_queue, resource_t resource) {
epoll_event event;
event.events = EPOLLIN;
event.data.ptr = NULL;
int res = epoll_ctl(event_queue->epoll_fd, EPOLL_CTL_DEL, resource, &event);
check("Could remove socket from watching", res != 0);
}
void queue_init_timer(event_queue_t *event_queue, time_t secs) {
int res = -1;
// Kill the old timer first (if necessary)
if(event_queue->timer_fd != -1) {
queue_stop_timer(event_queue);
}
// Create the timer
event_queue->timer_fd = timerfd_create(CLOCK_MONOTONIC, 0);
check("Could not create timer", event_queue->timer_fd < 0);
// Set the timer_fd to be nonblocking
res = fcntl(event_queue->timer_fd, F_SETFL, O_NONBLOCK);
check("Could not make timer non-blocking", res != 0);
// Arm the timer
itimerspec timer_spec;
bzero(&timer_spec, sizeof(timer_spec));
timer_spec.it_value.tv_sec = secs;
timer_spec.it_value.tv_nsec = 0;
timer_spec.it_interval.tv_sec = secs;
timer_spec.it_interval.tv_nsec = 0;
res = timerfd_settime(event_queue->timer_fd, 0, &timer_spec, NULL);
check("Could not arm the timer.", res != 0);
// Watch the timer
queue_watch_resource(event_queue, event_queue->timer_fd, eo_read, (event_state_t*)&(event_queue->timer_fd));
}
void queue_stop_timer(event_queue_t *event_queue) {
if(event_queue->timer_fd == -1)
return;
// Stop watching the timer
queue_forget_resource(event_queue, event_queue->timer_fd);
int res = -1;
// Disarm the timer (should happen automatically on close, but what the hell)
itimerspec timer_spec;
bzero(&timer_spec, sizeof(timer_spec));
res = timerfd_settime(event_queue->timer_fd, 0, &timer_spec, NULL);
check("Could not disarm the timer.", res != 0);
// Close the timer fd
res = close(event_queue->timer_fd);
check("Could not close the timer.", res != 0);
event_queue->timer_fd = -1;
}
void post_itc_message(event_queue_t *event_queue, itc_event_t *event) {
int res;
// Note: This will be atomic as long as sizeof(itc_event_t) <
// PIPE_BUF
res = write(event_queue->itc_pipe[1], event, sizeof(itc_event_t));
check("Could not post message to itc queue", res != sizeof(itc_event_t));
// TODO: serialization of the whole structure isn't as fast as
// serializing a pointer (but that would involve heap allocation,
// and a thread-safe allocator, which is a whole other can of
// worms). We should revisit this when it's more clear how ITC is
// used.
}
<commit_msg>Some formatting changes<commit_after>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/timerfd.h>
#include <fcntl.h>
#include <unistd.h>
#include <sched.h>
#include <stdio.h>
#include <errno.h>
#include <strings.h>
#include <new>
#include <algorithm>
#include "config.hpp"
#include "utils.hpp"
#include "event_queue.hpp"
// TODO: report event queue statistics.
// Some forward declarations
void queue_init_timer(event_queue_t *event_queue, time_t secs);
void queue_stop_timer(event_queue_t *event_queue);
void process_aio_notify(event_queue_t *self) {
int res, nevents;
eventfd_t nevents_total;
res = eventfd_read(self->aio_notify_fd, &nevents_total);
check("Could not read aio_notify_fd value", res != 0);
// Note: O(1) array allocators are hard. To avoid all the
// complexity, we'll use a fixed sized array and call io_getevents
// multiple times if we have to (which should be very unlikely,
// anyway).
io_event events[MAX_IO_EVENT_PROCESSING_BATCH_SIZE];
do {
// Grab the events. Note: we need to make sure we don't read
// more than nevents_total, otherwise we risk reading an io
// event and getting an eventfd for this read event later due
// to the way the kernel is structured. Better avoid this
// complexity (hence std::min below).
nevents = io_getevents(self->aio_context, 0,
std::min((int)nevents_total, MAX_IO_EVENT_PROCESSING_BATCH_SIZE),
events, NULL);
check("Waiting for AIO event failed", nevents < 1);
// Process the events
for(int i = 0; i < nevents; i++) {
if(self->event_handler) {
event_t qevent;
bzero((char*)&qevent, sizeof(qevent));
qevent.event_type = et_disk;
iocb *op = (iocb*)events[i].obj;
qevent.result = events[i].res;
qevent.buf = op->u.c.buf;
qevent.state = (event_state_t*)events[i].data;
if(op->aio_lio_opcode == IO_CMD_PREAD)
qevent.op = eo_read;
else
qevent.op = eo_write;
self->event_handler(self, &qevent);
}
self->alloc.free(events[i].obj);
}
nevents_total -= nevents;
} while(nevents_total > 0);
}
void process_timer_notify(event_queue_t *self) {
int res;
eventfd_t nexpirations;
res = eventfd_read(self->timer_fd, &nexpirations);
check("Could not read timer_fd value", res != 0);
self->total_expirations += nexpirations;
// Internal ops to perform on the timer
if(self->total_expirations % ALLOC_GC_IN_TICKS == 0) {
// Perform allocator gc
self->alloc.gc();
}
// Let queue user handle the event, if they wish
if(self->event_handler) {
event_t qevent;
bzero((char*)&qevent, sizeof(qevent));
qevent.event_type = et_timer;
qevent.state = (event_state_t*)&self->timer_fd;
qevent.result = nexpirations;
qevent.op = eo_read;
self->event_handler(self, &qevent);
}
}
int process_itc_notify(event_queue_t *self) {
int res;
itc_event_t event;
// Read the event
res = read(self->itc_pipe[0], &event, sizeof(event));
check("Could not read itc event", res != sizeof(event));
// Process the event
switch(event.event_type) {
case iet_shutdown:
return 1;
break;
case iet_new_socket:
// The state will be freed within the fsm when the socket is
// closed (or killed for a variety of possible reasons)
fsm_state_t *state = self->alloc.malloc<fsm_state_t>();
fsm_init_state(state);
state->source = event.data;
// TODO: what about when socket is ready to write?
queue_watch_resource(self, event.data, eo_read, state);
printf("Opened socket %d\n", event.data);
break;
}
return 0;
}
void* epoll_handler(void *arg) {
int res;
event_queue_t *self = (event_queue_t*)arg;
epoll_event events[MAX_IO_EVENT_PROCESSING_BATCH_SIZE];
do {
res = epoll_wait(self->epoll_fd, events, MAX_IO_EVENT_PROCESSING_BATCH_SIZE, -1);
// epoll_wait might return with EINTR in some cases (in
// particular under GDB), we just need to retry.
if(res == -1 && errno == EINTR) {
continue;
}
check("Waiting for epoll events failed", res == -1);
// TODO: instead of processing the events immediately, we
// might want to queue them up and then process the queue in
// bursts. This might reduce response time but increase
// overall throughput because it will minimize cache faults
// associated with instructions as well as data structures
// (see section 7 [CPU scheduling] in B-tree Indexes and CPU
// Caches by Goetz Graege and Pre-Ake Larson).
for(int i = 0; i < res; i++) {
resource_t source = ((event_state_t*)events[i].data.ptr)->source;
if(source == self->aio_notify_fd) {
process_aio_notify(self);
continue;
}
if(source == self->timer_fd) {
process_timer_notify(self);
continue;
}
if(source == self->itc_pipe[0]) {
if(process_itc_notify(self)) {
// We're shutting down
return NULL;
}
else {
continue;
}
}
if(events[i].events == EPOLLIN ||
events[i].events == EPOLLOUT)
{
if(self->event_handler) {
event_t qevent;
bzero((char*)&qevent, sizeof(qevent));
qevent.event_type = et_sock;
qevent.state = (event_state_t*)events[i].data.ptr;
if(events[i].events & EPOLLIN)
qevent.op = eo_read;
else
qevent.op = eo_write;
self->event_handler(self, &qevent);
}
} else if(events[i].events == EPOLLRDHUP ||
events[i].events == EPOLLERR ||
events[i].events == EPOLLHUP) {
// TODO: if the connection dies we leak resources
// (memory, etc). We need to establish a state machine
// for each connection. We also might need our own
// timeout before we close the connection.
queue_forget_resource(self, source);
close(source);
} else {
check("epoll_wait came back with an unhandled event", 1);
}
}
} while(1);
return NULL;
}
void create_event_queue(event_queue_t *event_queue, int queue_id, event_handler_t event_handler,
worker_pool_t *parent_pool) {
int res;
event_queue->queue_id = queue_id;
event_queue->event_handler = event_handler;
event_queue->parent_pool = parent_pool;
event_queue->timer_fd = -1;
event_queue->total_expirations = 0;
// Initialize the allocator using placement new
new ((void*)&event_queue->alloc) event_queue_t::small_obj_alloc_t();
// Create aio context
event_queue->aio_context = 0;
res = io_setup(MAX_CONCURRENT_IO_REQUESTS, &event_queue->aio_context);
check("Could not setup aio context", res != 0);
// Create a poll fd
event_queue->epoll_fd = epoll_create1(0);
check("Could not create epoll fd", event_queue->epoll_fd == -1);
// Start the epoll thread
res = pthread_create(&event_queue->epoll_thread, NULL, epoll_handler, (void*)event_queue);
check("Could not create epoll thread", res != 0);
// Create aio notify fd
event_queue->aio_notify_fd = eventfd(0, 0);
check("Could not create aio notification fd", event_queue->aio_notify_fd == -1);
res = fcntl(event_queue->aio_notify_fd, F_SETFL, O_NONBLOCK);
check("Could not make aio notify fd non-blocking", res != 0);
queue_watch_resource(event_queue, event_queue->aio_notify_fd, eo_read, (event_state_t*)&(event_queue->aio_notify_fd));
// Create ITC notify pipe
res = pipe(event_queue->itc_pipe);
check("Could not create itc pipe", res != 0);
res = fcntl(event_queue->itc_pipe[0], F_SETFL, O_NONBLOCK);
check("Could not make itc pipe non-blocking (read end)", res != 0);
res = fcntl(event_queue->itc_pipe[1], F_SETFL, O_NONBLOCK);
check("Could not make itc pipe non-blocking (write end)", res != 0);
queue_watch_resource(event_queue, event_queue->itc_pipe[0], eo_read, (event_state_t*)&(event_queue->itc_pipe[0]));
// Set thread affinity
int ncpus = get_cpu_count();
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(queue_id % ncpus, &mask);
res = pthread_setaffinity_np(event_queue->epoll_thread, sizeof(cpu_set_t), &mask);
check("Could not set thread affinity", res != 0);
// Start the timer
queue_init_timer(event_queue, TIMER_TICKS_IN_SECS);
}
void destroy_event_queue(event_queue_t *event_queue) {
int res;
// Kill the poll thread
itc_event_t event;
event.event_type = iet_shutdown;
post_itc_message(event_queue, &event);
// Wait for the poll thread to die
res = pthread_join(event_queue->epoll_thread, NULL);
check("Could not join with epoll thread", res != 0);
// Stop the timer
queue_stop_timer(event_queue);
// Cleanup resources
res = close(event_queue->epoll_fd);
check("Could not close epoll_fd", res != 0);
res = close(event_queue->itc_pipe[0]);
check("Could not close itc pipe (read end)", res != 0);
res = close(event_queue->itc_pipe[1]);
check("Could not close itc pipe (write end)", res != 0);
res = close(event_queue->aio_notify_fd);
check("Could not close aio_notify_fd", res != 0);
res = io_destroy(event_queue->aio_context);
check("Could not destroy aio_context", res != 0);
(&event_queue->alloc)->~object_static_alloc_t();
}
void queue_watch_resource(event_queue_t *event_queue, resource_t resource,
event_op_t watch_mode, event_state_t *state) {
assert(state);
epoll_event event;
// only trigger if new events come in
event.events = EPOLLET;
if(watch_mode == eo_read)
event.events |= EPOLLIN;
else
event.events |= EPOLLOUT;
event.data.ptr = (void*)state;
int res = epoll_ctl(event_queue->epoll_fd, EPOLL_CTL_ADD, resource, &event);
check("Could not pass socket to worker", res != 0);
}
void queue_forget_resource(event_queue_t *event_queue, resource_t resource) {
epoll_event event;
event.events = EPOLLIN;
event.data.ptr = NULL;
int res = epoll_ctl(event_queue->epoll_fd, EPOLL_CTL_DEL, resource, &event);
check("Could remove socket from watching", res != 0);
}
void queue_init_timer(event_queue_t *event_queue, time_t secs) {
int res = -1;
// Kill the old timer first (if necessary)
if(event_queue->timer_fd != -1) {
queue_stop_timer(event_queue);
}
// Create the timer
event_queue->timer_fd = timerfd_create(CLOCK_MONOTONIC, 0);
check("Could not create timer", event_queue->timer_fd < 0);
// Set the timer_fd to be nonblocking
res = fcntl(event_queue->timer_fd, F_SETFL, O_NONBLOCK);
check("Could not make timer non-blocking", res != 0);
// Arm the timer
itimerspec timer_spec;
bzero(&timer_spec, sizeof(timer_spec));
timer_spec.it_value.tv_sec = secs;
timer_spec.it_value.tv_nsec = 0;
timer_spec.it_interval.tv_sec = secs;
timer_spec.it_interval.tv_nsec = 0;
res = timerfd_settime(event_queue->timer_fd, 0, &timer_spec, NULL);
check("Could not arm the timer.", res != 0);
// Watch the timer
queue_watch_resource(event_queue, event_queue->timer_fd, eo_read, (event_state_t*)&(event_queue->timer_fd));
}
void queue_stop_timer(event_queue_t *event_queue) {
if(event_queue->timer_fd == -1)
return;
// Stop watching the timer
queue_forget_resource(event_queue, event_queue->timer_fd);
int res = -1;
// Disarm the timer (should happen automatically on close, but what the hell)
itimerspec timer_spec;
bzero(&timer_spec, sizeof(timer_spec));
res = timerfd_settime(event_queue->timer_fd, 0, &timer_spec, NULL);
check("Could not disarm the timer.", res != 0);
// Close the timer fd
res = close(event_queue->timer_fd);
check("Could not close the timer.", res != 0);
event_queue->timer_fd = -1;
}
void post_itc_message(event_queue_t *event_queue, itc_event_t *event) {
int res;
// Note: This will be atomic as long as sizeof(itc_event_t) <
// PIPE_BUF
res = write(event_queue->itc_pipe[1], event, sizeof(itc_event_t));
check("Could not post message to itc queue", res != sizeof(itc_event_t));
// TODO: serialization of the whole structure isn't as fast as
// serializing a pointer (but that would involve heap allocation,
// and a thread-safe allocator, which is a whole other can of
// worms). We should revisit this when it's more clear how ITC is
// used.
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include "loader.h"
#define MAX_RX_SENSE_ERROR 23 /* Maximum number of cycles by which the detection of a start bit could be off (as affected by the Loader code) */
// Offset (in bytes) from end of Loader Image pointing to where most host-initialized values exist.
// Host-Initialized values are: Initial Bit Time, Final Bit Time, 1.5x Bit Time, Failsafe timeout,
// End of Packet timeout, and ExpectedID. In addition, the image checksum at word 5 needs to be
// updated. All these values need to be updated before the download stream is generated.
// NOTE: DAT block data is always placed before the first Spin method
#define RAW_LOADER_INIT_OFFSET_FROM_END (-(10 * 4) - 8)
// Raw loader image. This is a memory image of a Propeller Application written in PASM that fits into our initial
// download packet. Once started, it assists with the remainder of the download (at a faster speed and with more
// relaxed interstitial timing conducive of Internet Protocol delivery. This memory image isn't used as-is; before
// download, it is first adjusted to contain special values assigned by this host (communication timing and
// synchronization values) and then is translated into an optimized Propeller Download Stream understandable by the
// Propeller ROM-based boot loader.
#include "IP_Loader.h"
double ClockSpeed = 80000000.0;
static uint8_t initCallFrame[] = {0xFF, 0xFF, 0xF9, 0xFF, 0xFF, 0xFF, 0xF9, 0xFF};
static void SetHostInitializedValue(uint8_t *bytes, int offset, int value)
{
for (int i = 0; i < 4; ++i)
bytes[offset + i] = (value >> (i * 8)) & 0xFF;
}
static int32_t getLong(const uint8_t *buf)
{
return (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0];
}
static void setLong(uint8_t *buf, uint32_t value)
{
buf[3] = value >> 24;
buf[2] = value >> 16;
buf[1] = value >> 8;
buf[0] = value;
}
uint8_t *Loader::generateInitialLoaderImage(int packetID, int *pLength)
{
int initAreaOffset = sizeof(rawLoaderImage) + RAW_LOADER_INIT_OFFSET_FROM_END;
uint8_t *loaderImage;
int checksum, i;
// Allocate space for the image
if (!(loaderImage = (uint8_t *)malloc(sizeof(rawLoaderImage))))
return NULL;
// Make a copy of the loader template
memcpy(loaderImage, rawLoaderImage, sizeof(rawLoaderImage));
// Clock mode
//SetHostInitializedValue(loaderImage, initAreaOffset + 0, 0);
// Initial Bit Time.
SetHostInitializedValue(loaderImage, initAreaOffset + 4, (int)trunc(80000000.0 / m_connection->loaderBaudRate() + 0.5));
// Final Bit Time.
SetHostInitializedValue(loaderImage, initAreaOffset + 8, (int)trunc(80000000.0 / m_connection->fastLoaderBaudRate() + 0.5));
// 1.5x Final Bit Time minus maximum start bit sense error.
SetHostInitializedValue(loaderImage, initAreaOffset + 12, (int)trunc(1.5 * ClockSpeed / m_connection->fastLoaderBaudRate() - MAX_RX_SENSE_ERROR + 0.5));
// Failsafe Timeout (seconds-worth of Loader's Receive loop iterations).
SetHostInitializedValue(loaderImage, initAreaOffset + 16, (int)trunc(2.0 * ClockSpeed / (3 * 4) + 0.5));
// EndOfPacket Timeout (2 bytes worth of Loader's Receive loop iterations).
SetHostInitializedValue(loaderImage, initAreaOffset + 20, (int)trunc((2.0 * ClockSpeed / m_connection->fastLoaderBaudRate()) * (10.0 / 12.0) + 0.5));
// PatchLoaderLongValue(RawSize*4+RawLoaderInitOffset + 24, Max(Round(ClockSpeed * SSSHTime), 14));
// PatchLoaderLongValue(RawSize*4+RawLoaderInitOffset + 28, Max(Round(ClockSpeed * SCLHighTime), 14));
// PatchLoaderLongValue(RawSize*4+RawLoaderInitOffset + 32, Max(Round(ClockSpeed * SCLLowTime), 26));
// Minimum EEPROM Start/Stop Condition setup/hold time (400 KHz = 1/0.6 µS); Minimum 14 cycles
//SetHostInitializedValue(loaderImage, initAreaOffset + 24, 14);
// Minimum EEPROM SCL high time (400 KHz = 1/0.6 µS); Minimum 14 cycles
//SetHostInitializedValue(loaderImage, initAreaOffset + 28, 14);
// Minimum EEPROM SCL low time (400 KHz = 1/1.3 µS); Minimum 26 cycles
//SetHostInitializedValue(loaderImage, initAreaOffset + 32, 26);
// First Expected Packet ID; total packet count.
SetHostInitializedValue(loaderImage, initAreaOffset + 36, packetID);
// Recalculate and update checksum so low byte of checksum calculates to 0.
checksum = 0;
loaderImage[5] = 0; // start with a zero checksum
for (i = 0; i < (int)sizeof(rawLoaderImage); ++i)
checksum += loaderImage[i];
for (i = 0; i < (int)sizeof(initCallFrame); ++i)
checksum += initCallFrame[i];
loaderImage[5] = 256 - (checksum & 0xFF);
/* return the loader image */
*pLength = sizeof(rawLoaderImage);
return loaderImage;
}
int Loader::fastLoadFile(const char *file, LoadType loadType)
{
uint8_t *image;
int imageSize;
int sts;
/* make sure the image was loaded into memory */
if (!(image = readFile(file, &imageSize))) {
printf("error: failed to load image '%s'\n", file);
return -1;
}
/* load the file */
sts = fastLoadImage(image, imageSize, loadType);
free(image);
/* return load result */
return sts;
}
int Loader::fastLoadImage(const uint8_t *image, int imageSize, LoadType loadType)
{
uint8_t *loaderImage, response[8];
int loaderImageSize, result, i;
int32_t packetID, checksum;
/* compute the packet ID (number of packets to be sent) */
packetID = (imageSize + m_connection->maxDataSize() - 1) / m_connection->maxDataSize();
/* generate a loader image */
loaderImage = generateInitialLoaderImage(packetID, &loaderImageSize);
if (!loaderImage)
return -1;
/* compute the image checksum */
checksum = 0;
for (i = 0; i < imageSize; ++i)
checksum += image[i];
for (i = 0; i < (int)sizeof(initCallFrame); ++i)
checksum += initCallFrame[i];
/* load the second-stage loader using the propeller ROM protocol */
printf("Loading second-stage loader\n");
result = m_connection->loadImage(loaderImage, loaderImageSize, response, sizeof(response));
free(loaderImage);
if (result != 0)
return -1;
result = getLong(&response[0]);
if (result != packetID) {
printf("error: second-stage loader failed to start - packetID %d, result %d\n", packetID, result);
return -1;
}
/* switch to the final baud rate */
m_connection->setBaudRate(m_connection->fastLoaderBaudRate());
/* open the transparent serial connection that will be used for the second-stage loader */
if (m_connection->connect() != 0) {
printf("error: failed to connect to target\n");
return -1;
}
/* transmit the image */
printf("Loading image"); fflush(stdout);
while (imageSize > 0) {
int size;
if ((size = imageSize) > m_connection->maxDataSize())
size = m_connection->maxDataSize();
putchar('.'); fflush(stdout);
if (transmitPacket(packetID, image, size, &result) != 0) {
printf("error: transmitPacket failed\n");
return -1;
}
if (result != packetID - 1) {
printf("Unexpected result: expected %d, received %d\n", packetID - 1, result);
return -1;
}
imageSize -= size;
image += size;
--packetID;
}
putchar('\n');
/*
When we're doing a download that does not include an EEPROM write, the Packet IDs end up as:
ltVerifyRAM: zero
ltReadyToLaunch: -Checksum
ltLaunchNow: -Checksum - 1
... and when we're doing a download that includes an EEPROM write, the Packet IDs end up as:
ltVerifyRAM: zero
ltProgramEEPROM: -Checksum
ltReadyToLaunch: -Checksum*2
ltLaunchNow: -Checksum*2 - 1
*/
/* transmit the RAM verify packet and verify the checksum */
printf("Verifying RAM\n");
if (transmitPacket(packetID, verifyRAM, sizeof(verifyRAM), &result) != 0) {
printf("error: transmitPacket failed\n");
return -1;
}
if (result != -checksum) {
printf("Checksum error: expected %08x, got %08x\n", -checksum, result);
return -1;
}
packetID = -checksum;
if (loadType & ltDownloadAndProgram) {
printf("Programming EEPROM\n");
if (transmitPacket(packetID, programVerifyEEPROM, sizeof(programVerifyEEPROM), &result, 8000) != 0) {
printf("error: transmitPacket failed\n");
return -1;
}
if (result != -checksum*2) {
printf("EEPROM programming error: expected %08x, got %08x\n", -checksum*2, result);
return -1;
}
packetID = -checksum*2;
}
/* transmit the final launch packets */
printf("Sending readyToLaunch packet\n");
transmitPacket(packetID, readyToLaunch, sizeof(readyToLaunch), &result);
if (result != packetID - 1) {
printf("ReadyToLaunch failed: expected %08x, got %08x\n", packetID - 1, result);
return -1;
}
--packetID;
printf("Sending launchNow packet\n");
if (transmitPacket(packetID, launchNow, sizeof(launchNow), NULL) != 0) {
printf("error: transmitPacket failed\n");
return -1;
}
/* return successfully */
return 0;
}
int Loader::transmitPacket(int id, const uint8_t *payload, int payloadSize, int *pResult, int timeout)
{
int packetSize = 2*sizeof(uint32_t) + payloadSize;
uint8_t *packet, response[8];
int retries, result, cnt;
int32_t tag;
/* build the packet to transmit */
if (!(packet = (uint8_t *)malloc(packetSize)))
return -1;
setLong(&packet[0], id);
memcpy(&packet[8], payload, payloadSize);
/* send the packet */
retries = 3;
while (--retries >= 0) {
/* setup the packet header */
tag = (int32_t)rand();
setLong(&packet[4], tag);
//printf("transmit packet %d\n", id);
m_connection->sendData(packet, packetSize);
/* receive the response */
if (pResult) {
cnt = m_connection->receiveDataExactTimeout(response, sizeof(response), timeout);
result = getLong(&response[0]);
if (cnt == 8 && getLong(&response[4]) == tag && result != id) {
free(packet);
*pResult = result;
return 0;
}
}
/* don't wait for a result */
else {
free(packet);
return 0;
}
}
/* free the packet */
free(packet);
/* return timeout */
printf("error: transmitPacket %d failed\n", id);
return -1;
}
<commit_msg>Add some more debugging output to try to find the loader problems under Windows.<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include "loader.h"
#define MAX_RX_SENSE_ERROR 23 /* Maximum number of cycles by which the detection of a start bit could be off (as affected by the Loader code) */
// Offset (in bytes) from end of Loader Image pointing to where most host-initialized values exist.
// Host-Initialized values are: Initial Bit Time, Final Bit Time, 1.5x Bit Time, Failsafe timeout,
// End of Packet timeout, and ExpectedID. In addition, the image checksum at word 5 needs to be
// updated. All these values need to be updated before the download stream is generated.
// NOTE: DAT block data is always placed before the first Spin method
#define RAW_LOADER_INIT_OFFSET_FROM_END (-(10 * 4) - 8)
// Raw loader image. This is a memory image of a Propeller Application written in PASM that fits into our initial
// download packet. Once started, it assists with the remainder of the download (at a faster speed and with more
// relaxed interstitial timing conducive of Internet Protocol delivery. This memory image isn't used as-is; before
// download, it is first adjusted to contain special values assigned by this host (communication timing and
// synchronization values) and then is translated into an optimized Propeller Download Stream understandable by the
// Propeller ROM-based boot loader.
#include "IP_Loader.h"
double ClockSpeed = 80000000.0;
static uint8_t initCallFrame[] = {0xFF, 0xFF, 0xF9, 0xFF, 0xFF, 0xFF, 0xF9, 0xFF};
static void SetHostInitializedValue(uint8_t *bytes, int offset, int value)
{
for (int i = 0; i < 4; ++i)
bytes[offset + i] = (value >> (i * 8)) & 0xFF;
}
static int32_t getLong(const uint8_t *buf)
{
return (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0];
}
static void setLong(uint8_t *buf, uint32_t value)
{
buf[3] = value >> 24;
buf[2] = value >> 16;
buf[1] = value >> 8;
buf[0] = value;
}
uint8_t *Loader::generateInitialLoaderImage(int packetID, int *pLength)
{
int initAreaOffset = sizeof(rawLoaderImage) + RAW_LOADER_INIT_OFFSET_FROM_END;
uint8_t *loaderImage;
int checksum, i;
// Allocate space for the image
if (!(loaderImage = (uint8_t *)malloc(sizeof(rawLoaderImage))))
return NULL;
// Make a copy of the loader template
memcpy(loaderImage, rawLoaderImage, sizeof(rawLoaderImage));
// Clock mode
//SetHostInitializedValue(loaderImage, initAreaOffset + 0, 0);
// Initial Bit Time.
SetHostInitializedValue(loaderImage, initAreaOffset + 4, (int)trunc(80000000.0 / m_connection->loaderBaudRate() + 0.5));
// Final Bit Time.
SetHostInitializedValue(loaderImage, initAreaOffset + 8, (int)trunc(80000000.0 / m_connection->fastLoaderBaudRate() + 0.5));
// 1.5x Final Bit Time minus maximum start bit sense error.
SetHostInitializedValue(loaderImage, initAreaOffset + 12, (int)trunc(1.5 * ClockSpeed / m_connection->fastLoaderBaudRate() - MAX_RX_SENSE_ERROR + 0.5));
// Failsafe Timeout (seconds-worth of Loader's Receive loop iterations).
SetHostInitializedValue(loaderImage, initAreaOffset + 16, (int)trunc(2.0 * ClockSpeed / (3 * 4) + 0.5));
// EndOfPacket Timeout (2 bytes worth of Loader's Receive loop iterations).
SetHostInitializedValue(loaderImage, initAreaOffset + 20, (int)trunc((2.0 * ClockSpeed / m_connection->fastLoaderBaudRate()) * (10.0 / 12.0) + 0.5));
// PatchLoaderLongValue(RawSize*4+RawLoaderInitOffset + 24, Max(Round(ClockSpeed * SSSHTime), 14));
// PatchLoaderLongValue(RawSize*4+RawLoaderInitOffset + 28, Max(Round(ClockSpeed * SCLHighTime), 14));
// PatchLoaderLongValue(RawSize*4+RawLoaderInitOffset + 32, Max(Round(ClockSpeed * SCLLowTime), 26));
// Minimum EEPROM Start/Stop Condition setup/hold time (400 KHz = 1/0.6 µS); Minimum 14 cycles
//SetHostInitializedValue(loaderImage, initAreaOffset + 24, 14);
// Minimum EEPROM SCL high time (400 KHz = 1/0.6 µS); Minimum 14 cycles
//SetHostInitializedValue(loaderImage, initAreaOffset + 28, 14);
// Minimum EEPROM SCL low time (400 KHz = 1/1.3 µS); Minimum 26 cycles
//SetHostInitializedValue(loaderImage, initAreaOffset + 32, 26);
// First Expected Packet ID; total packet count.
SetHostInitializedValue(loaderImage, initAreaOffset + 36, packetID);
// Recalculate and update checksum so low byte of checksum calculates to 0.
checksum = 0;
loaderImage[5] = 0; // start with a zero checksum
for (i = 0; i < (int)sizeof(rawLoaderImage); ++i)
checksum += loaderImage[i];
for (i = 0; i < (int)sizeof(initCallFrame); ++i)
checksum += initCallFrame[i];
loaderImage[5] = 256 - (checksum & 0xFF);
/* return the loader image */
*pLength = sizeof(rawLoaderImage);
return loaderImage;
}
int Loader::fastLoadFile(const char *file, LoadType loadType)
{
uint8_t *image;
int imageSize;
int sts;
/* make sure the image was loaded into memory */
if (!(image = readFile(file, &imageSize))) {
printf("error: failed to load image '%s'\n", file);
return -1;
}
/* load the file */
sts = fastLoadImage(image, imageSize, loadType);
free(image);
/* return load result */
return sts;
}
int Loader::fastLoadImage(const uint8_t *image, int imageSize, LoadType loadType)
{
uint8_t *loaderImage, response[8];
int loaderImageSize, result, i;
int32_t packetID, checksum;
/* compute the packet ID (number of packets to be sent) */
packetID = (imageSize + m_connection->maxDataSize() - 1) / m_connection->maxDataSize();
/* generate a loader image */
loaderImage = generateInitialLoaderImage(packetID, &loaderImageSize);
if (!loaderImage)
return -1;
/* compute the image checksum */
checksum = 0;
for (i = 0; i < imageSize; ++i)
checksum += image[i];
for (i = 0; i < (int)sizeof(initCallFrame); ++i)
checksum += initCallFrame[i];
/* load the second-stage loader using the propeller ROM protocol */
printf("Loading second-stage loader\n");
result = m_connection->loadImage(loaderImage, loaderImageSize, response, sizeof(response));
free(loaderImage);
if (result != 0)
return -1;
result = getLong(&response[0]);
if (result != packetID) {
printf("error: second-stage loader failed to start - packetID %d, result %d\n", packetID, result);
return -1;
}
/* switch to the final baud rate */
m_connection->setBaudRate(m_connection->fastLoaderBaudRate());
/* open the transparent serial connection that will be used for the second-stage loader */
if (m_connection->connect() != 0) {
printf("error: failed to connect to target\n");
return -1;
}
/* transmit the image */
printf("Loading image"); fflush(stdout);
while (imageSize > 0) {
int size;
if ((size = imageSize) > m_connection->maxDataSize())
size = m_connection->maxDataSize();
putchar('.'); fflush(stdout);
if (transmitPacket(packetID, image, size, &result) != 0) {
printf("error: transmitPacket failed\n");
return -1;
}
if (result != packetID - 1) {
printf("Unexpected result: expected %d, received %d\n", packetID - 1, result);
return -1;
}
imageSize -= size;
image += size;
--packetID;
}
putchar('\n');
/*
When we're doing a download that does not include an EEPROM write, the Packet IDs end up as:
ltVerifyRAM: zero
ltReadyToLaunch: -Checksum
ltLaunchNow: -Checksum - 1
... and when we're doing a download that includes an EEPROM write, the Packet IDs end up as:
ltVerifyRAM: zero
ltProgramEEPROM: -Checksum
ltReadyToLaunch: -Checksum*2
ltLaunchNow: -Checksum*2 - 1
*/
/* transmit the RAM verify packet and verify the checksum */
printf("Verifying RAM\n");
if (transmitPacket(packetID, verifyRAM, sizeof(verifyRAM), &result) != 0) {
printf("error: transmitPacket failed\n");
return -1;
}
if (result != -checksum) {
printf("Checksum error: expected %08x, got %08x\n", -checksum, result);
return -1;
}
packetID = -checksum;
if (loadType & ltDownloadAndProgram) {
printf("Programming EEPROM\n");
if (transmitPacket(packetID, programVerifyEEPROM, sizeof(programVerifyEEPROM), &result, 8000) != 0) {
printf("error: transmitPacket failed\n");
return -1;
}
if (result != -checksum*2) {
printf("EEPROM programming error: expected %08x, got %08x\n", -checksum*2, result);
return -1;
}
packetID = -checksum*2;
}
/* transmit the final launch packets */
printf("Sending readyToLaunch packet\n");
if (transmitPacket(packetID, readyToLaunch, sizeof(readyToLaunch), &result) != 0) {
printf("error: transmitPacket failed\n");
return -1;
}
if (result != packetID - 1) {
printf("ReadyToLaunch failed: expected %08x, got %08x\n", packetID - 1, result);
return -1;
}
--packetID;
printf("Sending launchNow packet\n");
if (transmitPacket(packetID, launchNow, sizeof(launchNow), NULL) != 0) {
printf("error: transmitPacket failed\n");
return -1;
}
/* return successfully */
return 0;
}
int Loader::transmitPacket(int id, const uint8_t *payload, int payloadSize, int *pResult, int timeout)
{
int packetSize = 2*sizeof(uint32_t) + payloadSize;
uint8_t *packet, response[8];
int retries, result;
int32_t tag;
/* build the packet to transmit */
if (!(packet = (uint8_t *)malloc(packetSize)))
return -1;
setLong(&packet[0], id);
memcpy(&packet[8], payload, payloadSize);
/* send the packet */
retries = 3;
while (--retries >= 0) {
/* setup the packet header */
tag = (int32_t)rand();
setLong(&packet[4], tag);
//printf("transmit packet %d\n", id);
if (m_connection->sendData(packet, packetSize) != packetSize) {
printf("error: transmitPacket %d failed - sendData\n", id);
free(packet);
return -1;
}
/* receive the response */
if (pResult) {
if (m_connection->receiveDataExactTimeout(response, sizeof(response), timeout) != sizeof(response)) {
printf("error: transmitPacket %d failed - receiveDataExactTimeout\n", id);
free(packet);
return -1;
}
result = getLong(&response[0]);
if (getLong(&response[4]) == tag && result != id) {
*pResult = result;
free(packet);
return 0;
}
}
/* don't wait for a result */
else {
free(packet);
return 0;
}
printf("transmitPacket - retrying\n");
}
/* free the packet */
free(packet);
/* return timeout */
printf("error: transmitPacket %d failed - timeout\n", id);
return -1;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cr_html.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: vg $ $Date: 2006-09-25 13:26:08 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <fstream>
#include "cr_html.hxx"
#include "xmltree.hxx"
#include "../support/syshelp.hxx"
char C_sHtmlFileHeader1[] =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\n"
"<HTML>\n"
"<HEAD>\n"
" <TITLE>";
char C_sHtmlFileHeader2[] =
"</TITLE>\n"
" <META NAME=\"GENERATOR\" CONTENT=\"xml2cmp\">\n"
"</HEAD>\n"
"<BODY BGCOLOR=\"#ffffff\">\n<P><BR></P>";
char C_sHtmlFileFoot[] = "</BODY>\n</HTML>\n";
HtmlCreator::HtmlCreator( const char * i_pOutputFileName,
const XmlElement & i_rDocument,
const Simstr & i_sIDL_BaseDirectory )
: aFile(i_pOutputFileName, std::ios::out
#ifdef WNT
| std::ios::binary
#endif
),
rDocument(i_rDocument),
sIdl_BaseDirectory(i_sIDL_BaseDirectory)
{
if ( !aFile )
{
std::cerr << "Error: " << i_pOutputFileName << " could not be created." << std::endl;
exit(0);
}
}
HtmlCreator::~HtmlCreator()
{
aFile.close();
}
void
HtmlCreator::Run()
{
WriteStr( C_sHtmlFileHeader1 );
WriteStr( "ModuleDescription" );
WriteStr( C_sHtmlFileHeader2 );
rDocument.Write2Html(*this);
WriteStr( "<P><BR><BR></P>\n" );
WriteStr( C_sHtmlFileFoot );
}
void
HtmlCreator::StartTable()
{
WriteStr( "<P><BR></P>\n" );
WriteStr(
"<TABLE WIDTH=95% BORDER=1 CELLSPACING=0 CELLPADDING=4>\n"
" <TBODY>\n" );
}
void
HtmlCreator::FinishTable()
{
WriteStr( " </TBODY>\n"
"</TABLE>\n\n" );
}
void
HtmlCreator::StartBigCell( const char * i_sTitle )
{
WriteStr( "<TR><TD COLSPAN=2>\n"
"<H4><BR>" );
WriteStr( i_sTitle );
WriteStr( "</H4>\n" );
}
void
HtmlCreator::FinishBigCell()
{
WriteStr( "</TD><TR>\n" );
}
void
HtmlCreator::Write_SglTextElement( const SglTextElement & i_rElement,
bool i_bStrong )
{
StartRow();
WriteElementName( i_rElement.Name(), i_bStrong );
StartCell( "77%");
if (i_bStrong)
{
WriteStr( "<H4><A NAME=\"" );
unsigned nLen = strlen(i_rElement.Data());
if ( i_rElement.IsReversedName())
{
const char * pEnd = strchr(i_rElement.Data(), ' ');
nLen = (unsigned)( pEnd - i_rElement.Data() );
}
aFile.write( i_rElement.Data(), (int) nLen );
WriteStr( "\">" );
}
WriteName( aFile, sIdl_BaseDirectory, i_rElement.Data(),
i_bStrong ? lt_nolink : i_rElement.LinkType() );
if (i_bStrong)
WriteStr( "</A></H4>" );
FinishCell();
FinishRow();
}
void
HtmlCreator::Write_MultiTextElement( const MultipleTextElement & i_rElement )
{
StartRow();
WriteElementName( i_rElement.Name(), false );
StartCell( "77%");
unsigned i_max = i_rElement.Size();
for ( unsigned i = 0; i < i_max; ++i )
{
if (i > 0)
WriteStr( "<BR>\n" );
WriteName( aFile, sIdl_BaseDirectory, i_rElement.Data(i), i_rElement.LinkType() );
} // end for
FinishCell();
FinishRow();
}
void
HtmlCreator::Write_SglText( const Simstr & i_sName,
const Simstr & i_sValue )
{
StartRow();
WriteElementName( i_sName, false );
StartCell( "77%");
WriteStr( i_sValue );
FinishCell();
FinishRow();
}
void
HtmlCreator::Write_ReferenceDocu( const Simstr & i_sName,
const Simstr & i_sRef,
const Simstr & i_sRole,
const Simstr & i_sTitle )
{
StartRow();
StartCell( "23%" );
WriteStr(i_sName);
FinishCell();
StartCell( "77%" );
if ( !i_sRef.is_empty() )
{
WriteStr("<A href=\"");
WriteStr(i_sRef);
WriteStr("\">");
if ( !i_sTitle.is_empty() )
WriteStr( i_sTitle );
else
WriteStr(i_sRef);
WriteStr("</A><BR>\n");
}
else if ( !i_sTitle.is_empty() )
{
WriteStr("Title: ");
WriteStr( i_sTitle );
WriteStr("<BR>\n");
}
if ( !i_sRole.is_empty() )
{
WriteStr("Role: ");
WriteStr( i_sRole );
}
FinishCell();
FinishRow();
}
void
HtmlCreator::PrintH1( const char * i_pText)
{
static const char sH1a[] = "<H1 ALIGN=CENTER>";
static const char sH1e[] = "</H1>";
WriteStr(sH1a);
WriteStr(i_pText);
WriteStr(sH1e);
}
void
HtmlCreator::StartRow()
{
WriteStr( " <TR VALIGN=TOP>\n" );
}
void
HtmlCreator::FinishRow()
{
WriteStr( " </TR>\n" );
}
void
HtmlCreator::StartCell( const char * i_pWidth)
{
WriteStr( " <TD WIDTH=" );
WriteStr( i_pWidth );
WriteStr( ">\n <P>" );
}
void
HtmlCreator::FinishCell()
{
WriteStr( "</P>\n </TD>\n" );
}
void
HtmlCreator::WriteElementName( const Simstr & i_sName,
bool i_bStrong )
{
StartCell( "23%" );
if (i_bStrong)
WriteStr( "<H4>" );
WriteStr(i_sName);
if (i_bStrong)
WriteStr( "</H4>" );
FinishCell();
}
<commit_msg>INTEGRATION: CWS os2port02 (1.9.20); FILE MERGED 2007/10/04 19:45:26 ydario 1.9.20.1: Issue number: i82034 Submitted by: ydario Reviewed by: ydario Commit of changes for OS/2 CWS source code integration.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cr_html.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2007-11-02 12:56:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <fstream>
#include "cr_html.hxx"
#include "xmltree.hxx"
#include "../support/syshelp.hxx"
char C_sHtmlFileHeader1[] =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\n"
"<HTML>\n"
"<HEAD>\n"
" <TITLE>";
char C_sHtmlFileHeader2[] =
"</TITLE>\n"
" <META NAME=\"GENERATOR\" CONTENT=\"xml2cmp\">\n"
"</HEAD>\n"
"<BODY BGCOLOR=\"#ffffff\">\n<P><BR></P>";
char C_sHtmlFileFoot[] = "</BODY>\n</HTML>\n";
HtmlCreator::HtmlCreator( const char * i_pOutputFileName,
const XmlElement & i_rDocument,
const Simstr & i_sIDL_BaseDirectory )
: aFile(i_pOutputFileName, std::ios::out
#if defined(WNT) || defined(OS2)
| std::ios::binary
#endif
),
rDocument(i_rDocument),
sIdl_BaseDirectory(i_sIDL_BaseDirectory)
{
if ( !aFile )
{
std::cerr << "Error: " << i_pOutputFileName << " could not be created." << std::endl;
exit(0);
}
}
HtmlCreator::~HtmlCreator()
{
aFile.close();
}
void
HtmlCreator::Run()
{
WriteStr( C_sHtmlFileHeader1 );
WriteStr( "ModuleDescription" );
WriteStr( C_sHtmlFileHeader2 );
rDocument.Write2Html(*this);
WriteStr( "<P><BR><BR></P>\n" );
WriteStr( C_sHtmlFileFoot );
}
void
HtmlCreator::StartTable()
{
WriteStr( "<P><BR></P>\n" );
WriteStr(
"<TABLE WIDTH=95% BORDER=1 CELLSPACING=0 CELLPADDING=4>\n"
" <TBODY>\n" );
}
void
HtmlCreator::FinishTable()
{
WriteStr( " </TBODY>\n"
"</TABLE>\n\n" );
}
void
HtmlCreator::StartBigCell( const char * i_sTitle )
{
WriteStr( "<TR><TD COLSPAN=2>\n"
"<H4><BR>" );
WriteStr( i_sTitle );
WriteStr( "</H4>\n" );
}
void
HtmlCreator::FinishBigCell()
{
WriteStr( "</TD><TR>\n" );
}
void
HtmlCreator::Write_SglTextElement( const SglTextElement & i_rElement,
bool i_bStrong )
{
StartRow();
WriteElementName( i_rElement.Name(), i_bStrong );
StartCell( "77%");
if (i_bStrong)
{
WriteStr( "<H4><A NAME=\"" );
unsigned nLen = strlen(i_rElement.Data());
if ( i_rElement.IsReversedName())
{
const char * pEnd = strchr(i_rElement.Data(), ' ');
nLen = (unsigned)( pEnd - i_rElement.Data() );
}
aFile.write( i_rElement.Data(), (int) nLen );
WriteStr( "\">" );
}
WriteName( aFile, sIdl_BaseDirectory, i_rElement.Data(),
i_bStrong ? lt_nolink : i_rElement.LinkType() );
if (i_bStrong)
WriteStr( "</A></H4>" );
FinishCell();
FinishRow();
}
void
HtmlCreator::Write_MultiTextElement( const MultipleTextElement & i_rElement )
{
StartRow();
WriteElementName( i_rElement.Name(), false );
StartCell( "77%");
unsigned i_max = i_rElement.Size();
for ( unsigned i = 0; i < i_max; ++i )
{
if (i > 0)
WriteStr( "<BR>\n" );
WriteName( aFile, sIdl_BaseDirectory, i_rElement.Data(i), i_rElement.LinkType() );
} // end for
FinishCell();
FinishRow();
}
void
HtmlCreator::Write_SglText( const Simstr & i_sName,
const Simstr & i_sValue )
{
StartRow();
WriteElementName( i_sName, false );
StartCell( "77%");
WriteStr( i_sValue );
FinishCell();
FinishRow();
}
void
HtmlCreator::Write_ReferenceDocu( const Simstr & i_sName,
const Simstr & i_sRef,
const Simstr & i_sRole,
const Simstr & i_sTitle )
{
StartRow();
StartCell( "23%" );
WriteStr(i_sName);
FinishCell();
StartCell( "77%" );
if ( !i_sRef.is_empty() )
{
WriteStr("<A href=\"");
WriteStr(i_sRef);
WriteStr("\">");
if ( !i_sTitle.is_empty() )
WriteStr( i_sTitle );
else
WriteStr(i_sRef);
WriteStr("</A><BR>\n");
}
else if ( !i_sTitle.is_empty() )
{
WriteStr("Title: ");
WriteStr( i_sTitle );
WriteStr("<BR>\n");
}
if ( !i_sRole.is_empty() )
{
WriteStr("Role: ");
WriteStr( i_sRole );
}
FinishCell();
FinishRow();
}
void
HtmlCreator::PrintH1( const char * i_pText)
{
static const char sH1a[] = "<H1 ALIGN=CENTER>";
static const char sH1e[] = "</H1>";
WriteStr(sH1a);
WriteStr(i_pText);
WriteStr(sH1e);
}
void
HtmlCreator::StartRow()
{
WriteStr( " <TR VALIGN=TOP>\n" );
}
void
HtmlCreator::FinishRow()
{
WriteStr( " </TR>\n" );
}
void
HtmlCreator::StartCell( const char * i_pWidth)
{
WriteStr( " <TD WIDTH=" );
WriteStr( i_pWidth );
WriteStr( ">\n <P>" );
}
void
HtmlCreator::FinishCell()
{
WriteStr( "</P>\n </TD>\n" );
}
void
HtmlCreator::WriteElementName( const Simstr & i_sName,
bool i_bStrong )
{
StartCell( "23%" );
if (i_bStrong)
WriteStr( "<H4>" );
WriteStr(i_sName);
if (i_bStrong)
WriteStr( "</H4>" );
FinishCell();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ximpgrp.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: hr $ $Date: 2006-06-19 18:14:30 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLOFF_XMLNMSPE_HXX
#include"xmlnmspe.hxx"
#endif
#ifndef _XIMPGROUP_HXX
#include "ximpgrp.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XIMPSHAPE_HXX
#include "ximpshap.hxx"
#endif
#ifndef _XMLOFF_EVENTIMP_HXX
#include "eventimp.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_EVENT_LISTENERS;
using ::xmloff::token::XML_GLUE_POINT;
//////////////////////////////////////////////////////////////////////////////
TYPEINIT1( SdXMLGroupShapeContext, SvXMLImportContext );
SdXMLGroupShapeContext::SdXMLGroupShapeContext(
SvXMLImport& rImport,
USHORT nPrfx, const OUString& rLocalName,
const uno::Reference< xml::sax::XAttributeList>& xAttrList,
uno::Reference< drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape)
: SdXMLShapeContext( rImport, nPrfx, rLocalName, xAttrList, rShapes, bTemporaryShape )
{
}
//////////////////////////////////////////////////////////////////////////////
SdXMLGroupShapeContext::~SdXMLGroupShapeContext()
{
}
//////////////////////////////////////////////////////////////////////////////
SvXMLImportContext* SdXMLGroupShapeContext::CreateChildContext( USHORT nPrefix,
const OUString& rLocalName,
const uno::Reference< xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext* pContext = 0L;
if( nPrefix == XML_NAMESPACE_OFFICE && IsXMLToken( rLocalName, XML_EVENT_LISTENERS ) )
{
pContext = new SdXMLEventsContext( GetImport(), nPrefix, rLocalName, xAttrList, mxShape );
}
else if( nPrefix == XML_NAMESPACE_DRAW && IsXMLToken( rLocalName, XML_GLUE_POINT ) )
{
addGluePoint( xAttrList );
}
else
{
// call GroupChildContext function at common ShapeImport
pContext = GetImport().GetShapeImport()->CreateGroupChildContext(
GetImport(), nPrefix, rLocalName, xAttrList, mxChilds);
}
// call parent when no own context was created
if(!pContext)
pContext = SvXMLImportContext::CreateChildContext(
nPrefix, rLocalName, xAttrList);
return pContext;
}
//////////////////////////////////////////////////////////////////////////////
void SdXMLGroupShapeContext::StartElement(const uno::Reference< xml::sax::XAttributeList>&)
{
// create new group shape and add it to rShapes, use it
// as base for the new group import
AddShape( "com.sun.star.drawing.GroupShape" );
if(mxShape.is())
{
SetStyle( false );
mxChilds = uno::Reference< drawing::XShapes >::query( mxShape );
if( mxChilds.is() )
GetImport().GetShapeImport()->pushGroupForSorting( mxChilds );
}
GetImport().GetShapeImport()->finishShape( mxShape, mxAttrList, mxShapes );
}
//////////////////////////////////////////////////////////////////////////////
void SdXMLGroupShapeContext::EndElement()
{
if( mxChilds.is() )
GetImport().GetShapeImport()->popGroupAndSort();
SdXMLShapeContext::EndElement();
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.15.34); FILE MERGED 2006/09/01 17:59:37 kaib 1.15.34.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ximpgrp.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: obo $ $Date: 2006-09-17 10:31:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _XMLOFF_XMLNMSPE_HXX
#include"xmlnmspe.hxx"
#endif
#ifndef _XIMPGROUP_HXX
#include "ximpgrp.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XIMPSHAPE_HXX
#include "ximpshap.hxx"
#endif
#ifndef _XMLOFF_EVENTIMP_HXX
#include "eventimp.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_EVENT_LISTENERS;
using ::xmloff::token::XML_GLUE_POINT;
//////////////////////////////////////////////////////////////////////////////
TYPEINIT1( SdXMLGroupShapeContext, SvXMLImportContext );
SdXMLGroupShapeContext::SdXMLGroupShapeContext(
SvXMLImport& rImport,
USHORT nPrfx, const OUString& rLocalName,
const uno::Reference< xml::sax::XAttributeList>& xAttrList,
uno::Reference< drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape)
: SdXMLShapeContext( rImport, nPrfx, rLocalName, xAttrList, rShapes, bTemporaryShape )
{
}
//////////////////////////////////////////////////////////////////////////////
SdXMLGroupShapeContext::~SdXMLGroupShapeContext()
{
}
//////////////////////////////////////////////////////////////////////////////
SvXMLImportContext* SdXMLGroupShapeContext::CreateChildContext( USHORT nPrefix,
const OUString& rLocalName,
const uno::Reference< xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext* pContext = 0L;
if( nPrefix == XML_NAMESPACE_OFFICE && IsXMLToken( rLocalName, XML_EVENT_LISTENERS ) )
{
pContext = new SdXMLEventsContext( GetImport(), nPrefix, rLocalName, xAttrList, mxShape );
}
else if( nPrefix == XML_NAMESPACE_DRAW && IsXMLToken( rLocalName, XML_GLUE_POINT ) )
{
addGluePoint( xAttrList );
}
else
{
// call GroupChildContext function at common ShapeImport
pContext = GetImport().GetShapeImport()->CreateGroupChildContext(
GetImport(), nPrefix, rLocalName, xAttrList, mxChilds);
}
// call parent when no own context was created
if(!pContext)
pContext = SvXMLImportContext::CreateChildContext(
nPrefix, rLocalName, xAttrList);
return pContext;
}
//////////////////////////////////////////////////////////////////////////////
void SdXMLGroupShapeContext::StartElement(const uno::Reference< xml::sax::XAttributeList>&)
{
// create new group shape and add it to rShapes, use it
// as base for the new group import
AddShape( "com.sun.star.drawing.GroupShape" );
if(mxShape.is())
{
SetStyle( false );
mxChilds = uno::Reference< drawing::XShapes >::query( mxShape );
if( mxChilds.is() )
GetImport().GetShapeImport()->pushGroupForSorting( mxChilds );
}
GetImport().GetShapeImport()->finishShape( mxShape, mxAttrList, mxShapes );
}
//////////////////////////////////////////////////////////////////////////////
void SdXMLGroupShapeContext::EndElement()
{
if( mxChilds.is() )
GetImport().GetShapeImport()->popGroupAndSort();
SdXMLShapeContext::EndElement();
}
<|endoftext|> |
<commit_before>#include "Schematic.hpp"
namespace Slic3r {
Schematic::Schematic()
{
this->rootOffset = new Pointf3(0, 0, 0);
this->filename = "Default file";
}
Schematic::~Schematic()
{
}
void Schematic::addElectronicPart(ElectronicPart* part)
{
this->partlist.push_back(part);
std::cout << "is visible from c: " << part->isVisible() << std::endl;
}
ElectronicPart* Schematic::addElectronicPart(std::string name, std::string library, std::string deviceset, std::string device, std::string package)
{
addElectronicPart(new ElectronicPart(name, library, deviceset, device, package));
return this->partlist.back();
}
void Schematic::addElectronicNet(ElectronicNet* net)
{
this->netlist.push_back(net);
}
ElectronicParts* Schematic::getPartlist()
{
return &this->partlist;
}
void Schematic::setRootOffset(Pointf3 offset)
{
delete this->rootOffset;
this->rootOffset = new Pointf3(offset.x, offset.y, offset.z);
}
Pointf3 Schematic::getRootOffset()
{
return *(this->rootOffset);
}
void Schematic::setFilename(std::string filename)
{
this->filename = filename;
}
}
<commit_msg>removed debug comment<commit_after>#include "Schematic.hpp"
namespace Slic3r {
Schematic::Schematic()
{
this->rootOffset = new Pointf3(0, 0, 0);
this->filename = "Default file";
}
Schematic::~Schematic()
{
}
void Schematic::addElectronicPart(ElectronicPart* part)
{
this->partlist.push_back(part);
}
ElectronicPart* Schematic::addElectronicPart(std::string name, std::string library, std::string deviceset, std::string device, std::string package)
{
addElectronicPart(new ElectronicPart(name, library, deviceset, device, package));
return this->partlist.back();
}
void Schematic::addElectronicNet(ElectronicNet* net)
{
this->netlist.push_back(net);
}
ElectronicParts* Schematic::getPartlist()
{
return &this->partlist;
}
void Schematic::setRootOffset(Pointf3 offset)
{
delete this->rootOffset;
this->rootOffset = new Pointf3(offset.x, offset.y, offset.z);
}
Pointf3 Schematic::getRootOffset()
{
return *(this->rootOffset);
}
void Schematic::setFilename(std::string filename)
{
this->filename = filename;
}
}
<|endoftext|> |
<commit_before>#include "Serial.hpp"
#include <algorithm>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#if _WIN32
#include <Windows.h>
#include <Setupapi.h>
#include <initguid.h>
#include <devguid.h>
// Undefine min/max macros incompatible with the standard library
// For example, std::numeric_limits<std::streamsize>::max()
// produces some weird errors
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
#include "boost/nowide/convert.hpp"
#pragma comment(lib, "user32.lib")
#elif __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#include <CoreFoundation/CFString.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/serial/IOSerialKeys.h>
#include <IOKit/serial/ioss.h>
#include <sys/syslimits.h>
#endif
namespace Slic3r {
namespace Utils {
static bool looks_like_printer(const std::string &friendly_name)
{
return friendly_name.find("Original Prusa") != std::string::npos;
}
std::vector<SerialPortInfo> scan_serial_ports_extended()
{
std::vector<SerialPortInfo> output;
#ifdef _WIN32
SP_DEVINFO_DATA devInfoData = { 0 };
devInfoData.cbSize = sizeof(devInfoData);
// Get the tree containing the info for the ports.
HDEVINFO hDeviceInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_PORTS, 0, nullptr, DIGCF_PRESENT);
if (hDeviceInfo != INVALID_HANDLE_VALUE) {
// Iterate over all the devices in the tree.
for (int nDevice = 0; SetupDiEnumDeviceInfo(hDeviceInfo, nDevice, &devInfoData); ++ nDevice) {
SerialPortInfo port_info;
// Get the registry key which stores the ports settings.
HKEY hDeviceKey = SetupDiOpenDevRegKey(hDeviceInfo, &devInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE);
if (hDeviceKey) {
// Read in the name of the port.
wchar_t pszPortName[4096];
DWORD dwSize = sizeof(pszPortName);
DWORD dwType = 0;
if (RegQueryValueEx(hDeviceKey, L"PortName", NULL, &dwType, (LPBYTE)pszPortName, &dwSize) == ERROR_SUCCESS)
port_info.port = boost::nowide::narrow(pszPortName);
RegCloseKey(hDeviceKey);
if (port_info.port.empty())
continue;
}
// Find the size required to hold the device info.
DWORD regDataType;
DWORD reqSize = 0;
SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_HARDWAREID, nullptr, nullptr, 0, &reqSize);
std::vector<wchar_t> hardware_id(reqSize > 1 ? reqSize : 1);
// Now store it in a buffer.
if (! SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_HARDWAREID, ®DataType, (BYTE*)hardware_id.data(), reqSize, nullptr))
continue;
port_info.hardware_id = boost::nowide::narrow(hardware_id.data());
// Find the size required to hold the friendly name.
reqSize = 0;
SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_FRIENDLYNAME, nullptr, nullptr, 0, &reqSize);
std::vector<wchar_t> friendly_name;
friendly_name.reserve(reqSize > 1 ? reqSize : 1);
// Now store it in a buffer.
if (! SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_FRIENDLYNAME, nullptr, (BYTE*)friendly_name.data(), reqSize, nullptr)) {
port_info.friendly_name = port_info.port;
} else {
port_info.friendly_name = boost::nowide::narrow(friendly_name.data());
port_info.is_printer = looks_like_printer(port_info.friendly_name);
}
output.emplace_back(std::move(port_info));
}
}
#elif __APPLE__
// inspired by https://sigrok.org/wiki/Libserialport
CFMutableDictionaryRef classes = IOServiceMatching(kIOSerialBSDServiceValue);
if (classes != 0) {
io_iterator_t iter;
if (IOServiceGetMatchingServices(kIOMasterPortDefault, classes, &iter) == KERN_SUCCESS) {
io_object_t port;
while ((port = IOIteratorNext(iter)) != 0) {
CFTypeRef cf_property = IORegistryEntryCreateCFProperty(port, CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
if (cf_property) {
char path[PATH_MAX];
Boolean result = CFStringGetCString(cf_property, path, sizeof(path), kCFStringEncodingUTF8);
CFRelease(cf_property);
if (result) {
SerialPortInfo port_info;
port_info.port = path;
if ((cf_property = IORegistryEntrySearchCFProperty(port, kIOServicePlane,
CFSTR("USB Interface Name"), kCFAllocatorDefault,
kIORegistryIterateRecursively | kIORegistryIterateParents)) ||
(cf_property = IORegistryEntrySearchCFProperty(port, kIOServicePlane,
CFSTR("USB Product Name"), kCFAllocatorDefault,
kIORegistryIterateRecursively | kIORegistryIterateParents)) ||
(cf_property = IORegistryEntrySearchCFProperty(port, kIOServicePlane,
CFSTR("Product Name"), kCFAllocatorDefault,
kIORegistryIterateRecursively | kIORegistryIterateParents)) ||
(cf_property = IORegistryEntryCreateCFProperty(port,
CFSTR(kIOTTYDeviceKey), kCFAllocatorDefault, 0))) {
// Description limited to 127 char, anything longer would not be user friendly anyway.
char description[128];
if (CFStringGetCString(cf_property, description, sizeof(description), kCFStringEncodingUTF8)) {
port_info.friendly_name = std::string(description) + " (" + port_info.port + ")";
port_info.is_printer = looks_like_printer(port_info.friendly_name);
}
CFRelease(cf_property);
}
if (port_info.friendly_name.empty())
port_info.friendly_name = port_info.port;
output.emplace_back(std::move(port_info));
}
}
IOObjectRelease(port);
}
}
}
#else
// UNIX / Linux
std::initializer_list<const char*> prefixes { "ttyUSB" , "ttyACM", "tty.", "cu.", "rfcomm" };
for (auto &dir_entry : boost::filesystem::directory_iterator(boost::filesystem::path("/dev"))) {
std::string name = dir_entry.path().filename().string();
for (const char *prefix : prefixes) {
if (boost::starts_with(name, prefix)) {
SerialPortInfo spi;
spi.port = dir_entry.path().string();
spi.hardware_id = port;
spi.friendly_name = spi.port;
out.emplace_back(std::move(spi));
break;
}
}
}
#endif
output.erase(std::remove_if(output.begin(), output.end(),
[](const SerialPortInfo &info) {
return boost::starts_with(info.port, "Bluetooth") || boost::starts_with(info.port, "FireFly");
}),
output.end());
return output;
}
std::vector<std::string> scan_serial_ports()
{
std::vector<SerialPortInfo> ports = scan_serial_ports_extended();
std::vector<std::string> output;
output.reserve(ports.size());
for (const SerialPortInfo &spi : ports)
output.emplace_back(std::move(spi.port));
return output;
}
} // namespace Utils
} // namespace Slic3r
<commit_msg>Another fix for linux & osx<commit_after>#include "Serial.hpp"
#include <algorithm>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#if _WIN32
#include <Windows.h>
#include <Setupapi.h>
#include <initguid.h>
#include <devguid.h>
// Undefine min/max macros incompatible with the standard library
// For example, std::numeric_limits<std::streamsize>::max()
// produces some weird errors
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
#include "boost/nowide/convert.hpp"
#pragma comment(lib, "user32.lib")
#elif __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#include <CoreFoundation/CFString.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/serial/IOSerialKeys.h>
#include <IOKit/serial/ioss.h>
#include <sys/syslimits.h>
#endif
namespace Slic3r {
namespace Utils {
static bool looks_like_printer(const std::string &friendly_name)
{
return friendly_name.find("Original Prusa") != std::string::npos;
}
std::vector<SerialPortInfo> scan_serial_ports_extended()
{
std::vector<SerialPortInfo> output;
#ifdef _WIN32
SP_DEVINFO_DATA devInfoData = { 0 };
devInfoData.cbSize = sizeof(devInfoData);
// Get the tree containing the info for the ports.
HDEVINFO hDeviceInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_PORTS, 0, nullptr, DIGCF_PRESENT);
if (hDeviceInfo != INVALID_HANDLE_VALUE) {
// Iterate over all the devices in the tree.
for (int nDevice = 0; SetupDiEnumDeviceInfo(hDeviceInfo, nDevice, &devInfoData); ++ nDevice) {
SerialPortInfo port_info;
// Get the registry key which stores the ports settings.
HKEY hDeviceKey = SetupDiOpenDevRegKey(hDeviceInfo, &devInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE);
if (hDeviceKey) {
// Read in the name of the port.
wchar_t pszPortName[4096];
DWORD dwSize = sizeof(pszPortName);
DWORD dwType = 0;
if (RegQueryValueEx(hDeviceKey, L"PortName", NULL, &dwType, (LPBYTE)pszPortName, &dwSize) == ERROR_SUCCESS)
port_info.port = boost::nowide::narrow(pszPortName);
RegCloseKey(hDeviceKey);
if (port_info.port.empty())
continue;
}
// Find the size required to hold the device info.
DWORD regDataType;
DWORD reqSize = 0;
SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_HARDWAREID, nullptr, nullptr, 0, &reqSize);
std::vector<wchar_t> hardware_id(reqSize > 1 ? reqSize : 1);
// Now store it in a buffer.
if (! SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_HARDWAREID, ®DataType, (BYTE*)hardware_id.data(), reqSize, nullptr))
continue;
port_info.hardware_id = boost::nowide::narrow(hardware_id.data());
// Find the size required to hold the friendly name.
reqSize = 0;
SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_FRIENDLYNAME, nullptr, nullptr, 0, &reqSize);
std::vector<wchar_t> friendly_name;
friendly_name.reserve(reqSize > 1 ? reqSize : 1);
// Now store it in a buffer.
if (! SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_FRIENDLYNAME, nullptr, (BYTE*)friendly_name.data(), reqSize, nullptr)) {
port_info.friendly_name = port_info.port;
} else {
port_info.friendly_name = boost::nowide::narrow(friendly_name.data());
port_info.is_printer = looks_like_printer(port_info.friendly_name);
}
output.emplace_back(std::move(port_info));
}
}
#elif __APPLE__
// inspired by https://sigrok.org/wiki/Libserialport
CFMutableDictionaryRef classes = IOServiceMatching(kIOSerialBSDServiceValue);
if (classes != 0) {
io_iterator_t iter;
if (IOServiceGetMatchingServices(kIOMasterPortDefault, classes, &iter) == KERN_SUCCESS) {
io_object_t port;
while ((port = IOIteratorNext(iter)) != 0) {
CFTypeRef cf_property = IORegistryEntryCreateCFProperty(port, CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
if (cf_property) {
char path[PATH_MAX];
Boolean result = CFStringGetCString((CFStringRef)cf_property, path, sizeof(path), kCFStringEncodingUTF8);
CFRelease(cf_property);
if (result) {
SerialPortInfo port_info;
port_info.port = path;
if ((cf_property = IORegistryEntrySearchCFProperty(port, kIOServicePlane,
CFSTR("USB Interface Name"), kCFAllocatorDefault,
kIORegistryIterateRecursively | kIORegistryIterateParents)) ||
(cf_property = IORegistryEntrySearchCFProperty(port, kIOServicePlane,
CFSTR("USB Product Name"), kCFAllocatorDefault,
kIORegistryIterateRecursively | kIORegistryIterateParents)) ||
(cf_property = IORegistryEntrySearchCFProperty(port, kIOServicePlane,
CFSTR("Product Name"), kCFAllocatorDefault,
kIORegistryIterateRecursively | kIORegistryIterateParents)) ||
(cf_property = IORegistryEntryCreateCFProperty(port,
CFSTR(kIOTTYDeviceKey), kCFAllocatorDefault, 0))) {
// Description limited to 127 char, anything longer would not be user friendly anyway.
char description[128];
if (CFStringGetCString((CFStringRef)cf_property, description, sizeof(description), kCFStringEncodingUTF8)) {
port_info.friendly_name = std::string(description) + " (" + port_info.port + ")";
port_info.is_printer = looks_like_printer(port_info.friendly_name);
}
CFRelease(cf_property);
}
if (port_info.friendly_name.empty())
port_info.friendly_name = port_info.port;
output.emplace_back(std::move(port_info));
}
}
IOObjectRelease(port);
}
}
}
#else
// UNIX / Linux
std::initializer_list<const char*> prefixes { "ttyUSB" , "ttyACM", "tty.", "cu.", "rfcomm" };
for (auto &dir_entry : boost::filesystem::directory_iterator(boost::filesystem::path("/dev"))) {
std::string name = dir_entry.path().filename().string();
for (const char *prefix : prefixes) {
if (boost::starts_with(name, prefix)) {
SerialPortInfo spi;
spi.port = dir_entry.path().string();
spi.hardware_id = spi.port;
spi.friendly_name = spi.port;
output.emplace_back(std::move(spi));
break;
}
}
}
#endif
output.erase(std::remove_if(output.begin(), output.end(),
[](const SerialPortInfo &info) {
return boost::starts_with(info.port, "Bluetooth") || boost::starts_with(info.port, "FireFly");
}),
output.end());
return output;
}
std::vector<std::string> scan_serial_ports()
{
std::vector<SerialPortInfo> ports = scan_serial_ports_extended();
std::vector<std::string> output;
output.reserve(ports.size());
for (const SerialPortInfo &spi : ports)
output.emplace_back(std::move(spi.port));
return output;
}
} // namespace Utils
} // namespace Slic3r
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: drviewsh.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-09 07:13:01 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "DrawViewShell.hxx"
#ifndef _AEITEM_HXX //autogen
#include <svtools/aeitem.hxx>
#endif
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#pragma hdrstop
#ifndef _SVX_FMSHELL_HXX // XXX nur temp (dg)
#include <svx/fmshell.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#include "app.hrc"
#include "strings.hrc"
#include "sdpage.hxx"
#ifndef SD_FRAME_VIEW
#include "FrameView.hxx"
#endif
#include "sdresid.hxx"
#include "drawdoc.hxx"
#include "DrawDocShell.hxx"
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#ifndef SD_GRAPHIC_VIEW_SHELL_HXX
#include "GraphicViewShell.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
namespace sd {
#define TABCONTROL_INITIAL_SIZE 500
/*************************************************************************
|*
|* Sprung zu Bookmark
|*
\************************************************************************/
BOOL DrawViewShell::GotoBookmark(const String& rBookmark)
{
BOOL bRet = FALSE;
::sd::DrawDocShell* pDocSh = GetDocSh();
if( pDocSh )
{
if( !pDocSh->GetViewShell() ) //#i26016# this case occurs if the jump-target-document was opened already with file open dialog before triggering the jump via hyperlink
pDocSh->Connect(this);
bRet = (pDocSh->GotoBookmark(rBookmark));
}
return bRet;
}
/*************************************************************************
|*
|* Bereich sichtbar machen (Bildausschnitt scrollen)
|*
\************************************************************************/
void DrawViewShell::MakeVisible(const Rectangle& rRect, ::Window& rWin)
{
// #98568# In older versions, if in X or Y the size of the object was
// smaller than the visible area, the user-defined zoom was
// changed. This was decided to be a bug for 6.x, thus I developed a
// version which instead handles X/Y bigger/smaller and visibility
// questions seperately. The new behaviour is triggered with the
// bZoomAllowed parameter which for old behaviour should be set to
// sal_True. I looked at all uses of MakeVisible() in the application
// and found no valid reason for really changing the zoom factor, thus I
// decided to NOT expand (incompatible) this virtual method to get one
// more parameter. If this is wanted in later versions, feel free to add
// that bool to the parameter list.
sal_Bool bZoomAllowed(sal_False);
Size aLogicSize(rRect.GetSize());
// Sichtbarer Bereich
Size aVisSizePixel(rWin.GetOutputSizePixel());
Rectangle aVisArea(rWin.PixelToLogic(Rectangle(Point(0,0), aVisSizePixel)));
Size aVisAreaSize(aVisArea.GetSize());
if(!aVisArea.IsInside(rRect) && !mpSlideShow)
{
// Objekt liegt nicht komplett im sichtbaren Bereich
sal_Int32 nFreeSpaceX(aVisAreaSize.Width() - aLogicSize.Width());
sal_Int32 nFreeSpaceY(aVisAreaSize.Height() - aLogicSize.Height());
if(bZoomAllowed && (nFreeSpaceX < 0 || nFreeSpaceY < 0))
{
// Objekt passt nicht in sichtbaren Bereich -> auf Objektgroesse zoomen
SetZoomRect(rRect);
}
else
{
// #98568# allow a mode for move-only visibility without zooming.
const sal_Int32 nPercentBorder(30);
const Rectangle aInnerRectangle(
aVisArea.Left() + ((aVisAreaSize.Width() * nPercentBorder) / 200),
aVisArea.Top() + ((aVisAreaSize.Height() * nPercentBorder) / 200),
aVisArea.Right() - ((aVisAreaSize.Width() * nPercentBorder) / 200),
aVisArea.Bottom() - ((aVisAreaSize.Height() * nPercentBorder) / 200)
);
Point aNewPos(aVisArea.TopLeft());
if(nFreeSpaceX < 0)
{
if(aInnerRectangle.Left() > rRect.Right())
{
// object moves out to the left
aNewPos.X() -= aVisAreaSize.Width() / 2;
}
if(aInnerRectangle.Right() < rRect.Left())
{
// object moves out to the right
aNewPos.X() += aVisAreaSize.Width() / 2;
}
}
else
{
if(nFreeSpaceX > rRect.GetWidth())
nFreeSpaceX = rRect.GetWidth();
while(rRect.Right() > aNewPos.X() + aVisAreaSize.Width())
aNewPos.X() += nFreeSpaceX;
while(rRect.Left() < aNewPos.X())
aNewPos.X() -= nFreeSpaceX;
}
if(nFreeSpaceY < 0)
{
if(aInnerRectangle.Top() > rRect.Bottom())
{
// object moves out to the top
aNewPos.Y() -= aVisAreaSize.Height() / 2;
}
if(aInnerRectangle.Bottom() < rRect.Top())
{
// object moves out to the right
aNewPos.Y() += aVisAreaSize.Height() / 2;
}
}
else
{
if(nFreeSpaceY > rRect.GetHeight())
nFreeSpaceY = rRect.GetHeight();
while(rRect.Bottom() > aNewPos.Y() + aVisAreaSize.Height())
aNewPos.Y() += nFreeSpaceY;
while(rRect.Top() < aNewPos.Y())
aNewPos.Y() -= nFreeSpaceY;
}
// did position change? Does it need to be set?
if(aNewPos != aVisArea.TopLeft())
{
aVisArea.SetPos(aNewPos);
SetZoomRect(aVisArea);
}
}
}
}
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.9.282); FILE MERGED 2006/09/01 17:37:38 kaib 1.9.282.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: drviewsh.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2006-09-16 19:39:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "DrawViewShell.hxx"
#ifndef _AEITEM_HXX //autogen
#include <svtools/aeitem.hxx>
#endif
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _SVX_FMSHELL_HXX // XXX nur temp (dg)
#include <svx/fmshell.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#include "app.hrc"
#include "strings.hrc"
#include "sdpage.hxx"
#ifndef SD_FRAME_VIEW
#include "FrameView.hxx"
#endif
#include "sdresid.hxx"
#include "drawdoc.hxx"
#include "DrawDocShell.hxx"
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#ifndef SD_GRAPHIC_VIEW_SHELL_HXX
#include "GraphicViewShell.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
namespace sd {
#define TABCONTROL_INITIAL_SIZE 500
/*************************************************************************
|*
|* Sprung zu Bookmark
|*
\************************************************************************/
BOOL DrawViewShell::GotoBookmark(const String& rBookmark)
{
BOOL bRet = FALSE;
::sd::DrawDocShell* pDocSh = GetDocSh();
if( pDocSh )
{
if( !pDocSh->GetViewShell() ) //#i26016# this case occurs if the jump-target-document was opened already with file open dialog before triggering the jump via hyperlink
pDocSh->Connect(this);
bRet = (pDocSh->GotoBookmark(rBookmark));
}
return bRet;
}
/*************************************************************************
|*
|* Bereich sichtbar machen (Bildausschnitt scrollen)
|*
\************************************************************************/
void DrawViewShell::MakeVisible(const Rectangle& rRect, ::Window& rWin)
{
// #98568# In older versions, if in X or Y the size of the object was
// smaller than the visible area, the user-defined zoom was
// changed. This was decided to be a bug for 6.x, thus I developed a
// version which instead handles X/Y bigger/smaller and visibility
// questions seperately. The new behaviour is triggered with the
// bZoomAllowed parameter which for old behaviour should be set to
// sal_True. I looked at all uses of MakeVisible() in the application
// and found no valid reason for really changing the zoom factor, thus I
// decided to NOT expand (incompatible) this virtual method to get one
// more parameter. If this is wanted in later versions, feel free to add
// that bool to the parameter list.
sal_Bool bZoomAllowed(sal_False);
Size aLogicSize(rRect.GetSize());
// Sichtbarer Bereich
Size aVisSizePixel(rWin.GetOutputSizePixel());
Rectangle aVisArea(rWin.PixelToLogic(Rectangle(Point(0,0), aVisSizePixel)));
Size aVisAreaSize(aVisArea.GetSize());
if(!aVisArea.IsInside(rRect) && !mpSlideShow)
{
// Objekt liegt nicht komplett im sichtbaren Bereich
sal_Int32 nFreeSpaceX(aVisAreaSize.Width() - aLogicSize.Width());
sal_Int32 nFreeSpaceY(aVisAreaSize.Height() - aLogicSize.Height());
if(bZoomAllowed && (nFreeSpaceX < 0 || nFreeSpaceY < 0))
{
// Objekt passt nicht in sichtbaren Bereich -> auf Objektgroesse zoomen
SetZoomRect(rRect);
}
else
{
// #98568# allow a mode for move-only visibility without zooming.
const sal_Int32 nPercentBorder(30);
const Rectangle aInnerRectangle(
aVisArea.Left() + ((aVisAreaSize.Width() * nPercentBorder) / 200),
aVisArea.Top() + ((aVisAreaSize.Height() * nPercentBorder) / 200),
aVisArea.Right() - ((aVisAreaSize.Width() * nPercentBorder) / 200),
aVisArea.Bottom() - ((aVisAreaSize.Height() * nPercentBorder) / 200)
);
Point aNewPos(aVisArea.TopLeft());
if(nFreeSpaceX < 0)
{
if(aInnerRectangle.Left() > rRect.Right())
{
// object moves out to the left
aNewPos.X() -= aVisAreaSize.Width() / 2;
}
if(aInnerRectangle.Right() < rRect.Left())
{
// object moves out to the right
aNewPos.X() += aVisAreaSize.Width() / 2;
}
}
else
{
if(nFreeSpaceX > rRect.GetWidth())
nFreeSpaceX = rRect.GetWidth();
while(rRect.Right() > aNewPos.X() + aVisAreaSize.Width())
aNewPos.X() += nFreeSpaceX;
while(rRect.Left() < aNewPos.X())
aNewPos.X() -= nFreeSpaceX;
}
if(nFreeSpaceY < 0)
{
if(aInnerRectangle.Top() > rRect.Bottom())
{
// object moves out to the top
aNewPos.Y() -= aVisAreaSize.Height() / 2;
}
if(aInnerRectangle.Bottom() < rRect.Top())
{
// object moves out to the right
aNewPos.Y() += aVisAreaSize.Height() / 2;
}
}
else
{
if(nFreeSpaceY > rRect.GetHeight())
nFreeSpaceY = rRect.GetHeight();
while(rRect.Bottom() > aNewPos.Y() + aVisAreaSize.Height())
aNewPos.Y() += nFreeSpaceY;
while(rRect.Top() < aNewPos.Y())
aNewPos.Y() -= nFreeSpaceY;
}
// did position change? Does it need to be set?
if(aNewPos != aVisArea.TopLeft())
{
aVisArea.SetPos(aNewPos);
SetZoomRect(aVisArea);
}
}
}
}
}
<|endoftext|> |
<commit_before>#ifndef GUARD_account_hpp
#define GUARD_account_hpp
/** \file account.hpp
*
* \brief Header file pertaining to Account class.
*
* \author Matthew Harvey
* \date 04 July 2012.
*
* Copyright (c) 2012, Matthew Harvey. All rights reserved.
*/
#include "general_typedefs.hpp"
#include "sqloxx/database_connection.hpp"
#include "sqloxx/persistent_object.hpp"
#include <boost/noncopyable.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <string>
#include <vector>
namespace phatbooks
{
/**
* Represents an Account object that is "live" in memory, rather than
* stored in a database.
*
* @todo I should probably load m_name immediately with the id, but then
* lazy load everything else. Note the m_name is used as an identifier
* in Entry objects. At the moment I have got m_name as one of the lazy
* attributes.
*/
class Account:
public sqloxx::PersistentObject<IdType>,
private boost::noncopyable
{
public:
typedef IdType Id;
typedef sqloxx::PersistentObject<Id> PersistentObject;
enum AccountType
{
// enum order is significant, as the database contains
// a table with primary keys in this order. See setup_tables
// method
asset = 1,
liability,
equity,
revenue,
expense,
pure_envelope
};
/**
* Returns a vector of account type names, corresponding to the
* AccountType enumerations, and in the same order.
*/
static std::vector<std::string> account_type_names();
/**
* Sets up tables in the database required for the persistence of
* Account objects.
*/
static void setup_tables(sqloxx::DatabaseConnection& dbc);
/**
* Initialize a "draft" account, that will not correspond to any
* particular object in the database.
*/
explicit
Account
( boost::shared_ptr<sqloxx::DatabaseConnection> p_database_connection
);
/**
* Get an Account by id from database.
*/
Account
( boost::shared_ptr<sqloxx::DatabaseConnection> p_database_connection,
Id p_id
);
/**
* Get an Account by name from the database.
*/
Account
( boost::shared_ptr<sqloxx::DatabaseConnection> p_database_connection,
std::string const& p_name
);
// Default destructor is fine.
/**
* Returns name of account.
*/
std::string name();
/**
* Returns abbreviation of native commodity of this account.
*/
std::string commodity_abbreviation();
/**
* Returns AccountType of account.
*/
AccountType account_type();
/**
* Returns description of account.
*/
std::string description();
void set_account_type(AccountType p_account_type);
void set_name(std::string const& p_name);
void set_commodity_abbreviation
( std::string const& p_commodity_abbreviation
);
void set_description(std::string const& p_description);
private:
virtual void do_load_all();
/* WARNING I need to implement this properly
*/
virtual void do_save_existing_all()
{
}
/* WARNING I need to implement this properly
*/
virtual void do_save_existing_partial()
{
}
virtual void do_save_new_all();
virtual std::string do_get_table_name() const;
void load_name_knowing_id();
void load_id_knowing_name();
struct AccountData
{
std::string name;
boost::optional<std::string> commodity_abbreviation;
boost::optional<AccountType> account_type;
boost::optional<std::string> description;
};
boost::scoped_ptr<AccountData> m_data;
};
inline
Account::Account
( boost::shared_ptr<sqloxx::DatabaseConnection> p_database_connection
):
PersistentObject(p_database_connection),
m_data(new AccountData)
{
}
inline
Account::Account
( boost::shared_ptr<sqloxx::DatabaseConnection> p_database_connection,
Id p_id
):
PersistentObject(p_database_connection, p_id),
m_data(new AccountData)
{
}
inline
Account::Account
( boost::shared_ptr<sqloxx::DatabaseConnection> p_database_connection,
std::string const& p_name
):
PersistentObject(p_database_connection)
{
m_data->name = p_name;
load_id_knowing_name();
}
} // namespace phatbooks
#endif // GUARD_account_hpp
<commit_msg>Fixed bug in Account re. uninitialized account name.<commit_after>#ifndef GUARD_account_hpp
#define GUARD_account_hpp
/** \file account.hpp
*
* \brief Header file pertaining to Account class.
*
* \author Matthew Harvey
* \date 04 July 2012.
*
* Copyright (c) 2012, Matthew Harvey. All rights reserved.
*/
#include "general_typedefs.hpp"
#include "sqloxx/database_connection.hpp"
#include "sqloxx/persistent_object.hpp"
#include <boost/noncopyable.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <string>
#include <vector>
namespace phatbooks
{
/**
* Represents an Account object that is "live" in memory, rather than
* stored in a database.
*
* @todo I should probably load m_name immediately with the id, but then
* lazy load everything else. Note the m_name is used as an identifier
* in Entry objects. At the moment I have got m_name as one of the lazy
* attributes.
*/
class Account:
public sqloxx::PersistentObject<IdType>,
private boost::noncopyable
{
public:
typedef IdType Id;
typedef sqloxx::PersistentObject<Id> PersistentObject;
enum AccountType
{
// enum order is significant, as the database contains
// a table with primary keys in this order. See setup_tables
// method
asset = 1,
liability,
equity,
revenue,
expense,
pure_envelope
};
/**
* Returns a vector of account type names, corresponding to the
* AccountType enumerations, and in the same order.
*/
static std::vector<std::string> account_type_names();
/**
* Sets up tables in the database required for the persistence of
* Account objects.
*/
static void setup_tables(sqloxx::DatabaseConnection& dbc);
/**
* Initialize a "draft" account, that will not correspond to any
* particular object in the database.
*/
explicit
Account
( boost::shared_ptr<sqloxx::DatabaseConnection> p_database_connection
);
/**
* Get an Account by id from database.
*/
Account
( boost::shared_ptr<sqloxx::DatabaseConnection> p_database_connection,
Id p_id
);
/**
* Get an Account by name from the database.
*/
Account
( boost::shared_ptr<sqloxx::DatabaseConnection> p_database_connection,
std::string const& p_name
);
// Default destructor is fine.
/**
* Returns name of account.
*/
std::string name();
/**
* Returns abbreviation of native commodity of this account.
*/
std::string commodity_abbreviation();
/**
* Returns AccountType of account.
*/
AccountType account_type();
/**
* Returns description of account.
*/
std::string description();
void set_account_type(AccountType p_account_type);
void set_name(std::string const& p_name);
void set_commodity_abbreviation
( std::string const& p_commodity_abbreviation
);
void set_description(std::string const& p_description);
private:
virtual void do_load_all();
/* WARNING I need to implement this properly
*/
virtual void do_save_existing_all()
{
}
/* WARNING I need to implement this properly
*/
virtual void do_save_existing_partial()
{
}
virtual void do_save_new_all();
virtual std::string do_get_table_name() const;
void load_name_knowing_id();
void load_id_knowing_name();
struct AccountData
{
std::string name;
boost::optional<std::string> commodity_abbreviation;
boost::optional<AccountType> account_type;
boost::optional<std::string> description;
};
boost::scoped_ptr<AccountData> m_data;
};
inline
Account::Account
( boost::shared_ptr<sqloxx::DatabaseConnection> p_database_connection
):
PersistentObject(p_database_connection),
m_data(new AccountData)
{
}
inline
Account::Account
( boost::shared_ptr<sqloxx::DatabaseConnection> p_database_connection,
Id p_id
):
PersistentObject(p_database_connection, p_id),
m_data(new AccountData)
{
load_name_knowing_id();
}
inline
Account::Account
( boost::shared_ptr<sqloxx::DatabaseConnection> p_database_connection,
std::string const& p_name
):
PersistentObject(p_database_connection),
m_data(new AccountData)
{
m_data->name = p_name;
load_id_knowing_name();
}
} // namespace phatbooks
#endif // GUARD_account_hpp
<|endoftext|> |
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/FORMAT/SCWRLRotamerFile.h>
#include <BALL/STRUCTURE/rotamerLibrary.h>
using namespace std;
namespace BALL
{
SCWRLRotamerFile::SCWRLRotamerFile()
: LineBasedFile()
{
}
SCWRLRotamerFile::SCWRLRotamerFile(const String& name, File::OpenMode open_mode)
: LineBasedFile(name, open_mode)
{
}
SCWRLRotamerFile::~SCWRLRotamerFile()
{
}
const SCWRLRotamerFile& SCWRLRotamerFile::operator = (const SCWRLRotamerFile& file)
{
LineBasedFile::operator = (file);
return *this;
}
void SCWRLRotamerFile::operator >> (RotamerLibrary& rotamer_library)
{
// now we must decide wether this is a backbone dependent or not
RegularExpression match_indep("[A-Z][A-Z][A-Z] [0-9] [0-9] [0-9] [0-9] *[0-9]* *[0-9]* *[0-9\\.]*");
// if the expression matches at least one time, this might be a bb indep file
while (readLine())
{
if (match_indep.match(line_))
{
rewind();
readSCWRLBackboneIndependentLibraryFile_(rotamer_library);
if (!rotamer_library.validate())
{
throw(Exception::ParseError(__FILE__, __LINE__, "The discretization of the backbone torsions are not correct!", ""));
}
clear();
return;
}
}
// if not matched this is much likely a backbone independent file
rewind();
readSCWRLBackboneDependentLibraryFile_(rotamer_library);
if (!rotamer_library.validate())
{
throw(Exception::ParseError(__FILE__, __LINE__, "The discretization of the backbone torsions are not correct!", ""));
}
clear();
return;
}
void SCWRLRotamerFile::readSCWRLBackboneDependentLibraryFile_(RotamerLibrary& rotamer_library)
{
rotamer_library.setBackboneDependent(true);
String aa_name;
Index phi(0);
Index psi(0);
double probability(0);
while(readLine())
{
phi = line_.getField(1).toInt();
psi = line_.getField(2).toInt();
probability = line_.getField(8).toFloat();
Size number_of_torsions(0);
for (Size i = 4; i != 8; ++i)
{
if (line_.getField(i).toInt() != 0)
{
number_of_torsions++;
}
else
{
break;
}
}
//Angle chi1, chi2, chi3, chi4;
//chi1.set(line_.getField(9).toFloat(), false);
//chi2.set(line_.getField(10).toFloat(), false);
//chi3.set(line_.getField(11).toFloat(), false);
//chi4.set(line_.getField(12).toFloat(), false);
aa_name = line_.getField(0);
rotamer_library.addRotamer(aa_name, Rotamer(probability, line_.getField(9).toFloat(),
line_.getField(10).toFloat(),
line_.getField(11).toFloat(),
line_.getField(12).toFloat()), number_of_torsions, phi, psi);
}
return;
}
void SCWRLRotamerFile::readSCWRLBackboneIndependentLibraryFile_(RotamerLibrary& rotamer_library)
{
rotamer_library.setBackboneDependent(false);
// read the file into a vector of Strings to reparse
// it faster. Since the SQWRL format is a pain in the ass
// we have to identify relevant lines by a regular expression
RegularExpression regexp("[A-Z][A-Z][A-Z] [0-9] [0-9] [0-9] [0-9] *[0-9]* *[0-9]* *[0-9\\.]*");
String split[18];
while (readLine())
{
if (regexp.match(line_))
{
String aa_name = line_(0, 3);
Size number_of_fields = line_.split(split, 18);
float prob = line_.getField(7).toFloat() / 100.0;
//Angle chi1, chi2, chi3, chi4;
float chi1(0), chi2(0), chi3(0), chi4(0);
//chi1.set(line_.getField(11).toFloat());
chi1 = line_.getField(11).toFloat();
Size number_of_torsions = 1;
if (number_of_fields > 13)
{
//chi2.set(line_.getField(13).toFloat());
chi2 = line_.getField(13).toFloat();
number_of_torsions = 2;
}
if (number_of_fields > 15)
{
//chi3.set(line_.getField(15).toFloat());
chi3 = line_.getField(15).toFloat();
number_of_torsions = 3;
}
if (number_of_fields > 17)
{
//chi4.set(line_.getField(17).toFloat());
chi4 = line_.getField(17).toFloat();
number_of_torsions = 4;
}
rotamer_library.addRotamer(aa_name, Rotamer(prob, chi1, chi2, chi3, chi4), number_of_torsions);
}
}
}
} // namespace BALL
<commit_msg>Speed up SCWRLRotamerFile.<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/FORMAT/SCWRLRotamerFile.h>
#include <BALL/STRUCTURE/rotamerLibrary.h>
using namespace std;
namespace BALL
{
SCWRLRotamerFile::SCWRLRotamerFile()
: LineBasedFile()
{
}
SCWRLRotamerFile::SCWRLRotamerFile(const String& name, File::OpenMode open_mode)
: LineBasedFile(name, open_mode)
{
}
SCWRLRotamerFile::~SCWRLRotamerFile()
{
}
const SCWRLRotamerFile& SCWRLRotamerFile::operator = (const SCWRLRotamerFile& file)
{
LineBasedFile::operator = (file);
return *this;
}
void SCWRLRotamerFile::operator >> (RotamerLibrary& rotamer_library)
{
// now we must decide wether this is a backbone dependent or not
RegularExpression match_indep("[A-Z][A-Z][A-Z] [0-9] [0-9] [0-9] [0-9] *[0-9]* *[0-9]* *[0-9\\.]*");
// if the expression matches at least one time, this might be a bb indep file
while (readLine())
{
if (match_indep.match(line_))
{
rewind();
readSCWRLBackboneIndependentLibraryFile_(rotamer_library);
if (!rotamer_library.validate())
{
throw(Exception::ParseError(__FILE__, __LINE__, "The discretization of the backbone torsions are not correct!", ""));
}
clear();
return;
}
}
// if not matched this is much likely a backbone independent file
rewind();
readSCWRLBackboneDependentLibraryFile_(rotamer_library);
if (!rotamer_library.validate())
{
throw(Exception::ParseError(__FILE__, __LINE__, "The discretization of the backbone torsions are not correct!", ""));
}
clear();
return;
}
void SCWRLRotamerFile::readSCWRLBackboneDependentLibraryFile_(RotamerLibrary& rotamer_library)
{
rotamer_library.setBackboneDependent(true);
String aa_name;
Index phi(0);
Index psi(0);
double probability(0);
std::vector<String> split;
while(readLine())
{
line_.split(split);
phi = split[1].toInt();
psi = split[2].toInt();
probability = split[8].toFloat();
Size number_of_torsions(0);
for (Size i = 4; i != 8; ++i)
{
if (split[i].toInt() != 0)
{
number_of_torsions++;
}
else
{
break;
}
}
//Angle chi1, chi2, chi3, chi4;
//chi1.set(split[9].toFloat(), false);
//chi2.set(split[10].toFloat(), false);
//chi3.set(split[11].toFloat(), false);
//chi4.set(split[12].toFloat(), false);
aa_name = split[0];
rotamer_library.addRotamer(aa_name, Rotamer(probability, split[9].toFloat(),
split[10].toFloat(),
split[11].toFloat(),
split[12].toFloat()), number_of_torsions, phi, psi);
}
return;
}
void SCWRLRotamerFile::readSCWRLBackboneIndependentLibraryFile_(RotamerLibrary& rotamer_library)
{
rotamer_library.setBackboneDependent(false);
// read the file into a vector of Strings to reparse
// it faster. Since the SQWRL format is a pain in the ass
// we have to identify relevant lines by a regular expression
RegularExpression regexp("[A-Z][A-Z][A-Z] [0-9] [0-9] [0-9] [0-9] *[0-9]* *[0-9]* *[0-9\\.]*");
String split[18];
while (readLine())
{
if (regexp.match(line_))
{
String aa_name = line_(0, 3);
Size number_of_fields = line_.split(split, 18);
float prob = split[7].toFloat() / 100.0;
//Angle chi1, chi2, chi3, chi4;
float chi1(0), chi2(0), chi3(0), chi4(0);
//chi1.set(split[11].toFloat());
chi1 = split[11].toFloat();
Size number_of_torsions = 1;
if (number_of_fields > 13)
{
//chi2.set(split[13].toFloat());
chi2 = split[13].toFloat();
number_of_torsions = 2;
}
if (number_of_fields > 15)
{
//chi3.set(split[15].toFloat());
chi3 = split[15].toFloat();
number_of_torsions = 3;
}
if (number_of_fields > 17)
{
//chi4.set(split[17].toFloat());
chi4 = split[17].toFloat();
number_of_torsions = 4;
}
rotamer_library.addRotamer(aa_name, Rotamer(prob, chi1, chi2, chi3, chi4), number_of_torsions);
}
}
}
} // namespace BALL
<|endoftext|> |
<commit_before>#include "stdsneezy.h"
#include "database.h"
#include "shop.h"
#include "shopowned.h"
void calcBankInterest()
{
TDatabase db(DB_SNEEZY), in(DB_SNEEZY);
double profit_sell;
unsigned int shop_nr;
int pretalens=0, posttalens=0;
db.query("select shop_nr, keeper from shop");
while(db.fetchRow()){
if(mob_index[real_mobile(convertTo<int>(db["keeper"]))].spec==SPEC_BANKER){
shop_nr=convertTo<int>(db["shop_nr"]);
profit_sell=shop_index[shop_nr].profit_sell;
if(profit_sell==1.0)
continue;
in.query("select sum(talens) as talens from shopownedbank where shop_nr=%i",
shop_nr);
if(in.fetchRow())
pretalens=convertTo<int>(in["talens"]);
in.query("select sum(talens) as talens from shopownedcorpbank where shop_nr=%i",
shop_nr);
if(in.fetchRow())
pretalens+=convertTo<int>(in["talens"]);
// calculate interest
in.query("update shopownedbank set earned_interest=earned_interest + (talens * (%f / 365.0)) where shop_nr=%i", profit_sell, shop_nr);
// doll out earned interest that isn't fractional
in.query("update shopownedbank set talens=talens + trunc(earned_interest), earned_interest=earned_interest - trunc(earned_interest) where shop_nr=%i", shop_nr);
// calculate interest
in.query("update shopownedcorpbank set earned_interest=earned_interest + (talens * (%f / 365.0)) where shop_nr=%i", profit_sell, shop_nr);
// doll out earned interest that isn't fractional
in.query("update shopownedcorpbank set talens=talens + trunc(earned_interest), earned_interest=earned_interest - trunc(earned_interest) where shop_nr=%i", shop_nr);
in.query("select sum(talens) as talens from shopownedbank where shop_nr=%i",
shop_nr);
if(in.fetchRow())
posttalens=convertTo<int>(in["talens"]);
in.query("select sum(talens) as talens from shopownedcorpbank where shop_nr=%i",
shop_nr);
if(in.fetchRow())
posttalens+=convertTo<int>(in["talens"]);
if((posttalens-pretalens) !=0)
in.query("insert into shoplog values (%i, '%s', 'paying interest', 'all', %i, 0, 0, now(), 0)", shop_nr,
mob_index[real_mobile(convertTo<int>(db["keeper"]))].short_desc,
posttalens-pretalens);
}
}
}
int bankWithdraw(TBeing *ch, TMonster *myself, TMonster *teller, int shop_nr, int money)
{
TDatabase db(DB_SNEEZY);
int bankmoney;
if (!ch->isPc() || dynamic_cast<TMonster *>(ch)) {
teller->doTell(ch->getName(), "Stupid monster can't bank here!");
return TRUE;
}
db.query("select talens from shopownedbank where shop_nr=%i and player_id=%i", shop_nr, ch->getPlayerID());
if(!db.fetchRow()){
teller->doTell(ch->getName(), "You don't have an account here.");
teller->doTell(ch->getName(), "To open an account, type 'buy account'.");
teller->doTell(ch->getName(), "The new account fee is 100 talens.");
return FALSE;
} else
bankmoney = convertTo<int>(db["talens"]);
if (money > bankmoney) {
teller->doTell(ch->getName(), "You don't have enough in the bank for that!");
return TRUE;
} else if(myself->getMoney() < money){
teller->doTell(ch->getName(), "The bank doesn't have your funds available right now!");
return TRUE;
} else if (money <= 0) {
teller->doTell(ch->getName(), "Go away, you bother me.");
return TRUE;
}
teller->doTell(ch->getName(), "Thank you.");
myself->giveMoney(ch, money, GOLD_XFER);
myself->saveItems(fmt("%s/%d") % SHOPFILE_PATH % shop_nr);
db.query("update shopownedbank set talens=talens-%i where player_id=%i and shop_nr=%i", money, ch->getPlayerID(), shop_nr);
shoplog(shop_nr, ch, myself, "talens", -money, "withdrawal");
return TRUE;
}
int bankDeposit(TBeing *ch, TMonster *myself, TMonster *teller, int shop_nr, int money)
{
TDatabase db(DB_SNEEZY);
int bankmoney;
if (!ch->isPc() || dynamic_cast<TMonster *>(ch)) {
teller->doTell(ch->getName(), "Stupid monster can't bank here!");
return TRUE;
}
db.query("select talens from shopownedbank where shop_nr=%i and player_id=%i", shop_nr, ch->getPlayerID());
if(!db.fetchRow()){
teller->doTell(ch->getName(), "You don't have an account here.");
teller->doTell(ch->getName(), "To open an account, type 'buy account'.");
teller->doTell(ch->getName(), "The new account fee is 100 talens.");
return TRUE;
}
if (money <= 0) {
teller->doTell(ch->getName(), "Go away, you bother me.");
return TRUE;
} else if (money > ch->getMoney()) {
teller->doTell(ch->getName(), "You don't have enough for that!");
return TRUE;
}
teller->doTell(ch->getName(), "Thank you.");
ch->giveMoney(myself, money, GOLD_XFER);
myself->saveItems(fmt("%s/%d") % SHOPFILE_PATH % shop_nr);
db.query("update shopownedbank set talens=talens+%i where player_id=%i and shop_nr=%i", money, ch->getPlayerID(), shop_nr);
shoplog(shop_nr, ch, myself, "talens", money, "deposit");
db.query("select talens from shopownedbank where shop_nr=%i and player_id=%i", shop_nr, ch->getPlayerID());
if (!db.fetchRow()) {
teller->doTell(ch->getName(), "You really should not see me, this is an error...");
vlogf(LOG_BUG, fmt("Banking error, was unable to retrieve balance after a deposit: %s") % ch->getName());
return TRUE;
} else
bankmoney = convertTo<int>(db["talens"]);
teller->doTell(ch->getName(), fmt("...Your new balance is %i") % bankmoney);
return TRUE;
}
int bankBalance(TBeing *ch, TMonster *myself, TMonster *teller, int shop_nr)
{
TDatabase db(DB_SNEEZY);
int bankmoney;
db.query("select talens from shopownedbank where shop_nr=%i and player_id=%i", shop_nr, ch->getPlayerID());
if(!db.fetchRow()){
teller->doTell(ch->getName(), "You don't have an account here.");
teller->doTell(ch->getName(), "To open an account, type 'buy account'.");
teller->doTell(ch->getName(), "The new account fee is 100 talens.");
return TRUE;
} else
bankmoney = convertTo<int>(db["talens"]);
teller->doTell(ch->getName(), fmt("Your balance is %i.") % bankmoney);
return TRUE;
}
int bankBuyAccount(TBeing *ch, TMonster *myself, TMonster *teller, int shop_nr, int money)
{
TDatabase db(DB_SNEEZY);
if(ch->getMoney() < 100){
teller->doTell(ch->getName(), "You don't have enough money to open an account.");
return TRUE;
}
db.query("select talens from shopownedbank where player_id=%i and shop_nr=%i", ch->getPlayerID(), shop_nr);
if(db.fetchRow()){
teller->doTell(ch->getName(), "You already have an account.");
return TRUE;
}
db.query("insert into shopownedbank (player_id, shop_nr, talens) values (%i, %i, 0)", ch->getPlayerID(), shop_nr);
ch->giveMoney(myself, 100, GOLD_XFER);
shoplog(shop_nr, ch, myself, "talens", 100, "new account");
myself->saveItems(fmt("%s/%d") % SHOPFILE_PATH % shop_nr);
teller->doTell(ch->getName(), "Your account is now open and ready for use.");
return TRUE;
}
int banker(TBeing *ch, cmdTypeT cmd, const char *arg, TMonster *myself, TObj *)
{
int shop_nr, money=0;
TDatabase db(DB_SNEEZY);
if((cmd!=CMD_WITHDRAW &&
cmd!=CMD_DEPOSIT &&
cmd!=CMD_BUY &&
cmd!=CMD_LIST &&
cmd!=CMD_BALANCE &&
cmd!=CMD_WHISPER) ||
!ch || !myself)
return FALSE;
if(!(shop_nr=find_shop_nr(myself->number)))
return FALSE;
if(cmd==CMD_WHISPER)
return shopWhisper(ch, myself, shop_nr, arg);
if(cmd==CMD_LIST){
TShopOwned tso(shop_nr, myself, ch);
if(!tso.hasAccess(SHOPACCESS_LOGS)){
myself->doTell(ch->getName(), "Sorry, you don't have access to do that.");
return FALSE;
}
db.query("select p.name, b.talens from player p, shopownedbank b where b.shop_nr=%i and b.player_id=p.id union select c.name, b.talens from corporation c, shopownedcorpbank b where b.shop_nr=c.bank and b.shop_nr=%i and b.corp_id=c.corp_id order by talens desc", shop_nr, shop_nr);
sstring buf;
int empty=0;
while(db.fetchRow()){
if(convertTo<int>(db["talens"]) == 0)
empty++;
else
buf += fmt("<c>%s - %s talens.<1>\n\r") % db["name"] %
talenDisplay(convertTo<int>(db["talens"]));
}
buf += fmt("%i empty accounts.\n\r") % empty;
db.query("select (sb.c+sbc.c) as c, (sb.t+sbc.t) as t from (select count(*) as c, sum(talens) as t from shopownedbank where shop_nr=%i) sb, (select count(*) as c, sum(talens) as t from shopownedcorpbank where shop_nr=%i) sbc", shop_nr, shop_nr);
if(db.fetchRow()){
buf += fmt("%i total accounts, %s talens.\n\r") %
convertTo<int>(db["c"]) %
talenDisplay(convertTo<int>(db["t"]));
}
ch->desc->page_string(buf);
return TRUE;
}
if(cmd==CMD_BUY && sstring(arg).lower()=="account"){
money=convertTo<int>(arg);
return bankBuyAccount(ch, myself, myself, shop_nr, money);
} else if(cmd==CMD_BALANCE){
return bankBalance(ch, myself, myself, shop_nr);
} else if(cmd==CMD_WITHDRAW){
if(!strcmp(arg, "all"))
money=ch->getBank();
else
money=convertTo<int>(arg);
return bankWithdraw(ch, myself, myself, shop_nr, money);
} else if(cmd==CMD_DEPOSIT){
if(!strcmp(arg, "all"))
money=ch->getMoney();
else
money=convertTo<int>(arg);
return bankDeposit(ch, myself, myself, shop_nr, money);
}
return TRUE;
}
int bankRoom(TBeing *ch, cmdTypeT cmd, const char *arg, TRoom *rp)
{
TMonster *teller, *banker;
TBeing *t;
int tmp=130, money, shop_nr;
// tellers/branches can only do these commands
if(cmd!=CMD_WITHDRAW &&
cmd!=CMD_DEPOSIT &&
cmd!=CMD_BALANCE &&
cmd!=CMD_BUY)
return FALSE;
// find out which teller for this room
switch(rp->number){
case 31751:
case 31756:
case 2351:
tmp=31750;
break;
case 1295:
tmp=1295;
break;
case 3755:
tmp=3755;
break;
case 8756:
tmp=8756;
break;
}
// find the teller
for(t=character_list;t;t=t->next){
if(t->mobVnum()==tmp)
break;
}
if(!t || !(teller=dynamic_cast<TMonster *>(t)))
return FALSE;
// find out which banker for this room
switch(rp->number){
case 31751:
case 31756:
case 2351:
tmp=31765;
break;
case 1295:
tmp=1295;
break;
case 3755:
tmp=3755;
break;
case 8756:
tmp=8756;
break;
}
// find the banker
for(t=character_list;t;t=t->next){
if(t->mobVnum()==tmp)
break;
}
if(!t || !(banker=dynamic_cast<TMonster *>(t)))
return FALSE;
if(!(shop_nr=find_shop_nr(banker->number)))
return FALSE;
if(cmd==CMD_BUY && sstring(arg).lower()=="account"){
money=convertTo<int>(arg);
return bankBuyAccount(ch, banker, teller, shop_nr, money);
} else if(cmd==CMD_BALANCE){
return bankBalance(ch, banker, teller, shop_nr);
} else if(cmd==CMD_WITHDRAW){
if(!strcmp(arg, "all"))
money=ch->getBank();
else
money=convertTo<int>(arg);
return bankWithdraw(ch, banker, teller, shop_nr, money);
} else if(cmd==CMD_DEPOSIT){
if(!strcmp(arg, "all"))
money=ch->getMoney();
else
money=convertTo<int>(arg);
return bankDeposit(ch, banker, teller, shop_nr, money);
}
return FALSE;
}
<commit_msg>added check to set talens and earned_interest to 0 if null<commit_after>#include "stdsneezy.h"
#include "database.h"
#include "shop.h"
#include "shopowned.h"
void calcBankInterest()
{
TDatabase db(DB_SNEEZY), in(DB_SNEEZY);
double profit_sell;
unsigned int shop_nr;
int pretalens=0, posttalens=0;
db.query("update shopownedbank set earned_interest=0 where earned_interest is null");
db.query("update shopownedcorpbank set earned_interest=0 where earned_interest is null");
db.query("update shopownedbank set talens=0 where talens is null");
db.query("update shopownedcorpbank set talens=0 where talens is null");
db.query("select shop_nr, keeper from shop");
while(db.fetchRow()){
if(mob_index[real_mobile(convertTo<int>(db["keeper"]))].spec==SPEC_BANKER){
shop_nr=convertTo<int>(db["shop_nr"]);
profit_sell=shop_index[shop_nr].profit_sell;
if(profit_sell==1.0)
continue;
in.query("select sum(talens) as talens from shopownedbank where shop_nr=%i",
shop_nr);
if(in.fetchRow())
pretalens=convertTo<int>(in["talens"]);
in.query("select sum(talens) as talens from shopownedcorpbank where shop_nr=%i",
shop_nr);
if(in.fetchRow())
pretalens+=convertTo<int>(in["talens"]);
// calculate interest
in.query("update shopownedbank set earned_interest=earned_interest + (talens * (%f / 365.0)) where shop_nr=%i", profit_sell, shop_nr);
// doll out earned interest that isn't fractional
in.query("update shopownedbank set talens=talens + trunc(earned_interest), earned_interest=earned_interest - trunc(earned_interest) where shop_nr=%i", shop_nr);
// calculate interest
in.query("update shopownedcorpbank set earned_interest=earned_interest + (talens * (%f / 365.0)) where shop_nr=%i", profit_sell, shop_nr);
// doll out earned interest that isn't fractional
in.query("update shopownedcorpbank set talens=talens + trunc(earned_interest), earned_interest=earned_interest - trunc(earned_interest) where shop_nr=%i", shop_nr);
in.query("select sum(talens) as talens from shopownedbank where shop_nr=%i",
shop_nr);
if(in.fetchRow())
posttalens=convertTo<int>(in["talens"]);
in.query("select sum(talens) as talens from shopownedcorpbank where shop_nr=%i",
shop_nr);
if(in.fetchRow())
posttalens+=convertTo<int>(in["talens"]);
if((posttalens-pretalens) !=0)
in.query("insert into shoplog values (%i, '%s', 'paying interest', 'all', %i, 0, 0, now(), 0)", shop_nr,
mob_index[real_mobile(convertTo<int>(db["keeper"]))].short_desc,
posttalens-pretalens);
}
}
}
int bankWithdraw(TBeing *ch, TMonster *myself, TMonster *teller, int shop_nr, int money)
{
TDatabase db(DB_SNEEZY);
int bankmoney;
if (!ch->isPc() || dynamic_cast<TMonster *>(ch)) {
teller->doTell(ch->getName(), "Stupid monster can't bank here!");
return TRUE;
}
db.query("select talens from shopownedbank where shop_nr=%i and player_id=%i", shop_nr, ch->getPlayerID());
if(!db.fetchRow()){
teller->doTell(ch->getName(), "You don't have an account here.");
teller->doTell(ch->getName(), "To open an account, type 'buy account'.");
teller->doTell(ch->getName(), "The new account fee is 100 talens.");
return FALSE;
} else
bankmoney = convertTo<int>(db["talens"]);
if (money > bankmoney) {
teller->doTell(ch->getName(), "You don't have enough in the bank for that!");
return TRUE;
} else if(myself->getMoney() < money){
teller->doTell(ch->getName(), "The bank doesn't have your funds available right now!");
return TRUE;
} else if (money <= 0) {
teller->doTell(ch->getName(), "Go away, you bother me.");
return TRUE;
}
teller->doTell(ch->getName(), "Thank you.");
myself->giveMoney(ch, money, GOLD_XFER);
myself->saveItems(fmt("%s/%d") % SHOPFILE_PATH % shop_nr);
db.query("update shopownedbank set talens=talens-%i where player_id=%i and shop_nr=%i", money, ch->getPlayerID(), shop_nr);
shoplog(shop_nr, ch, myself, "talens", -money, "withdrawal");
return TRUE;
}
int bankDeposit(TBeing *ch, TMonster *myself, TMonster *teller, int shop_nr, int money)
{
TDatabase db(DB_SNEEZY);
int bankmoney;
if (!ch->isPc() || dynamic_cast<TMonster *>(ch)) {
teller->doTell(ch->getName(), "Stupid monster can't bank here!");
return TRUE;
}
db.query("select talens from shopownedbank where shop_nr=%i and player_id=%i", shop_nr, ch->getPlayerID());
if(!db.fetchRow()){
teller->doTell(ch->getName(), "You don't have an account here.");
teller->doTell(ch->getName(), "To open an account, type 'buy account'.");
teller->doTell(ch->getName(), "The new account fee is 100 talens.");
return TRUE;
}
if (money <= 0) {
teller->doTell(ch->getName(), "Go away, you bother me.");
return TRUE;
} else if (money > ch->getMoney()) {
teller->doTell(ch->getName(), "You don't have enough for that!");
return TRUE;
}
teller->doTell(ch->getName(), "Thank you.");
ch->giveMoney(myself, money, GOLD_XFER);
myself->saveItems(fmt("%s/%d") % SHOPFILE_PATH % shop_nr);
db.query("update shopownedbank set talens=talens+%i where player_id=%i and shop_nr=%i", money, ch->getPlayerID(), shop_nr);
shoplog(shop_nr, ch, myself, "talens", money, "deposit");
db.query("select talens from shopownedbank where shop_nr=%i and player_id=%i", shop_nr, ch->getPlayerID());
if (!db.fetchRow()) {
teller->doTell(ch->getName(), "You really should not see me, this is an error...");
vlogf(LOG_BUG, fmt("Banking error, was unable to retrieve balance after a deposit: %s") % ch->getName());
return TRUE;
} else
bankmoney = convertTo<int>(db["talens"]);
teller->doTell(ch->getName(), fmt("...Your new balance is %i") % bankmoney);
return TRUE;
}
int bankBalance(TBeing *ch, TMonster *myself, TMonster *teller, int shop_nr)
{
TDatabase db(DB_SNEEZY);
int bankmoney;
db.query("select talens from shopownedbank where shop_nr=%i and player_id=%i", shop_nr, ch->getPlayerID());
if(!db.fetchRow()){
teller->doTell(ch->getName(), "You don't have an account here.");
teller->doTell(ch->getName(), "To open an account, type 'buy account'.");
teller->doTell(ch->getName(), "The new account fee is 100 talens.");
return TRUE;
} else
bankmoney = convertTo<int>(db["talens"]);
teller->doTell(ch->getName(), fmt("Your balance is %i.") % bankmoney);
return TRUE;
}
int bankBuyAccount(TBeing *ch, TMonster *myself, TMonster *teller, int shop_nr, int money)
{
TDatabase db(DB_SNEEZY);
if(ch->getMoney() < 100){
teller->doTell(ch->getName(), "You don't have enough money to open an account.");
return TRUE;
}
db.query("select talens from shopownedbank where player_id=%i and shop_nr=%i", ch->getPlayerID(), shop_nr);
if(db.fetchRow()){
teller->doTell(ch->getName(), "You already have an account.");
return TRUE;
}
db.query("insert into shopownedbank (player_id, shop_nr, talens) values (%i, %i, 0)", ch->getPlayerID(), shop_nr);
ch->giveMoney(myself, 100, GOLD_XFER);
shoplog(shop_nr, ch, myself, "talens", 100, "new account");
myself->saveItems(fmt("%s/%d") % SHOPFILE_PATH % shop_nr);
teller->doTell(ch->getName(), "Your account is now open and ready for use.");
return TRUE;
}
int banker(TBeing *ch, cmdTypeT cmd, const char *arg, TMonster *myself, TObj *)
{
int shop_nr, money=0;
TDatabase db(DB_SNEEZY);
if((cmd!=CMD_WITHDRAW &&
cmd!=CMD_DEPOSIT &&
cmd!=CMD_BUY &&
cmd!=CMD_LIST &&
cmd!=CMD_BALANCE &&
cmd!=CMD_WHISPER) ||
!ch || !myself)
return FALSE;
if(!(shop_nr=find_shop_nr(myself->number)))
return FALSE;
if(cmd==CMD_WHISPER)
return shopWhisper(ch, myself, shop_nr, arg);
if(cmd==CMD_LIST){
TShopOwned tso(shop_nr, myself, ch);
if(!tso.hasAccess(SHOPACCESS_LOGS)){
myself->doTell(ch->getName(), "Sorry, you don't have access to do that.");
return FALSE;
}
db.query("select p.name, b.talens from player p, shopownedbank b where b.shop_nr=%i and b.player_id=p.id union select c.name, b.talens from corporation c, shopownedcorpbank b where b.shop_nr=c.bank and b.shop_nr=%i and b.corp_id=c.corp_id order by talens desc", shop_nr, shop_nr);
sstring buf;
int empty=0;
while(db.fetchRow()){
if(convertTo<int>(db["talens"]) == 0)
empty++;
else
buf += fmt("<c>%s - %s talens.<1>\n\r") % db["name"] %
talenDisplay(convertTo<int>(db["talens"]));
}
buf += fmt("%i empty accounts.\n\r") % empty;
db.query("select (sb.c+sbc.c) as c, (sb.t+sbc.t) as t from (select count(*) as c, sum(talens) as t from shopownedbank where shop_nr=%i) sb, (select count(*) as c, sum(talens) as t from shopownedcorpbank where shop_nr=%i) sbc", shop_nr, shop_nr);
if(db.fetchRow()){
buf += fmt("%i total accounts, %s talens.\n\r") %
convertTo<int>(db["c"]) %
talenDisplay(convertTo<int>(db["t"]));
}
ch->desc->page_string(buf);
return TRUE;
}
if(cmd==CMD_BUY && sstring(arg).lower()=="account"){
money=convertTo<int>(arg);
return bankBuyAccount(ch, myself, myself, shop_nr, money);
} else if(cmd==CMD_BALANCE){
return bankBalance(ch, myself, myself, shop_nr);
} else if(cmd==CMD_WITHDRAW){
if(!strcmp(arg, "all"))
money=ch->getBank();
else
money=convertTo<int>(arg);
return bankWithdraw(ch, myself, myself, shop_nr, money);
} else if(cmd==CMD_DEPOSIT){
if(!strcmp(arg, "all"))
money=ch->getMoney();
else
money=convertTo<int>(arg);
return bankDeposit(ch, myself, myself, shop_nr, money);
}
return TRUE;
}
int bankRoom(TBeing *ch, cmdTypeT cmd, const char *arg, TRoom *rp)
{
TMonster *teller, *banker;
TBeing *t;
int tmp=130, money, shop_nr;
// tellers/branches can only do these commands
if(cmd!=CMD_WITHDRAW &&
cmd!=CMD_DEPOSIT &&
cmd!=CMD_BALANCE &&
cmd!=CMD_BUY)
return FALSE;
// find out which teller for this room
switch(rp->number){
case 31751:
case 31756:
case 2351:
tmp=31750;
break;
case 1295:
tmp=1295;
break;
case 3755:
tmp=3755;
break;
case 8756:
tmp=8756;
break;
}
// find the teller
for(t=character_list;t;t=t->next){
if(t->mobVnum()==tmp)
break;
}
if(!t || !(teller=dynamic_cast<TMonster *>(t)))
return FALSE;
// find out which banker for this room
switch(rp->number){
case 31751:
case 31756:
case 2351:
tmp=31765;
break;
case 1295:
tmp=1295;
break;
case 3755:
tmp=3755;
break;
case 8756:
tmp=8756;
break;
}
// find the banker
for(t=character_list;t;t=t->next){
if(t->mobVnum()==tmp)
break;
}
if(!t || !(banker=dynamic_cast<TMonster *>(t)))
return FALSE;
if(!(shop_nr=find_shop_nr(banker->number)))
return FALSE;
if(cmd==CMD_BUY && sstring(arg).lower()=="account"){
money=convertTo<int>(arg);
return bankBuyAccount(ch, banker, teller, shop_nr, money);
} else if(cmd==CMD_BALANCE){
return bankBalance(ch, banker, teller, shop_nr);
} else if(cmd==CMD_WITHDRAW){
if(!strcmp(arg, "all"))
money=ch->getBank();
else
money=convertTo<int>(arg);
return bankWithdraw(ch, banker, teller, shop_nr, money);
} else if(cmd==CMD_DEPOSIT){
if(!strcmp(arg, "all"))
money=ch->getMoney();
else
money=convertTo<int>(arg);
return bankDeposit(ch, banker, teller, shop_nr, money);
}
return FALSE;
}
<|endoftext|> |
<commit_before>#include "stdsneezy.h"
#include "database.h"
#include "shop.h"
#include "shopowned.h"
#include "process.h"
// procBankInterest
procBankInterest::procBankInterest(const int &p)
{
trigger_pulse=p;
name="procBankInterest";
}
void procBankInterest::run(int pulse) const
{
TDatabase db(DB_SNEEZY), in(DB_SNEEZY);
double profit_sell;
unsigned int shop_nr;
int pretalens=0, posttalens=0;
db.query("update shopownedbank set earned_interest=0 where earned_interest is null");
db.query("update shopownedcorpbank set earned_interest=0 where earned_interest is null");
db.query("update shopownedbank set talens=0 where talens is null");
db.query("update shopownedcorpbank set talens=0 where talens is null");
db.query("select shop_nr, keeper from shop");
while(db.fetchRow()){
if(mob_index[real_mobile(convertTo<int>(db["keeper"]))].spec==SPEC_BANKER){
shop_nr=convertTo<int>(db["shop_nr"]);
profit_sell=shop_index[shop_nr].profit_sell;
if(profit_sell==1.0)
continue;
in.query("select sum(talens) as talens from shopownedbank where shop_nr=%i",
shop_nr);
if(in.fetchRow())
pretalens=convertTo<int>(in["talens"]);
in.query("select sum(talens) as talens from shopownedcorpbank where shop_nr=%i",
shop_nr);
if(in.fetchRow())
pretalens+=convertTo<int>(in["talens"]);
// calculate interest
in.query("update shopownedbank set earned_interest=earned_interest + (talens * (%f / 365.0)) where shop_nr=%i", profit_sell, shop_nr);
// doll out earned interest that isn't fractional
in.query("update shopownedbank set talens=talens + truncate(earned_interest,0), earned_interest=earned_interest - trunc(earned_interest) where shop_nr=%i", shop_nr);
// calculate interest
in.query("update shopownedcorpbank set earned_interest=earned_interest + (talens * (%f / 365.0)) where shop_nr=%i", profit_sell, shop_nr);
// doll out earned interest that isn't fractional
in.query("update shopownedcorpbank set talens=talens + truncate(earned_interest,0), earned_interest=earned_interest - truncate(earned_interest,0) where shop_nr=%i", shop_nr);
in.query("select sum(talens) as talens from shopownedbank where shop_nr=%i",
shop_nr);
if(in.fetchRow())
posttalens=convertTo<int>(in["talens"]);
in.query("select sum(talens) as talens from shopownedcorpbank where shop_nr=%i",
shop_nr);
if(in.fetchRow())
posttalens+=convertTo<int>(in["talens"]);
if((posttalens-pretalens) !=0)
in.query("insert into shoplog values (%i, '%s', 'paying interest', 'all', %i, 0, 0, now(), 0)", shop_nr,
mob_index[real_mobile(convertTo<int>(db["keeper"]))].short_desc,
posttalens-pretalens);
}
}
}
int bankWithdraw(TBeing *ch, TMonster *myself, TMonster *teller, int shop_nr, int money)
{
TDatabase db(DB_SNEEZY);
int bankmoney;
if (!ch->isPc() || dynamic_cast<TMonster *>(ch)) {
teller->doTell(ch->getName(), "Stupid monster can't bank here!");
return TRUE;
}
db.query("select talens from shopownedbank where shop_nr=%i and player_id=%i", shop_nr, ch->getPlayerID());
if(!db.fetchRow()){
teller->doTell(ch->getName(), "You don't have an account here.");
teller->doTell(ch->getName(), "To open an account, type 'buy account'.");
teller->doTell(ch->getName(), "The new account fee is 100 talens.");
return FALSE;
} else
bankmoney = convertTo<int>(db["talens"]);
if (money > bankmoney) {
teller->doTell(ch->getName(), "You don't have enough in the bank for that!");
return TRUE;
} else if(myself->getMoney() < money){
teller->doTell(ch->getName(), "The bank doesn't have your funds available right now!");
return TRUE;
} else if (money <= 0) {
teller->doTell(ch->getName(), "Go away, you bother me.");
return TRUE;
}
teller->doTell(ch->getName(), "Thank you.");
myself->giveMoney(ch, money, GOLD_XFER);
myself->saveItems(fmt("%s/%d") % SHOPFILE_PATH % shop_nr);
db.query("update shopownedbank set talens=talens-%i where player_id=%i and shop_nr=%i", money, ch->getPlayerID(), shop_nr);
shoplog(shop_nr, ch, myself, "talens", -money, "withdrawal");
return TRUE;
}
int bankDeposit(TBeing *ch, TMonster *myself, TMonster *teller, int shop_nr, int money)
{
TDatabase db(DB_SNEEZY);
int bankmoney;
if (!ch->isPc() || dynamic_cast<TMonster *>(ch)) {
teller->doTell(ch->getName(), "Stupid monster can't bank here!");
return TRUE;
}
db.query("select talens from shopownedbank where shop_nr=%i and player_id=%i", shop_nr, ch->getPlayerID());
if(!db.fetchRow()){
teller->doTell(ch->getName(), "You don't have an account here.");
teller->doTell(ch->getName(), "To open an account, type 'buy account'.");
teller->doTell(ch->getName(), "The new account fee is 100 talens.");
return TRUE;
}
if (money <= 0) {
teller->doTell(ch->getName(), "Go away, you bother me.");
return TRUE;
} else if (money > ch->getMoney()) {
teller->doTell(ch->getName(), "You don't have enough for that!");
return TRUE;
}
teller->doTell(ch->getName(), "Thank you.");
ch->giveMoney(myself, money, GOLD_XFER);
myself->saveItems(fmt("%s/%d") % SHOPFILE_PATH % shop_nr);
db.query("update shopownedbank set talens=talens+%i where player_id=%i and shop_nr=%i", money, ch->getPlayerID(), shop_nr);
shoplog(shop_nr, ch, myself, "talens", money, "deposit");
db.query("select talens from shopownedbank where shop_nr=%i and player_id=%i", shop_nr, ch->getPlayerID());
if (!db.fetchRow()) {
teller->doTell(ch->getName(), "You really should not see me, this is an error...");
vlogf(LOG_BUG, fmt("Banking error, was unable to retrieve balance after a deposit: %s") % ch->getName());
return TRUE;
} else
bankmoney = convertTo<int>(db["talens"]);
teller->doTell(ch->getName(), fmt("...Your new balance is %i") % bankmoney);
return TRUE;
}
int bankBalance(TBeing *ch, TMonster *myself, TMonster *teller, int shop_nr)
{
TDatabase db(DB_SNEEZY);
int bankmoney;
db.query("select talens from shopownedbank where shop_nr=%i and player_id=%i", shop_nr, ch->getPlayerID());
if(!db.fetchRow()){
teller->doTell(ch->getName(), "You don't have an account here.");
teller->doTell(ch->getName(), "To open an account, type 'buy account'.");
teller->doTell(ch->getName(), "The new account fee is 100 talens.");
return TRUE;
} else
bankmoney = convertTo<int>(db["talens"]);
teller->doTell(ch->getName(), fmt("Your balance is %i.") % bankmoney);
return TRUE;
}
int bankBuyAccount(TBeing *ch, TMonster *myself, TMonster *teller, int shop_nr, int money)
{
TDatabase db(DB_SNEEZY);
if(ch->getMoney() < 100){
teller->doTell(ch->getName(), "You don't have enough money to open an account.");
return TRUE;
}
db.query("select talens from shopownedbank where player_id=%i and shop_nr=%i", ch->getPlayerID(), shop_nr);
if(db.fetchRow()){
teller->doTell(ch->getName(), "You already have an account.");
return TRUE;
}
db.query("insert into shopownedbank (player_id, shop_nr, talens) values (%i, %i, 0)", ch->getPlayerID(), shop_nr);
ch->giveMoney(myself, 100, GOLD_XFER);
shoplog(shop_nr, ch, myself, "talens", 100, "new account");
myself->saveItems(fmt("%s/%d") % SHOPFILE_PATH % shop_nr);
teller->doTell(ch->getName(), "Your account is now open and ready for use.");
return TRUE;
}
int banker(TBeing *ch, cmdTypeT cmd, const char *arg, TMonster *myself, TObj *)
{
int shop_nr, money=0;
TDatabase db(DB_SNEEZY);
if((cmd!=CMD_WITHDRAW &&
cmd!=CMD_DEPOSIT &&
cmd!=CMD_BUY &&
cmd!=CMD_LIST &&
cmd!=CMD_BALANCE &&
cmd!=CMD_WHISPER) ||
!ch || !myself)
return FALSE;
if(!(shop_nr=find_shop_nr(myself->number)))
return FALSE;
if(cmd==CMD_WHISPER)
return shopWhisper(ch, myself, shop_nr, arg);
if(cmd==CMD_LIST){
TShopOwned tso(shop_nr, myself, ch);
if(!tso.hasAccess(SHOPACCESS_LOGS)){
myself->doTell(ch->getName(), "Sorry, you don't have access to do that.");
return FALSE;
}
db.query("select p.name, b.talens from player p, shopownedbank b where b.shop_nr=%i and b.player_id=p.id union select c.name, b.talens from corporation c, shopownedcorpbank b where b.shop_nr=c.bank and b.shop_nr=%i and b.corp_id=c.corp_id order by talens desc", shop_nr, shop_nr);
sstring buf;
int empty=0;
while(db.fetchRow()){
if(convertTo<int>(db["talens"]) == 0)
empty++;
else
buf += fmt("<c>%s - %s talens.<1>\n\r") % db["name"] %
talenDisplay(convertTo<int>(db["talens"]));
}
buf += fmt("%i empty accounts.\n\r") % empty;
db.query("select (sb.c+sbc.c) as c, (sb.t+sbc.t) as t from (select count(*) as c, sum(talens) as t from shopownedbank where shop_nr=%i) sb, (select count(*) as c, sum(talens) as t from shopownedcorpbank where shop_nr=%i) sbc", shop_nr, shop_nr);
if(db.fetchRow()){
buf += fmt("%i total accounts, %s talens.\n\r") %
convertTo<int>(db["c"]) %
talenDisplay(convertTo<int>(db["t"]));
}
ch->desc->page_string(buf);
return TRUE;
}
if(cmd==CMD_BUY && sstring(arg).lower()=="account"){
money=convertTo<int>(arg);
return bankBuyAccount(ch, myself, myself, shop_nr, money);
} else if(cmd==CMD_BALANCE){
return bankBalance(ch, myself, myself, shop_nr);
} else if(cmd==CMD_WITHDRAW){
if(!strcmp(arg, "all"))
money=ch->getBank();
else
money=convertTo<int>(arg);
return bankWithdraw(ch, myself, myself, shop_nr, money);
} else if(cmd==CMD_DEPOSIT){
if(!strcmp(arg, "all"))
money=ch->getMoney();
else
money=convertTo<int>(arg);
return bankDeposit(ch, myself, myself, shop_nr, money);
}
return TRUE;
}
int bankRoom(TBeing *ch, cmdTypeT cmd, const char *arg, TRoom *rp)
{
TMonster *teller, *banker;
TBeing *t;
int tmp=130, money, shop_nr;
// tellers/branches can only do these commands
if(cmd!=CMD_WITHDRAW &&
cmd!=CMD_DEPOSIT &&
cmd!=CMD_BALANCE &&
cmd!=CMD_BUY)
return FALSE;
// find out which teller for this room
switch(rp->number){
case 31751:
case 31756:
case 2351:
tmp=31750;
break;
case 1295:
tmp=1295;
break;
case 3755:
tmp=3755;
break;
case 8756:
tmp=8756;
break;
}
// find the teller
for(t=character_list;t;t=t->next){
if(t->mobVnum()==tmp)
break;
}
if(!t || !(teller=dynamic_cast<TMonster *>(t)))
return FALSE;
// find out which banker for this room
switch(rp->number){
case 31751:
case 31756:
case 2351:
tmp=31765;
break;
case 1295:
tmp=1295;
break;
case 3755:
tmp=3755;
break;
case 8756:
tmp=8756;
break;
}
// find the banker
for(t=character_list;t;t=t->next){
if(t->mobVnum()==tmp)
break;
}
if(!t || !(banker=dynamic_cast<TMonster *>(t)))
return FALSE;
if(!(shop_nr=find_shop_nr(banker->number)))
return FALSE;
if(cmd==CMD_BUY && sstring(arg).lower()=="account"){
money=convertTo<int>(arg);
return bankBuyAccount(ch, banker, teller, shop_nr, money);
} else if(cmd==CMD_BALANCE){
return bankBalance(ch, banker, teller, shop_nr);
} else if(cmd==CMD_WITHDRAW){
if(!strcmp(arg, "all"))
money=ch->getBank();
else
money=convertTo<int>(arg);
return bankWithdraw(ch, banker, teller, shop_nr, money);
} else if(cmd==CMD_DEPOSIT){
if(!strcmp(arg, "all"))
money=ch->getMoney();
else
money=convertTo<int>(arg);
return bankDeposit(ch, banker, teller, shop_nr, money);
}
return FALSE;
}
<commit_msg>fixed another query<commit_after>#include "stdsneezy.h"
#include "database.h"
#include "shop.h"
#include "shopowned.h"
#include "process.h"
// procBankInterest
procBankInterest::procBankInterest(const int &p)
{
trigger_pulse=p;
name="procBankInterest";
}
void procBankInterest::run(int pulse) const
{
TDatabase db(DB_SNEEZY), in(DB_SNEEZY);
double profit_sell;
unsigned int shop_nr;
int pretalens=0, posttalens=0;
db.query("update shopownedbank set earned_interest=0 where earned_interest is null");
db.query("update shopownedcorpbank set earned_interest=0 where earned_interest is null");
db.query("update shopownedbank set talens=0 where talens is null");
db.query("update shopownedcorpbank set talens=0 where talens is null");
db.query("select shop_nr, keeper from shop");
while(db.fetchRow()){
if(mob_index[real_mobile(convertTo<int>(db["keeper"]))].spec==SPEC_BANKER){
shop_nr=convertTo<int>(db["shop_nr"]);
profit_sell=shop_index[shop_nr].profit_sell;
if(profit_sell==1.0)
continue;
in.query("select sum(talens) as talens from shopownedbank where shop_nr=%i",
shop_nr);
if(in.fetchRow())
pretalens=convertTo<int>(in["talens"]);
in.query("select sum(talens) as talens from shopownedcorpbank where shop_nr=%i",
shop_nr);
if(in.fetchRow())
pretalens+=convertTo<int>(in["talens"]);
// calculate interest
in.query("update shopownedbank set earned_interest=earned_interest + (talens * (%f / 365.0)) where shop_nr=%i", profit_sell, shop_nr);
// doll out earned interest that isn't fractional
in.query("update shopownedbank set talens=talens + truncate(earned_interest,0), earned_interest=earned_interest - truncate(earned_interest,0) where shop_nr=%i", shop_nr);
// calculate interest
in.query("update shopownedcorpbank set earned_interest=earned_interest + (talens * (%f / 365.0)) where shop_nr=%i", profit_sell, shop_nr);
// doll out earned interest that isn't fractional
in.query("update shopownedcorpbank set talens=talens + truncate(earned_interest,0), earned_interest=earned_interest - truncate(earned_interest,0) where shop_nr=%i", shop_nr);
in.query("select sum(talens) as talens from shopownedbank where shop_nr=%i",
shop_nr);
if(in.fetchRow())
posttalens=convertTo<int>(in["talens"]);
in.query("select sum(talens) as talens from shopownedcorpbank where shop_nr=%i",
shop_nr);
if(in.fetchRow())
posttalens+=convertTo<int>(in["talens"]);
if((posttalens-pretalens) !=0)
in.query("insert into shoplog values (%i, '%s', 'paying interest', 'all', %i, 0, 0, now(), 0)", shop_nr,
mob_index[real_mobile(convertTo<int>(db["keeper"]))].short_desc,
posttalens-pretalens);
}
}
}
int bankWithdraw(TBeing *ch, TMonster *myself, TMonster *teller, int shop_nr, int money)
{
TDatabase db(DB_SNEEZY);
int bankmoney;
if (!ch->isPc() || dynamic_cast<TMonster *>(ch)) {
teller->doTell(ch->getName(), "Stupid monster can't bank here!");
return TRUE;
}
db.query("select talens from shopownedbank where shop_nr=%i and player_id=%i", shop_nr, ch->getPlayerID());
if(!db.fetchRow()){
teller->doTell(ch->getName(), "You don't have an account here.");
teller->doTell(ch->getName(), "To open an account, type 'buy account'.");
teller->doTell(ch->getName(), "The new account fee is 100 talens.");
return FALSE;
} else
bankmoney = convertTo<int>(db["talens"]);
if (money > bankmoney) {
teller->doTell(ch->getName(), "You don't have enough in the bank for that!");
return TRUE;
} else if(myself->getMoney() < money){
teller->doTell(ch->getName(), "The bank doesn't have your funds available right now!");
return TRUE;
} else if (money <= 0) {
teller->doTell(ch->getName(), "Go away, you bother me.");
return TRUE;
}
teller->doTell(ch->getName(), "Thank you.");
myself->giveMoney(ch, money, GOLD_XFER);
myself->saveItems(fmt("%s/%d") % SHOPFILE_PATH % shop_nr);
db.query("update shopownedbank set talens=talens-%i where player_id=%i and shop_nr=%i", money, ch->getPlayerID(), shop_nr);
shoplog(shop_nr, ch, myself, "talens", -money, "withdrawal");
return TRUE;
}
int bankDeposit(TBeing *ch, TMonster *myself, TMonster *teller, int shop_nr, int money)
{
TDatabase db(DB_SNEEZY);
int bankmoney;
if (!ch->isPc() || dynamic_cast<TMonster *>(ch)) {
teller->doTell(ch->getName(), "Stupid monster can't bank here!");
return TRUE;
}
db.query("select talens from shopownedbank where shop_nr=%i and player_id=%i", shop_nr, ch->getPlayerID());
if(!db.fetchRow()){
teller->doTell(ch->getName(), "You don't have an account here.");
teller->doTell(ch->getName(), "To open an account, type 'buy account'.");
teller->doTell(ch->getName(), "The new account fee is 100 talens.");
return TRUE;
}
if (money <= 0) {
teller->doTell(ch->getName(), "Go away, you bother me.");
return TRUE;
} else if (money > ch->getMoney()) {
teller->doTell(ch->getName(), "You don't have enough for that!");
return TRUE;
}
teller->doTell(ch->getName(), "Thank you.");
ch->giveMoney(myself, money, GOLD_XFER);
myself->saveItems(fmt("%s/%d") % SHOPFILE_PATH % shop_nr);
db.query("update shopownedbank set talens=talens+%i where player_id=%i and shop_nr=%i", money, ch->getPlayerID(), shop_nr);
shoplog(shop_nr, ch, myself, "talens", money, "deposit");
db.query("select talens from shopownedbank where shop_nr=%i and player_id=%i", shop_nr, ch->getPlayerID());
if (!db.fetchRow()) {
teller->doTell(ch->getName(), "You really should not see me, this is an error...");
vlogf(LOG_BUG, fmt("Banking error, was unable to retrieve balance after a deposit: %s") % ch->getName());
return TRUE;
} else
bankmoney = convertTo<int>(db["talens"]);
teller->doTell(ch->getName(), fmt("...Your new balance is %i") % bankmoney);
return TRUE;
}
int bankBalance(TBeing *ch, TMonster *myself, TMonster *teller, int shop_nr)
{
TDatabase db(DB_SNEEZY);
int bankmoney;
db.query("select talens from shopownedbank where shop_nr=%i and player_id=%i", shop_nr, ch->getPlayerID());
if(!db.fetchRow()){
teller->doTell(ch->getName(), "You don't have an account here.");
teller->doTell(ch->getName(), "To open an account, type 'buy account'.");
teller->doTell(ch->getName(), "The new account fee is 100 talens.");
return TRUE;
} else
bankmoney = convertTo<int>(db["talens"]);
teller->doTell(ch->getName(), fmt("Your balance is %i.") % bankmoney);
return TRUE;
}
int bankBuyAccount(TBeing *ch, TMonster *myself, TMonster *teller, int shop_nr, int money)
{
TDatabase db(DB_SNEEZY);
if(ch->getMoney() < 100){
teller->doTell(ch->getName(), "You don't have enough money to open an account.");
return TRUE;
}
db.query("select talens from shopownedbank where player_id=%i and shop_nr=%i", ch->getPlayerID(), shop_nr);
if(db.fetchRow()){
teller->doTell(ch->getName(), "You already have an account.");
return TRUE;
}
db.query("insert into shopownedbank (player_id, shop_nr, talens) values (%i, %i, 0)", ch->getPlayerID(), shop_nr);
ch->giveMoney(myself, 100, GOLD_XFER);
shoplog(shop_nr, ch, myself, "talens", 100, "new account");
myself->saveItems(fmt("%s/%d") % SHOPFILE_PATH % shop_nr);
teller->doTell(ch->getName(), "Your account is now open and ready for use.");
return TRUE;
}
int banker(TBeing *ch, cmdTypeT cmd, const char *arg, TMonster *myself, TObj *)
{
int shop_nr, money=0;
TDatabase db(DB_SNEEZY);
if((cmd!=CMD_WITHDRAW &&
cmd!=CMD_DEPOSIT &&
cmd!=CMD_BUY &&
cmd!=CMD_LIST &&
cmd!=CMD_BALANCE &&
cmd!=CMD_WHISPER) ||
!ch || !myself)
return FALSE;
if(!(shop_nr=find_shop_nr(myself->number)))
return FALSE;
if(cmd==CMD_WHISPER)
return shopWhisper(ch, myself, shop_nr, arg);
if(cmd==CMD_LIST){
TShopOwned tso(shop_nr, myself, ch);
if(!tso.hasAccess(SHOPACCESS_LOGS)){
myself->doTell(ch->getName(), "Sorry, you don't have access to do that.");
return FALSE;
}
db.query("select p.name, b.talens from player p, shopownedbank b where b.shop_nr=%i and b.player_id=p.id union select c.name, b.talens from corporation c, shopownedcorpbank b where b.shop_nr=c.bank and b.shop_nr=%i and b.corp_id=c.corp_id order by talens desc", shop_nr, shop_nr);
sstring buf;
int empty=0;
while(db.fetchRow()){
if(convertTo<int>(db["talens"]) == 0)
empty++;
else
buf += fmt("<c>%s - %s talens.<1>\n\r") % db["name"] %
talenDisplay(convertTo<int>(db["talens"]));
}
buf += fmt("%i empty accounts.\n\r") % empty;
db.query("select (sb.c+sbc.c) as c, (sb.t+sbc.t) as t from (select count(*) as c, sum(talens) as t from shopownedbank where shop_nr=%i) sb, (select count(*) as c, sum(talens) as t from shopownedcorpbank where shop_nr=%i) sbc", shop_nr, shop_nr);
if(db.fetchRow()){
buf += fmt("%i total accounts, %s talens.\n\r") %
convertTo<int>(db["c"]) %
talenDisplay(convertTo<int>(db["t"]));
}
ch->desc->page_string(buf);
return TRUE;
}
if(cmd==CMD_BUY && sstring(arg).lower()=="account"){
money=convertTo<int>(arg);
return bankBuyAccount(ch, myself, myself, shop_nr, money);
} else if(cmd==CMD_BALANCE){
return bankBalance(ch, myself, myself, shop_nr);
} else if(cmd==CMD_WITHDRAW){
if(!strcmp(arg, "all"))
money=ch->getBank();
else
money=convertTo<int>(arg);
return bankWithdraw(ch, myself, myself, shop_nr, money);
} else if(cmd==CMD_DEPOSIT){
if(!strcmp(arg, "all"))
money=ch->getMoney();
else
money=convertTo<int>(arg);
return bankDeposit(ch, myself, myself, shop_nr, money);
}
return TRUE;
}
int bankRoom(TBeing *ch, cmdTypeT cmd, const char *arg, TRoom *rp)
{
TMonster *teller, *banker;
TBeing *t;
int tmp=130, money, shop_nr;
// tellers/branches can only do these commands
if(cmd!=CMD_WITHDRAW &&
cmd!=CMD_DEPOSIT &&
cmd!=CMD_BALANCE &&
cmd!=CMD_BUY)
return FALSE;
// find out which teller for this room
switch(rp->number){
case 31751:
case 31756:
case 2351:
tmp=31750;
break;
case 1295:
tmp=1295;
break;
case 3755:
tmp=3755;
break;
case 8756:
tmp=8756;
break;
}
// find the teller
for(t=character_list;t;t=t->next){
if(t->mobVnum()==tmp)
break;
}
if(!t || !(teller=dynamic_cast<TMonster *>(t)))
return FALSE;
// find out which banker for this room
switch(rp->number){
case 31751:
case 31756:
case 2351:
tmp=31765;
break;
case 1295:
tmp=1295;
break;
case 3755:
tmp=3755;
break;
case 8756:
tmp=8756;
break;
}
// find the banker
for(t=character_list;t;t=t->next){
if(t->mobVnum()==tmp)
break;
}
if(!t || !(banker=dynamic_cast<TMonster *>(t)))
return FALSE;
if(!(shop_nr=find_shop_nr(banker->number)))
return FALSE;
if(cmd==CMD_BUY && sstring(arg).lower()=="account"){
money=convertTo<int>(arg);
return bankBuyAccount(ch, banker, teller, shop_nr, money);
} else if(cmd==CMD_BALANCE){
return bankBalance(ch, banker, teller, shop_nr);
} else if(cmd==CMD_WITHDRAW){
if(!strcmp(arg, "all"))
money=ch->getBank();
else
money=convertTo<int>(arg);
return bankWithdraw(ch, banker, teller, shop_nr, money);
} else if(cmd==CMD_DEPOSIT){
if(!strcmp(arg, "all"))
money=ch->getMoney();
else
money=convertTo<int>(arg);
return bankDeposit(ch, banker, teller, shop_nr, money);
}
return FALSE;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
SneezyMUD++ - All rights reserved, SneezyMUD Coding Team.
"spec_mobs_goring.cc"
All functions and routines related to the Boar/Tusk Goring code.
Created 10/20/99 - Lapsos(William A. Perrotto III)
******************************************************************************/
#include "stdsneezy.h"
int tuskGoring(TBeing *ch, cmdTypeT tCmd, const char *tArg, TMonster *tMyself, TObj *tObj)
{
TBeing *tVictim = tMyself->fight();
if (tCmd != CMD_MOB_COMBAT || !tMyself ||
!tMyself->awake() || tMyself->spelltask ||
!tVictim || tVictim->riding ||
tVictim->getPosition() > POSITION_STANDING ||
!tMyself->sameRoom(tVictim) || ::number(0, 7) ||
tMyself->getPosition() < POSITION_STANDING)
return FALSE;
if (!tVictim->isAgile(0) && ::number(0, 4)) {
act("$n charges into $N, impaling him fiercly!",
TRUE, tMyself, NULL, tVictim, TO_NOTVICT);
act("$n barrels down on you, impaling you painfully!",
TRUE, tMyself, NULL, tVictim, TO_VICT);
act("You charge down upon $N, impaling them!",
TRUE, tMyself, NULL, tVictim, TO_CHAR);
int tDamage = max(10, (int) (((tMyself->GetMaxLevel() * 5) + ::number(-10, 10)) / 2));
if (tMyself->reconcileDamage(tVictim, tDamage, DAMAGE_RAMMED) == -1) {
delete tVictim;
tVictim = NULL;
return TRUE;
}
tMyself->cantHit += tMyself->loseRound(1);
tVictim->cantHit += tVictim->loseRound(2);
tVictim->setPosition(POSITION_SITTING);
return TRUE;
} else {
act("$n charges towards $N, but they easily dodges them.",
TRUE, tMyself, NULL, tVictim, TO_NOTVICT);
act("$n barrels down on you, but you easily dodge them.",
TRUE, tMyself, NULL, tVictim, TO_VICT);
act("You charge down upon $N, but they easily dodge you making you look the ass!",
TRUE, tMyself, NULL, tVictim, TO_CHAR);
}
return TRUE;
}
<commit_msg>fixed sameRoom args<commit_after>/*****************************************************************************
SneezyMUD++ - All rights reserved, SneezyMUD Coding Team.
"spec_mobs_goring.cc"
All functions and routines related to the Boar/Tusk Goring code.
******************************************************************************/
#include "stdsneezy.h"
int tuskGoring(TBeing *ch, cmdTypeT tCmd, const char *tArg, TMonster *tMyself, TObj *tObj)
{
TBeing *tVictim = tMyself->fight();
if (tCmd != CMD_MOB_COMBAT || !tMyself ||
!tMyself->awake() || tMyself->spelltask ||
!tVictim || tVictim->riding ||
tVictim->getPosition() > POSITION_STANDING ||
!tMyself->sameRoom(*tVictim) || ::number(0, 7) ||
tMyself->getPosition() < POSITION_STANDING)
return FALSE;
if (!tVictim->isAgile(0) && ::number(0, 4)) {
act("$n charges into $N, impaling him fiercly!",
TRUE, tMyself, NULL, tVictim, TO_NOTVICT);
act("$n barrels down on you, impaling you painfully!",
TRUE, tMyself, NULL, tVictim, TO_VICT);
act("You charge down upon $N, impaling them!",
TRUE, tMyself, NULL, tVictim, TO_CHAR);
int tDamage = max(10, (int) (((tMyself->GetMaxLevel() * 5) + ::number(-10, 10)) / 2));
if (tMyself->reconcileDamage(tVictim, tDamage, DAMAGE_RAMMED) == -1) {
delete tVictim;
tVictim = NULL;
return TRUE;
}
tMyself->cantHit += tMyself->loseRound(1);
tVictim->cantHit += tVictim->loseRound(2);
tVictim->setPosition(POSITION_SITTING);
return TRUE;
} else {
act("$n charges towards $N, but they easily dodges them.",
TRUE, tMyself, NULL, tVictim, TO_NOTVICT);
act("$n barrels down on you, but you easily dodge them.",
TRUE, tMyself, NULL, tVictim, TO_VICT);
act("You charge down upon $N, but they easily dodge you making you look the ass!",
TRUE, tMyself, NULL, tVictim, TO_CHAR);
}
return TRUE;
}
<|endoftext|> |
<commit_before>#include "stdsneezy.h"
#include "spec_objs_sweeps.h"
#include "disc_sorcery.h"
int sweepsScratch(TBeing *ch, cmdTypeT cmd, const char *arg, TObj *o, TObj *)
{
if (cmd != CMD_SHAKE)
return FALSE;
sstring buf;
buf=sstring(arg).word(0);
if (!isname(buf, o->name) || !is_abbrev(buf, "tile"))
return FALSE;
if (!o || !ch)
return FALSE;
TBeing *cho;
cho = ch;
if (!(ch = dynamic_cast<TBeing *>(o->equippedBy)))
{
cho->sendTo("Maybe you should hold an unused tile in your hand.\n\r");
return TRUE;
}
TObj *tile = NULL;
if (!(tile = dynamic_cast<TObj *>(ch->equipment[HOLD_RIGHT])) &&
!(tile = dynamic_cast<TObj *>(ch->equipment[HOLD_LEFT])))
{
act("You must hold the tile before trying to shake it.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
return TRUE;
}
act("$n shakes a tile vigorously.",TRUE,ch,NULL,NULL,TO_ROOM,NULL);
act("You shake the tile vigorously.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
int roll = ::number(1,100);
sstring buf3, buf4;
// About 10,000 mobs load currently
if (roll == 1 || roll == 2)
buf3 = "C";
else if (roll == 3 || roll ==4)
buf3 = "L";
else if (roll == 5 || roll == 6)
buf3 = "Y";
else if (roll == 7 || roll == 8)
buf3 = "H";
else if (roll == 9 || roll == 10)
buf3 = "N";
else if (roll == 11 || roll == 12)
buf3 = "T";
else if (roll > 12 && roll <= 20)
buf3 = "S";
else if (roll > 20 && roll <= 40)
buf3 = "M";
else if (roll > 40 && roll <= 70)
buf3 = "O";
else
buf3 = "P";
ch->sendTo("As you watch, the blank face of the tile blurs momentarily.\n\r");
buf4 = fmt("The letter <Y>%s<z> appears.") % buf3;
// delete tile, load tile with join proc
// need to know what hand to hold it in tile->eq_pos
TObj *newtile = NULL;
if (!(newtile = read_object(TILEVNUM_SHAKEN, VIRTUAL))) {
vlogf(LOG_LOW, fmt("could not read obj %d in spec_objs_sweeps.cc") %
TILEVNUM_SHAKEN);
}
if (newtile) { // delete tile and load item
wearSlotT pos = o->eq_pos;
delete o;
o = NULL;
sstring buf5 = fmt("tile %s") % buf3;
sstring buf6 = fmt("an <b>obsidian tile<z> inscribed with <Y>%s<z>") % buf3;
newtile->swapToStrung();
newtile->name = mud_str_dup(buf5);
newtile->shortDescr = mud_str_dup(buf6);
act(buf4,TRUE,ch,NULL,NULL,TO_CHAR,NULL);
newtile->obj_flags.decay_time = o->obj_flags.decay_time;
ch->equipChar(newtile, pos, SILENT_YES);
} else {
ch->sendTo("Something has gone horribly wrong with your tile.\n\r");
vlogf(LOG_LOW, "Error in tile shake - no new tile.\n\r");
}
return TRUE;
}
int sweepsSplitJoin(TBeing *ch, cmdTypeT cmd, const char *arg, TObj *o, TObj *) {
if (cmd != CMD_COMBINE && cmd != CMD_SPLIT)
return FALSE;
sstring buf, buf4, buf5, buf6;
buf=sstring(arg).word(0);
if (!is_abbrev(buf, "tiles"))
return FALSE;
if (!o || !ch)
return FALSE;
TBeing *cho;
cho = ch;
if (!(ch = dynamic_cast<TBeing *>(o->equippedBy)))
{
cho->sendTo("Maybe you should hold the tile in your hand.\n\r");
return TRUE;
}
TObj *tile1 = NULL;
TObj *tile2 = NULL;
if (cmd == CMD_COMBINE)
{
if (!(tile1 = dynamic_cast<TObj *>(ch->equipment[HOLD_RIGHT])) ||
!(tile2 = dynamic_cast<TObj *>(ch->equipment[HOLD_LEFT])) ||
!(tile1->spec == SPEC_SPLIT_JOIN) ||
!(tile2->spec == SPEC_SPLIT_JOIN))
{
act("You must hold two tiles, on in each hand, in order to combine them.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
return TRUE;
}
//return quietly if the proc is firing from both hands
if (o == ch->equipment[HOLD_LEFT])
return TRUE;
act("$n fiddles with some tiles.",TRUE,ch,NULL,NULL,TO_ROOM,NULL);
act("You fiddle with some tiles.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
sstring name1 = sstring(tile1->name).word(1);
sstring name2 = sstring(tile2->name).word(1);
if (name1 == "" || name2 == "") {
act("Nothing happens.",TRUE,ch,NULL,NULL,TO_ROOM,NULL);
act("One of both of your tiles is faulty. Nothing happens.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
return TRUE;
}
act("<R>*SNAP*<z>\n\r$n lays one tile on top of another and they merge into one.",TRUE,ch,NULL,NULL,TO_ROOM,NULL);
act("<R>*SNAP*<z>\n\rYou lay one tile on top of the other and they merge into one.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
delete tile2;
sstring newname = fmt("%s%s") % name1 % name2;
ch->sendTo("As you watch, the face of the tile blurs momentarily.\n\r");
buf4 = fmt("The letters <Y>%s<z> appear.") % newname;
buf5 = fmt("tile %s") % newname;
buf6 = fmt("an <b>obsidian tile<z> inscribed with <Y>%s<z>") % newname;
tile1->swapToStrung();
tile1->name = mud_str_dup(buf5);
tile1->shortDescr = mud_str_dup(buf6);
act(buf4, TRUE,ch,NULL,NULL,TO_CHAR,NULL);
if (newname == "POP") {
act("The tile vanishes.", TRUE,ch,NULL,NULL,TO_CHAR,NULL);
act("The tile vanishes.", TRUE,ch,NULL,NULL,TO_ROOM,NULL);
delete tile1;
vlogf(LOG_LOW, fmt("%s has just been teleported by the sneezy sweeps") %
ch->getName());
teleport(ch,ch,50,100);
} else {
int newobjn = 0;
if (newname == "PCH") {
newobjn = STATS_POTION;
} else if (newname == "PLN") {
newobjn = LEARNING_POTION;
} else if (newname == "PMS") {
newobjn = MYSTERY_POTION;
} else if (newname == "PYT") {
newobjn = YOUTH_POTION;
} else if (newname == "POO") {
newobjn = OBJ_PILE_OFFAL;
} else if (newname == "MOP") {
newobjn = 9083; // a mop
}
if (newobjn > 0) {
TObj *newobj = NULL;
if (!(newobj = read_object(newobjn, VIRTUAL))) {
vlogf(LOG_LOW, fmt("could not read obj %d in spec_objs_sweeps.cc") %
newobjn);
}
if (newobj) { // delete tile and load item
delete tile1;
act("The tile vanishes, and $p appears in your hand.",
TRUE,ch,newobj,NULL,TO_CHAR,NULL);
act("The tile vanishes, and $p appears in $n's hand.",
TRUE,ch,newobj,NULL,TO_ROOM,NULL);
ch->equipChar(newobj, HOLD_RIGHT, SILENT_YES);
vlogf(LOG_LOW, fmt("%s has just won %s in the sneezy sweeps") %
ch->getName() % newobj->getName());
}
}
}
} else if (cmd == CMD_SPLIT) {
TThing *left=NULL, *right=NULL;
tile1 = dynamic_cast<TObj *>(ch->equipment[HOLD_RIGHT]);
if (!tile1)
tile1 = dynamic_cast<TObj *>(ch->equipment[HOLD_LEFT]);
left = ch->equipment[HOLD_LEFT];
right = ch->equipment[HOLD_RIGHT];
if ( ( left && right ) || !tile1 )
{
act("You must be holding a tile, with the other hand empty, to split the tile.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
return TRUE;
}
if (!(tile2 = read_object(TILEVNUM_SHAKEN, VIRTUAL) ))
{
vlogf(LOG_BUG, fmt("spec_objs_sweeps.cc, problem loading object %d") % TILEVNUM_SHAKEN);
act("Nothing happens.",TRUE,ch,NULL,NULL,TO_ROOM,NULL);
act("Nothing happens.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
return TRUE;
}
act("$n fiddles with a tile.",TRUE,ch,NULL,NULL,TO_ROOM,NULL);
act("You fiddle with a tile.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
sstring name1 = sstring(tile1->name).word(1);
sstring name2 = name1.substr(name1.length()-1, name1.length());
name1 = name1.substr(0, (name1.length())-1);
if (name1 == "" || name2 == "") {
act("Nothing happens.",TRUE,ch,NULL,NULL,TO_ROOM,NULL);
act("You can't split a tile with only one letter on it.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
return TRUE;
}
act("<R>*SNAP*<z>\n\r$n tugs at a tile and it separates into two.",TRUE,ch,NULL,NULL,TO_ROOM,NULL);
act("<R>*SNAP*<z>\n\rYou tug at a tile and it separates into two.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
// deal with tile1
buf5 = fmt("tile %s") % name1;
buf6 = fmt("an <b>obsidian tile<z> inscribed with <Y>%s<z>") % name1;
tile1->swapToStrung();
tile1->name = mud_str_dup(buf5);
tile1->shortDescr = mud_str_dup(buf6);
// deal with tile2 - new object
sstring buf5 = fmt("tile %s") % name2;
sstring buf6 = fmt("an <b>obsidian tile<z> inscribed with <Y>%s<z>") % name2;
tile2->swapToStrung();
tile2->name = mud_str_dup(buf5);
tile2->shortDescr = mud_str_dup(buf6);
tile2->obj_flags.decay_time = tile1->obj_flags.decay_time;
if (!left)
{
ch->equipChar(tile2, HOLD_LEFT, SILENT_YES);
} else if (!right) {
ch->equipChar(tile2, HOLD_RIGHT, SILENT_YES);
} else {
vlogf(LOG_BUG, "Somehow got to end of splitting tiles in spec_objs_sweeps.cc with both hands full.");
}
}
return TRUE;
}
<commit_msg>Hopefully fixed crash bug associated with tile shaking on special proc 133, sweeps object, where tiles were deleted before the mud finished creating the new tile<commit_after>#include "stdsneezy.h"
#include "spec_objs_sweeps.h"
#include "disc_sorcery.h"
int sweepsScratch(TBeing *ch, cmdTypeT cmd, const char *arg, TObj *o, TObj *)
{
if (cmd != CMD_SHAKE)
return FALSE;
sstring buf;
buf=sstring(arg).word(0);
if (!isname(buf, o->name) || !is_abbrev(buf, "tile"))
return FALSE;
if (!o || !ch)
return FALSE;
TBeing *cho;
cho = ch;
if (!(ch = dynamic_cast<TBeing *>(o->equippedBy)))
{
cho->sendTo("Maybe you should hold an unused tile in your hand.\n\r");
return TRUE;
}
TObj *tile = NULL;
if (!(tile = dynamic_cast<TObj *>(ch->equipment[HOLD_RIGHT])) &&
!(tile = dynamic_cast<TObj *>(ch->equipment[HOLD_LEFT])))
{
act("You must hold the tile before trying to shake it.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
return TRUE;
}
act("$n shakes a tile vigorously.",TRUE,ch,NULL,NULL,TO_ROOM,NULL);
act("You shake the tile vigorously.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
int roll = ::number(1,100);
sstring buf3, buf4;
// About 10,000 mobs load currently
if (roll == 1 || roll == 2)
buf3 = "C";
else if (roll == 3 || roll ==4)
buf3 = "L";
else if (roll == 5 || roll == 6)
buf3 = "Y";
else if (roll == 7 || roll == 8)
buf3 = "H";
else if (roll == 9 || roll == 10)
buf3 = "N";
else if (roll == 11 || roll == 12)
buf3 = "T";
else if (roll > 12 && roll <= 20)
buf3 = "S";
else if (roll > 20 && roll <= 40)
buf3 = "M";
else if (roll > 40 && roll <= 70)
buf3 = "O";
else
buf3 = "P";
ch->sendTo("As you watch, the blank face of the tile blurs momentarily.\n\r");
buf4 = fmt("The letter <Y>%s<z> appears.") % buf3;
// delete tile, load tile with join proc
// need to know what hand to hold it in tile->eq_pos
TObj *newtile = NULL;
if (!(newtile = read_object(TILEVNUM_SHAKEN, VIRTUAL))) {
vlogf(LOG_LOW, fmt("could not read obj %d in spec_objs_sweeps.cc") %
TILEVNUM_SHAKEN);
}
if (newtile) { // delete tile and load item
wearSlotT pos = o->eq_pos;
sstring buf5 = fmt("tile %s") % buf3;
sstring buf6 = fmt("an <b>obsidian tile<z> inscribed with <Y>%s<z>") % buf3;
newtile->swapToStrung();
newtile->name = mud_str_dup(buf5);
newtile->shortDescr = mud_str_dup(buf6);
act(buf4,TRUE,ch,NULL,NULL,TO_CHAR,NULL);
newtile->obj_flags.decay_time = o->obj_flags.decay_time;
delete o;
o = NULL;
ch->equipChar(newtile, pos, SILENT_YES);
} else {
ch->sendTo("Something has gone horribly wrong with your tile.\n\r");
vlogf(LOG_LOW, "Error in tile shake - no new tile.\n\r");
}
return TRUE;
}
int sweepsSplitJoin(TBeing *ch, cmdTypeT cmd, const char *arg, TObj *o, TObj *) {
if (cmd != CMD_COMBINE && cmd != CMD_SPLIT)
return FALSE;
sstring buf, buf4, buf5, buf6;
buf=sstring(arg).word(0);
if (!is_abbrev(buf, "tiles"))
return FALSE;
if (!o || !ch)
return FALSE;
TBeing *cho;
cho = ch;
if (!(ch = dynamic_cast<TBeing *>(o->equippedBy)))
{
cho->sendTo("Maybe you should hold the tile in your hand.\n\r");
return TRUE;
}
TObj *tile1 = NULL;
TObj *tile2 = NULL;
if (cmd == CMD_COMBINE)
{
if (!(tile1 = dynamic_cast<TObj *>(ch->equipment[HOLD_RIGHT])) ||
!(tile2 = dynamic_cast<TObj *>(ch->equipment[HOLD_LEFT])) ||
!(tile1->spec == SPEC_SPLIT_JOIN) ||
!(tile2->spec == SPEC_SPLIT_JOIN))
{
act("You must hold two tiles, on in each hand, in order to combine them.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
return TRUE;
}
//return quietly if the proc is firing from both hands
if (o == ch->equipment[HOLD_LEFT])
return TRUE;
act("$n fiddles with some tiles.",TRUE,ch,NULL,NULL,TO_ROOM,NULL);
act("You fiddle with some tiles.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
sstring name1 = sstring(tile1->name).word(1);
sstring name2 = sstring(tile2->name).word(1);
if (name1 == "" || name2 == "") {
act("Nothing happens.",TRUE,ch,NULL,NULL,TO_ROOM,NULL);
act("One of both of your tiles is faulty. Nothing happens.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
return TRUE;
}
act("<R>*SNAP*<z>\n\r$n lays one tile on top of another and they merge into one.",TRUE,ch,NULL,NULL,TO_ROOM,NULL);
act("<R>*SNAP*<z>\n\rYou lay one tile on top of the other and they merge into one.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
delete tile2;
sstring newname = fmt("%s%s") % name1 % name2;
ch->sendTo("As you watch, the face of the tile blurs momentarily.\n\r");
buf4 = fmt("The letters <Y>%s<z> appear.") % newname;
buf5 = fmt("tile %s") % newname;
buf6 = fmt("an <b>obsidian tile<z> inscribed with <Y>%s<z>") % newname;
tile1->swapToStrung();
tile1->name = mud_str_dup(buf5);
tile1->shortDescr = mud_str_dup(buf6);
act(buf4, TRUE,ch,NULL,NULL,TO_CHAR,NULL);
if (newname == "POP") {
act("The tile vanishes.", TRUE,ch,NULL,NULL,TO_CHAR,NULL);
act("The tile vanishes.", TRUE,ch,NULL,NULL,TO_ROOM,NULL);
delete tile1;
vlogf(LOG_LOW, fmt("%s has just been teleported by the sneezy sweeps") %
ch->getName());
teleport(ch,ch,50,100);
} else {
int newobjn = 0;
if (newname == "PCH") {
newobjn = STATS_POTION;
} else if (newname == "PLN") {
newobjn = LEARNING_POTION;
} else if (newname == "PMS") {
newobjn = MYSTERY_POTION;
} else if (newname == "PYT") {
newobjn = YOUTH_POTION;
} else if (newname == "POO") {
newobjn = OBJ_PILE_OFFAL;
} else if (newname == "MOP") {
newobjn = 9083; // a mop
}
if (newobjn > 0) {
TObj *newobj = NULL;
if (!(newobj = read_object(newobjn, VIRTUAL))) {
vlogf(LOG_LOW, fmt("could not read obj %d in spec_objs_sweeps.cc") %
newobjn);
}
if (newobj) { // delete tile and load item
delete tile1;
act("The tile vanishes, and $p appears in your hand.",
TRUE,ch,newobj,NULL,TO_CHAR,NULL);
act("The tile vanishes, and $p appears in $n's hand.",
TRUE,ch,newobj,NULL,TO_ROOM,NULL);
ch->equipChar(newobj, HOLD_RIGHT, SILENT_YES);
vlogf(LOG_LOW, fmt("%s has just won %s in the sneezy sweeps") %
ch->getName() % newobj->getName());
}
}
}
} else if (cmd == CMD_SPLIT) {
TThing *left=NULL, *right=NULL;
tile1 = dynamic_cast<TObj *>(ch->equipment[HOLD_RIGHT]);
if (!tile1)
tile1 = dynamic_cast<TObj *>(ch->equipment[HOLD_LEFT]);
left = ch->equipment[HOLD_LEFT];
right = ch->equipment[HOLD_RIGHT];
if ( ( left && right ) || !tile1 )
{
act("You must be holding a tile, with the other hand empty, to split the tile.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
return TRUE;
}
if (!(tile2 = read_object(TILEVNUM_SHAKEN, VIRTUAL) ))
{
vlogf(LOG_BUG, fmt("spec_objs_sweeps.cc, problem loading object %d") % TILEVNUM_SHAKEN);
act("Nothing happens.",TRUE,ch,NULL,NULL,TO_ROOM,NULL);
act("Nothing happens.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
return TRUE;
}
act("$n fiddles with a tile.",TRUE,ch,NULL,NULL,TO_ROOM,NULL);
act("You fiddle with a tile.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
sstring name1 = sstring(tile1->name).word(1);
sstring name2 = name1.substr(name1.length()-1, name1.length());
name1 = name1.substr(0, (name1.length())-1);
if (name1 == "" || name2 == "") {
act("Nothing happens.",TRUE,ch,NULL,NULL,TO_ROOM,NULL);
act("You can't split a tile with only one letter on it.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
return TRUE;
}
act("<R>*SNAP*<z>\n\r$n tugs at a tile and it separates into two.",TRUE,ch,NULL,NULL,TO_ROOM,NULL);
act("<R>*SNAP*<z>\n\rYou tug at a tile and it separates into two.",TRUE,ch,NULL,NULL,TO_CHAR,NULL);
// deal with tile1
buf5 = fmt("tile %s") % name1;
buf6 = fmt("an <b>obsidian tile<z> inscribed with <Y>%s<z>") % name1;
tile1->swapToStrung();
tile1->name = mud_str_dup(buf5);
tile1->shortDescr = mud_str_dup(buf6);
// deal with tile2 - new object
sstring buf5 = fmt("tile %s") % name2;
sstring buf6 = fmt("an <b>obsidian tile<z> inscribed with <Y>%s<z>") % name2;
tile2->swapToStrung();
tile2->name = mud_str_dup(buf5);
tile2->shortDescr = mud_str_dup(buf6);
tile2->obj_flags.decay_time = tile1->obj_flags.decay_time;
if (!left)
{
ch->equipChar(tile2, HOLD_LEFT, SILENT_YES);
} else if (!right) {
ch->equipChar(tile2, HOLD_RIGHT, SILENT_YES);
} else {
vlogf(LOG_BUG, "Somehow got to end of splitting tiles in spec_objs_sweeps.cc with both hands full.");
}
}
return TRUE;
}
<|endoftext|> |
<commit_before>#include "os/file_access.h"
#include "oamlGodotModule.h"
void oamlGodotModule::set_mix_rate(int p_rate) {
if (oaml == NULL)
return;
oaml->SetAudioFormat(p_rate, 2, 4, true);
}
bool oamlGodotModule::mix(AudioFrame *p_buffer, int p_frames) {
if (oaml == NULL)
return true;
zeromem(p_buffer, p_frames*sizeof(AudioFrame));
lock->lock();
oaml->MixToBuffer(p_buffer, p_frames*2);
lock->unlock();
return true;
}
// Called from audio thread
void oamlGodotModule::_mix_audio() {
AudioFrame *buffer = mix_buffer.ptrw();
int buffer_size = mix_buffer.size();
if (!mix(buffer, buffer_size))
return;
AudioFrame *target = AudioServer::get_singleton()->thread_get_channel_mix_buffer(0, 0);
for (int j = 0; j < buffer_size; j++) {
target[j] += buffer[j];
}
}
int oamlGodotModule::sp_get_channel_count() const {
return 2;
}
void oamlGodotModule::AddTension(int value) {
if (oaml == NULL)
return;
oaml->AddTension(value);
}
void oamlGodotModule::EnableDynamicCompressor(bool enable, double thresholdDb, double ratio) {
if (oaml == NULL)
return;
oaml->EnableDynamicCompressor(enable, thresholdDb, ratio);
}
String oamlGodotModule::GetPlayingInfo() {
if (oaml == NULL)
return "";
return String(oaml->GetPlayingInfo());
}
float oamlGodotModule::GetVolume() {
if (oaml == NULL)
return 1.0f;
return oaml->GetVolume();
}
void oamlGodotModule::Init(String defsFilename) {
if (oaml == NULL)
return;
oaml->Init(defsFilename.ascii().get_data());
}
void oamlGodotModule::InitString(String defs) {
if (oaml == NULL)
return;
oaml->InitString(defs.ascii());
}
bool oamlGodotModule::IsPaused() {
if (oaml == NULL)
return true;
return oaml->IsPaused();
}
bool oamlGodotModule::IsPlaying() {
if (oaml == NULL)
return false;
return oaml->IsPlaying();
}
bool oamlGodotModule::IsTrackPlaying(String name) {
if (oaml == NULL)
return false;
return oaml->IsTrackPlaying(name.ascii());
}
void oamlGodotModule::LoadTrack(String name) {
if (oaml == NULL)
return;
lock->lock();
oaml->LoadTrack(name.ascii());
lock->unlock();
}
float oamlGodotModule::LoadTrackProgress(String name) {
if (oaml == NULL)
return -1.f;
lock->lock();
float ret = oaml->LoadTrackProgress(name.ascii());
lock->unlock();
return ret;
}
void oamlGodotModule::Pause() {
if (oaml == NULL)
return;
lock->lock();
oaml->Pause();
lock->unlock();
}
void oamlGodotModule::PlayTrack(String name) {
if (oaml == NULL)
return;
lock->lock();
oaml->PlayTrack(name.ascii());
lock->unlock();
}
void oamlGodotModule::PlayTrackWithStringRandom(String str) {
if (oaml == NULL)
return;
lock->lock();
oaml->PlayTrackWithStringRandom(str.ascii());
lock->unlock();
}
void oamlGodotModule::PlayTrackByGroupRandom(String group) {
if (oaml == NULL)
return;
lock->lock();
oaml->PlayTrackByGroupRandom(group.ascii());
lock->unlock();
}
void oamlGodotModule::PlayTrackByGroupAndSubgroupRandom(String group, String subgroup) {
if (oaml == NULL)
return;
lock->lock();
oaml->PlayTrackByGroupAndSubgroupRandom(group.ascii(), subgroup.ascii());
lock->unlock();
}
void oamlGodotModule::Resume() {
if (oaml == NULL)
return;
lock->lock();
oaml->Resume();
lock->unlock();
}
void oamlGodotModule::SetMainLoopCondition(int value) {
if (oaml == NULL)
return;
lock->lock();
oaml->SetMainLoopCondition(value);
lock->unlock();
}
void oamlGodotModule::SetCondition(int id, int value) {
if (oaml == NULL)
return;
lock->lock();
oaml->SetCondition(id, value);
lock->unlock();
}
void oamlGodotModule::SetLayerGain(String layer, float gain) {
if (oaml == NULL)
return;
lock->lock();
oaml->SetLayerGain(layer.ascii(), gain);
lock->unlock();
}
void oamlGodotModule::SetLayerRandomChance(String layer, int randomChance) {
if (oaml == NULL)
return;
lock->lock();
oaml->SetLayerRandomChance(layer.ascii(), randomChance);
lock->unlock();
}
void oamlGodotModule::SetTension(int value) {
if (oaml == NULL)
return;
lock->lock();
oaml->SetTension(value);
lock->unlock();
}
void oamlGodotModule::SetVolume(float value) {
if (oaml == NULL)
return;
lock->lock();
oaml->SetVolume(value);
lock->unlock();
}
void oamlGodotModule::StopPlaying() {
if (oaml == NULL)
return;
lock->lock();
oaml->StopPlaying();
lock->unlock();
}
void oamlGodotModule::_bind_methods() {
ClassDB::bind_method("AddTension", &oamlGodotModule::AddTension);
ClassDB::bind_method("EnableDynamicCompressor", &oamlGodotModule::EnableDynamicCompressor);
ClassDB::bind_method("GetPlayingInfo", &oamlGodotModule::GetPlayingInfo);
ClassDB::bind_method("GetVolume", &oamlGodotModule::GetVolume);
ClassDB::bind_method("Init", &oamlGodotModule::Init);
ClassDB::bind_method("InitString", &oamlGodotModule::InitString);
ClassDB::bind_method("IsPaused", &oamlGodotModule::IsPaused);
ClassDB::bind_method("IsPlaying", &oamlGodotModule::IsPlaying);
ClassDB::bind_method("IsTrackPlaying", &oamlGodotModule::IsTrackPlaying);
ClassDB::bind_method("LoadTrack", &oamlGodotModule::LoadTrack);
ClassDB::bind_method("LoadTrackProgress", &oamlGodotModule::LoadTrackProgress);
ClassDB::bind_method("Pause", &oamlGodotModule::Pause);
ClassDB::bind_method("PlayTrack", &oamlGodotModule::PlayTrack);
ClassDB::bind_method("PlayTrackWithStringRandom", &oamlGodotModule::PlayTrackWithStringRandom);
ClassDB::bind_method("PlayTrackByGroupRandom", &oamlGodotModule::PlayTrackByGroupRandom);
ClassDB::bind_method("PlayTrackByGroupAndSubgroupRandom", &oamlGodotModule::PlayTrackByGroupAndSubgroupRandom);
ClassDB::bind_method("Resume", &oamlGodotModule::Resume);
ClassDB::bind_method("SetMainLoopCondition", &oamlGodotModule::SetMainLoopCondition);
ClassDB::bind_method("SetCondition", &oamlGodotModule::SetCondition);
ClassDB::bind_method("SetLayerGain", &oamlGodotModule::SetLayerGain);
ClassDB::bind_method("SetLayerRandomChance", &oamlGodotModule::SetLayerRandomChance);
ClassDB::bind_method("SetTension", &oamlGodotModule::SetTension);
ClassDB::bind_method("SetVolume", &oamlGodotModule::SetVolume);
ClassDB::bind_method("StopPlaying", &oamlGodotModule::StopPlaying);
}
static void* oamlOpen(const char *filename) {
FileAccess *f = FileAccess::open("res://"+String(filename), FileAccess::READ);
if (f == NULL) {
print_line("oaml: Error opening resource file: res://"+String(filename));
return NULL;
}
return (void*)f;
}
static size_t oamlRead(void *ptr, size_t size, size_t nitems, void *fd) {
FileAccess *f = (FileAccess*)fd;
return f->get_buffer((uint8_t*)ptr, size*nitems);
}
static int oamlSeek(void *fd, long offset, int whence) {
FileAccess *f = (FileAccess*)fd;
if (whence == SEEK_SET)
f->seek(offset);
else if (whence == SEEK_END)
f->seek_end(offset);
else if (whence == SEEK_CUR)
f->seek(f->get_position()+offset);
return 0;
}
static long oamlTell(void *fd) {
FileAccess *f = (FileAccess*)fd;
return f->get_position();
}
static int oamlClose(void *fd) {
FileAccess *f = (FileAccess*)fd;
f->close();
memdelete(f);
return 0;
}
static oamlFileCallbacks fileCbs = {
&oamlOpen,
&oamlRead,
&oamlSeek,
&oamlTell,
&oamlClose
};
oamlGodotModule::oamlGodotModule() {
lock = Mutex::create();
oaml = new oamlApi();
oaml->SetFileCallbacks(&fileCbs);
oaml->SetAudioFormat(AudioServer::get_singleton()->get_mix_rate(), 2, 4, true);
AudioServer::get_singleton()->lock();
mix_buffer.resize(AudioServer::get_singleton()->thread_get_mix_buffer_size());
AudioServer::get_singleton()->unlock();
AudioServer::get_singleton()->add_callback(_mix_audios, this);
}
oamlGodotModule::~oamlGodotModule() {
if (oaml != NULL) {
oaml->Shutdown();
delete oaml;
oaml = NULL;
}
if (lock != NULL) {
memdelete(lock);
lock = NULL;
}
AudioServer::get_singleton()->remove_callback(_mix_audios, this);
}
<commit_msg>Added workaround for new .import godot stuff, exported ogg files are read ok now.<commit_after>#include "core/io/config_file.h"
#include "os/file_access.h"
#include "oamlGodotModule.h"
void oamlGodotModule::set_mix_rate(int p_rate) {
if (oaml == NULL)
return;
oaml->SetAudioFormat(p_rate, 2, 4, true);
}
bool oamlGodotModule::mix(AudioFrame *p_buffer, int p_frames) {
if (oaml == NULL)
return true;
zeromem(p_buffer, p_frames*sizeof(AudioFrame));
lock->lock();
oaml->MixToBuffer(p_buffer, p_frames*2);
lock->unlock();
return true;
}
// Called from audio thread
void oamlGodotModule::_mix_audio() {
AudioFrame *buffer = mix_buffer.ptrw();
int buffer_size = mix_buffer.size();
if (!mix(buffer, buffer_size))
return;
AudioFrame *target = AudioServer::get_singleton()->thread_get_channel_mix_buffer(0, 0);
for (int j = 0; j < buffer_size; j++) {
target[j] += buffer[j];
}
}
int oamlGodotModule::sp_get_channel_count() const {
return 2;
}
void oamlGodotModule::AddTension(int value) {
if (oaml == NULL)
return;
oaml->AddTension(value);
}
void oamlGodotModule::EnableDynamicCompressor(bool enable, double thresholdDb, double ratio) {
if (oaml == NULL)
return;
oaml->EnableDynamicCompressor(enable, thresholdDb, ratio);
}
String oamlGodotModule::GetPlayingInfo() {
if (oaml == NULL)
return "";
return String(oaml->GetPlayingInfo());
}
float oamlGodotModule::GetVolume() {
if (oaml == NULL)
return 1.0f;
return oaml->GetVolume();
}
void oamlGodotModule::Init(String defsFilename) {
if (oaml == NULL)
return;
oaml->Init(defsFilename.ascii().get_data());
}
void oamlGodotModule::InitString(String defs) {
if (oaml == NULL)
return;
oaml->InitString(defs.ascii());
}
bool oamlGodotModule::IsPaused() {
if (oaml == NULL)
return true;
return oaml->IsPaused();
}
bool oamlGodotModule::IsPlaying() {
if (oaml == NULL)
return false;
return oaml->IsPlaying();
}
bool oamlGodotModule::IsTrackPlaying(String name) {
if (oaml == NULL)
return false;
return oaml->IsTrackPlaying(name.ascii());
}
void oamlGodotModule::LoadTrack(String name) {
if (oaml == NULL)
return;
lock->lock();
oaml->LoadTrack(name.ascii());
lock->unlock();
}
float oamlGodotModule::LoadTrackProgress(String name) {
if (oaml == NULL)
return -1.f;
lock->lock();
float ret = oaml->LoadTrackProgress(name.ascii());
lock->unlock();
return ret;
}
void oamlGodotModule::Pause() {
if (oaml == NULL)
return;
lock->lock();
oaml->Pause();
lock->unlock();
}
void oamlGodotModule::PlayTrack(String name) {
if (oaml == NULL)
return;
lock->lock();
oaml->PlayTrack(name.ascii());
lock->unlock();
}
void oamlGodotModule::PlayTrackWithStringRandom(String str) {
if (oaml == NULL)
return;
lock->lock();
oaml->PlayTrackWithStringRandom(str.ascii());
lock->unlock();
}
void oamlGodotModule::PlayTrackByGroupRandom(String group) {
if (oaml == NULL)
return;
lock->lock();
oaml->PlayTrackByGroupRandom(group.ascii());
lock->unlock();
}
void oamlGodotModule::PlayTrackByGroupAndSubgroupRandom(String group, String subgroup) {
if (oaml == NULL)
return;
lock->lock();
oaml->PlayTrackByGroupAndSubgroupRandom(group.ascii(), subgroup.ascii());
lock->unlock();
}
void oamlGodotModule::Resume() {
if (oaml == NULL)
return;
lock->lock();
oaml->Resume();
lock->unlock();
}
void oamlGodotModule::SetMainLoopCondition(int value) {
if (oaml == NULL)
return;
lock->lock();
oaml->SetMainLoopCondition(value);
lock->unlock();
}
void oamlGodotModule::SetCondition(int id, int value) {
if (oaml == NULL)
return;
lock->lock();
oaml->SetCondition(id, value);
lock->unlock();
}
void oamlGodotModule::SetLayerGain(String layer, float gain) {
if (oaml == NULL)
return;
lock->lock();
oaml->SetLayerGain(layer.ascii(), gain);
lock->unlock();
}
void oamlGodotModule::SetLayerRandomChance(String layer, int randomChance) {
if (oaml == NULL)
return;
lock->lock();
oaml->SetLayerRandomChance(layer.ascii(), randomChance);
lock->unlock();
}
void oamlGodotModule::SetTension(int value) {
if (oaml == NULL)
return;
lock->lock();
oaml->SetTension(value);
lock->unlock();
}
void oamlGodotModule::SetVolume(float value) {
if (oaml == NULL)
return;
lock->lock();
oaml->SetVolume(value);
lock->unlock();
}
void oamlGodotModule::StopPlaying() {
if (oaml == NULL)
return;
lock->lock();
oaml->StopPlaying();
lock->unlock();
}
void oamlGodotModule::_bind_methods() {
ClassDB::bind_method("AddTension", &oamlGodotModule::AddTension);
ClassDB::bind_method("EnableDynamicCompressor", &oamlGodotModule::EnableDynamicCompressor);
ClassDB::bind_method("GetPlayingInfo", &oamlGodotModule::GetPlayingInfo);
ClassDB::bind_method("GetVolume", &oamlGodotModule::GetVolume);
ClassDB::bind_method("Init", &oamlGodotModule::Init);
ClassDB::bind_method("InitString", &oamlGodotModule::InitString);
ClassDB::bind_method("IsPaused", &oamlGodotModule::IsPaused);
ClassDB::bind_method("IsPlaying", &oamlGodotModule::IsPlaying);
ClassDB::bind_method("IsTrackPlaying", &oamlGodotModule::IsTrackPlaying);
ClassDB::bind_method("LoadTrack", &oamlGodotModule::LoadTrack);
ClassDB::bind_method("LoadTrackProgress", &oamlGodotModule::LoadTrackProgress);
ClassDB::bind_method("Pause", &oamlGodotModule::Pause);
ClassDB::bind_method("PlayTrack", &oamlGodotModule::PlayTrack);
ClassDB::bind_method("PlayTrackWithStringRandom", &oamlGodotModule::PlayTrackWithStringRandom);
ClassDB::bind_method("PlayTrackByGroupRandom", &oamlGodotModule::PlayTrackByGroupRandom);
ClassDB::bind_method("PlayTrackByGroupAndSubgroupRandom", &oamlGodotModule::PlayTrackByGroupAndSubgroupRandom);
ClassDB::bind_method("Resume", &oamlGodotModule::Resume);
ClassDB::bind_method("SetMainLoopCondition", &oamlGodotModule::SetMainLoopCondition);
ClassDB::bind_method("SetCondition", &oamlGodotModule::SetCondition);
ClassDB::bind_method("SetLayerGain", &oamlGodotModule::SetLayerGain);
ClassDB::bind_method("SetLayerRandomChance", &oamlGodotModule::SetLayerRandomChance);
ClassDB::bind_method("SetTension", &oamlGodotModule::SetTension);
ClassDB::bind_method("SetVolume", &oamlGodotModule::SetVolume);
ClassDB::bind_method("StopPlaying", &oamlGodotModule::StopPlaying);
}
static void* oamlOpen(const char *filename) {
String path = "res://"+String(filename);
FileAccess *f = FileAccess::open(path, FileAccess::READ);
if (f == NULL) {
ConfigFile cf;
Error err = cf.load(path + ".import");
if (err == OK) {
f = FileAccess::open(cf.get_value("remap", "path"), FileAccess::READ);
if (f != NULL) {
char header[5] = "0000";
f->seek(28);
while (strncmp(header, "OggS", 4) != 0) {
f->get_buffer((uint8_t*)header, 4);
f->seek(f->get_position()-3);
}
f->seek(f->get_position()-1);
return (void*)f;
}
}
print_line("oaml: Error opening resource file:" + path);
return NULL;
}
return (void*)f;
}
static size_t oamlRead(void *ptr, size_t size, size_t nitems, void *fd) {
FileAccess *f = (FileAccess*)fd;
return f->get_buffer((uint8_t*)ptr, size*nitems);
}
static int oamlSeek(void *fd, long offset, int whence) {
FileAccess *f = (FileAccess*)fd;
if (whence == SEEK_SET)
f->seek(offset);
else if (whence == SEEK_END)
f->seek_end(offset);
else if (whence == SEEK_CUR)
f->seek(f->get_position()+offset);
return 0;
}
static long oamlTell(void *fd) {
FileAccess *f = (FileAccess*)fd;
return f->get_position();
}
static int oamlClose(void *fd) {
FileAccess *f = (FileAccess*)fd;
f->close();
memdelete(f);
return 0;
}
static oamlFileCallbacks fileCbs = {
&oamlOpen,
&oamlRead,
&oamlSeek,
&oamlTell,
&oamlClose
};
oamlGodotModule::oamlGodotModule() {
lock = Mutex::create();
oaml = new oamlApi();
oaml->SetFileCallbacks(&fileCbs);
oaml->SetAudioFormat(AudioServer::get_singleton()->get_mix_rate(), 2, 4, true);
AudioServer::get_singleton()->lock();
mix_buffer.resize(AudioServer::get_singleton()->thread_get_mix_buffer_size());
AudioServer::get_singleton()->unlock();
AudioServer::get_singleton()->add_callback(_mix_audios, this);
}
oamlGodotModule::~oamlGodotModule() {
if (oaml != NULL) {
oaml->Shutdown();
delete oaml;
oaml = NULL;
}
if (lock != NULL) {
memdelete(lock);
lock = NULL;
}
AudioServer::get_singleton()->remove_callback(_mix_audios, this);
}
<|endoftext|> |
<commit_before>/* post_auction_loop.h -*- C++ -*-
Jeremy Barnes, 31 May 2012
Copyright (c) 2012 Datacratic. All rights reserved.
*AuctionEvent and related classes
*/
#include <ostream>
#include <string>
#include "jml/utils/pair_utils.h"
#include "auction_events.h"
using namespace std;
using namespace ML;
using namespace RTBKIT;
/*****************************************************************************/
/* SUBMITTED AUCTION EVENT */
/*****************************************************************************/
void
SubmittedAuctionEvent::
serialize(ML::DB::Store_Writer & store) const
{
store << (unsigned char)0
<< auctionId << adSpotId << lossTimeout << augmentations
<< bidRequestStr << bidResponse << bidRequestStrFormat;
}
void
SubmittedAuctionEvent::
reconstitute(ML::DB::Store_Reader & store)
{
unsigned char version;
store >> version;
if (version != 0)
throw ML::Exception("unknown SubmittedAuctionEvent type");
store >> auctionId >> adSpotId >> lossTimeout >> augmentations
>> bidRequestStr >> bidResponse >> bidRequestStrFormat;
bidRequest.reset(BidRequest::parse(bidRequestStrFormat, bidRequestStr));
}
/*****************************************************************************/
/* POST AUCTION EVENT TYPE */
/*****************************************************************************/
const char *
RTBKIT::
print(PostAuctionEventType type)
{
switch (type) {
case PAE_INVALID: return "INVALID";
case PAE_WIN: return "WIN";
case PAE_LOSS: return "LOSS";
case PAE_CAMPAIGN_EVENT: return "EVENT";
default:
return "UNKNOWN";
}
}
namespace RTBKIT {
COMPACT_PERSISTENT_ENUM_IMPL(PostAuctionEventType);
}
/*****************************************************************************/
/* POST AUCTION EVENT */
/*****************************************************************************/
PostAuctionEvent::
PostAuctionEvent()
: type(PAE_INVALID)
{
}
PostAuctionEvent::
PostAuctionEvent(Json::Value const & json)
: type(PAE_INVALID)
{
for (auto it = json.begin(), end = json.end(); it != end; ++it) {
if (it.memberName() == "type")
type = (PostAuctionEventType) it->asInt();
else if (it.memberName() == "label")
label = it->asString();
else if (it.memberName() == "auctionId")
auctionId.parse(it->asString());
else if (it.memberName() == "adSpotId")
adSpotId.parse(it->asString());
else if (it.memberName() == "timestamp")
timestamp = Date::fromSecondsSinceEpoch(it->asDouble());
else if (it.memberName() == "account")
account = AccountKey::fromJson(*it);
else if (it.memberName() == "winPrice")
winPrice = Amount::fromJson(*it);
else if (it.memberName() == "uids")
uids = UserIds::createFromJson(*it);
else if (it.memberName() == "channels")
channels = SegmentList::createFromJson(*it);
else if (it.memberName() == "bidTimestamp")
bidTimestamp = Date::fromSecondsSinceEpoch(it->asDouble());
else throw ML::Exception("unknown location field " + it.memberName());
}
}
Json::Value
PostAuctionEvent::
toJson() const
{
Json::Value result;
result["type"] = (int) type;
if (!label.empty()) result["label"] = label;
result["auctionId"] = auctionId.toString();
result["adSpotId"] = adSpotId.toString();
result["timestamp"] = timestamp.secondsSinceEpoch();
result["account"] = account.toJson();
result["winPrice"] = winPrice.toJson();
result["uids"] = uids.toJson();
result["channels"] = channels.toJson();
result["bidTimestamp"] = bidTimestamp.secondsSinceEpoch();
return result;
}
void
PostAuctionEvent::
serialize(ML::DB::Store_Writer & store) const
{
unsigned char version = 2;
store << version << type;
if (type == PAE_CAMPAIGN_EVENT) {
store << label;
}
store << auctionId << adSpotId << timestamp
<< metadata << account << winPrice
<< uids << channels << bidTimestamp;
}
void
PostAuctionEvent::
reconstitute(ML::DB::Store_Reader & store)
{
unsigned char version;
store >> version;
if (version > 2)
throw ML::Exception("reconstituting unknown version of "
"PostAuctionEvent");
if (version <= 1) {
string campaign, strategy;
store >> type >> auctionId >> adSpotId >> timestamp
>> metadata >> campaign >> strategy;
account = { campaign, strategy };
}
else {
store >> type;
if (type == PAE_CAMPAIGN_EVENT) {
store >> label;
}
store >> auctionId >> adSpotId >> timestamp
>> metadata >> account;
}
if (version == 0) {
int winCpmInMillis;
store >> winCpmInMillis;
winPrice = MicroUSD(winCpmInMillis);
}
else store >> winPrice;
store >> uids >> channels >> bidTimestamp;
}
std::string
PostAuctionEvent::
print() const
{
std::string result = RTBKIT::print(type);
auto addVal = [&] (const std::string & val)
{
result += '\t' + val;
};
if (auctionId) {
addVal(auctionId.toString());
addVal(adSpotId.toString());
}
addVal(timestamp.print(6));
if (metadata.isNonNull())
addVal(metadata.toString());
if (!account.empty())
addVal(account.toString());
if (type == PAE_WIN)
addVal(winPrice.toString());
if (!uids.empty())
addVal(uids.toString());
if (!channels.empty())
addVal(channels.toString());
if (bidTimestamp != Date())
addVal(bidTimestamp.print(6));
return result;
}
std::ostream &
RTBKIT::
operator << (std::ostream & stream, const PostAuctionEvent & event)
{
return stream << event.print();
}
DB::Store_Writer &
RTBKIT::
operator << (DB::Store_Writer & store, shared_ptr<PostAuctionEvent> event)
{
event->serialize(store);
return store;
}
DB::Store_Reader &
RTBKIT::
operator >> (DB::Store_Reader & store, shared_ptr<PostAuctionEvent> & event)
{
event.reset(new PostAuctionEvent());
event->reconstitute(store);
return store;
}
/******************************************************************************/
/* CAMPAIGN EVENTS */
/******************************************************************************/
CampaignEvent
CampaignEvent::
fromJson(const Json::Value & jsonValue)
{
double timeSeconds(jsonValue["time"].asDouble());
CampaignEvent event(
jsonValue["label"].asString(),
Date::fromSecondsSinceEpoch(timeSeconds),
jsonValue["meta"]);
return event;
}
Json::Value
CampaignEvent::
toJson() const
{
Json::Value json(Json::ValueType::objectValue);
json["label"] = label_;
json["timestamp"] = time_.secondsSinceEpoch();
json["meta"] = meta_.toJson();
return json;
}
void
CampaignEvent::
serialize(DB::Store_Writer & writer) const
{
writer << label_ << time_.secondsSinceEpoch();
meta_.serialize(writer);
}
void
CampaignEvent::
reconstitute(DB::Store_Reader & store)
{
double timeSeconds;
string metaStr;
store >> label_ >> timeSeconds;
time_ = Date::fromSecondsSinceEpoch(timeSeconds);
meta_.reconstitute(store);
}
Json::Value
CampaignEvents::
toJson() const
{
Json::Value json(Json::ValueType::arrayValue);
for (const CampaignEvent & history: *this) {
json.append(history.toJson());
}
return json;
}
CampaignEvents
CampaignEvents::
fromJson(const Json::Value& json)
{
CampaignEvents events;
ExcCheck(json.isArray(), "invalid format for a campaign events object");
for (size_t i = 0; i < json.size(); ++i)
events.push_back(CampaignEvent::fromJson(json[i]));
return events;
}
bool
CampaignEvents::
hasEvent(const std::string & label) const
{
for (const CampaignEvent & history: *this) {
if (history.label_ == label) {
return true;
}
}
return false;
}
void
CampaignEvents::
setEvent(const std::string & label,
Date eventTime,
const JsonHolder & eventMeta)
{
if (hasEvent(label))
throw ML::Exception("already has event '" + label + "'");
emplace_back(label, eventTime, eventMeta);
}
/******************************************************************************/
/* DELIVERY EVENTS */
/******************************************************************************/
DeliveryEvent::Bid
DeliveryEvent::Bid::
fromJson(const Json::Value& json)
{
Bid bid;
if (!json) return bid;
bid.present = true;
const auto& members = json.getMemberNames();
for (const auto& m : members) {
const Json::Value& member = json[m];
bool invalid = false;
switch(m[0]) {
case 'a':
if (m == "agent") bid.agent = member.asString();
else if (m == "account") bid.account = AccountKey::fromJson(member);
else invalid = true;
break;
case 'b':
if (m == "bidData") bid.bids = Bids::fromJson(member.asString());
else invalid = true;
break;
case 'c':
if (m == "creativeId") bid.creativeId = member.asInt();
else if (m == "creativeName") bid.creativeName = member.asString();
else invalid = true;
break;
case 'l':
if (m == "localStatus") {
string status = member.asString();
if (status == "PENDING") bid.localStatus = Auction::PENDING;
else if (status == "WIN") bid.localStatus = Auction::WIN;
else if (status == "LOSS") bid.localStatus = Auction::LOSS;
else if (status == "TOOLATE") bid.localStatus = Auction::TOOLATE;
else if (status == "INVALID") bid.localStatus = Auction::INVALID;
else throw Exception("invalid localStatus value: " + status);
}
else invalid = true;
break;
case 'm':
if (m == "meta") bid.meta = member.asString();
else invalid = true;
break;
case 'p':
if (m == "price") bid.price = Auction::Price::fromJson(member);
else invalid = true;
break;
case 't':
if (m == "timestamp")
bid.time = Date::fromSecondsSinceEpoch(member.asDouble());
else if (m == "test") bid.test = member.asBool();
else if (m == "tagId") bid.test = member.asInt();
else invalid = true;
break;
case 'w':
if (m == "wcm") {
bid.wcm = WinCostModel::fromJson(member);
}
else {
invalid = true;
}
default:
invalid = true;
break;
}
ExcCheck(!invalid, "Unknown member: " + m);
}
return bid;
}
Json::Value
DeliveryEvent::Bid::
toJson() const
{
Json::Value json;
if (!present) return json;
json["timestamp"] = time.secondsSinceEpoch();
json["price"] = price.toJson();
json["test"] = test;
json["tagId"] = tagId;
json["bidData"] = bids.toJson();
json["agent"] = agent;
json["account"] = account.toJson();
json["meta"] = meta;
json["creativeId"] = creativeId;
json["creativeName"] = creativeName;
json["localStatus"] = Auction::Response::print(localStatus);
return json;
}
DeliveryEvent::Win
DeliveryEvent::Win::
fromJson(const Json::Value& json)
{
Win win;
if (!json) return win;
win.present = true;
const auto& members = json.getMemberNames();
for (const auto& m : members) {
const Json::Value& member = json[m];
bool invalid = false;
switch(m[0]) {
case 'm':
if (m == "meta") win.meta = member.asString();
else invalid = true;
break;
case 't':
if (m == "timestamp")
win.time = Date::fromSecondsSinceEpoch(member.asDouble());
else invalid = true;
break;
case 'r':
if (m == "reportedStatus")
win.reportedStatus = bidStatusFromString(member.asString());
else invalid = true;
break;
case 'w':
if (m == "winPrice") win.price = Amount::fromJson(member);
else invalid = true;
break;
default:
invalid = true;
break;
}
ExcCheck(!invalid, "Unknown member: " + m);
}
return win;
}
Json::Value
DeliveryEvent::Win::
toJson() const
{
Json::Value json;
if (!present) return json;
json["timestamp"] = time.secondsSinceEpoch();
json["reportedStatus"] = (reportedStatus == BS_WIN ? "WIN" : "LOSS");
json["winPrice"] = price.toJson();
json["meta"] = meta;
return json;
}
Json::Value
DeliveryEvent::
impressionToJson() const
{
Json::Value json;
for (const CampaignEvent& ev : campaignEvents) {
if (ev.label_ != "IMPRESSION") continue;
json = ev.toJson();
break;
}
return json;
}
Json::Value
DeliveryEvent::
clickToJson() const
{
Json::Value json;
for (const CampaignEvent& ev : campaignEvents) {
if (ev.label_ != "CLICK") continue;
json = ev.toJson();
break;
}
return json;
}
DeliveryEvent::Visit
DeliveryEvent::Visit::
fromJson(const Json::Value& json)
{
Visit visit;
if (!json) return visit;
const auto& members = json.getMemberNames();
for (const auto& m : members) {
const Json::Value& member = json[m];
bool invalid = false;
switch(m[0]) {
case 'c':
if (m == "channels")
visit.channels = SegmentList::createFromJson(member);
else invalid = true;
break;
case 'm':
if (m == "meta") visit.meta = member.asString();
else invalid = true;
break;
case 't':
if (m == "timestamp")
visit.time = Date::fromSecondsSinceEpoch(member.asDouble());
else invalid = true;
break;
default:
invalid = true;
break;
}
ExcCheck(!invalid, "Unknown member: " + m);
}
return visit;
}
Json::Value
DeliveryEvent::Visit::
toJson() const
{
Json::Value json;
json["timestamp"] = time.secondsSinceEpoch();
json["channels"] = channels.toJson();
json["meta"] = meta;
return json;
}
Json::Value
DeliveryEvent::
visitsToJson() const
{
Json::Value json;
for (const auto& visit : visits)
json.append(visit.toJson());
return json;
}
DeliveryEvent
DeliveryEvent::
parse(const std::vector<std::string>& msg)
{
DeliveryEvent ev;
ExcCheckGreaterEqual(msg.size(), 12, "Invalid message size");
using boost::lexical_cast;
ev.event = msg[0];
ev.timestamp = Date::fromSecondsSinceEpoch(lexical_cast<double>(msg[1]));
ev.auctionId = Id(msg[2]);
ev.spotId = Id(msg[3]);
ev.spotIndex = lexical_cast<int>(msg[4]);
string bidRequestSource = msg[5];
ev.bidRequest.reset(BidRequest::parse(bidRequestSource, msg[6]));
ev.augmentations = msg[7];
auto jsonParse = [] (const string& str)
{
if (str.empty()) return Json::Value();
return Json::parse(str);
};
ev.bid = Bid::fromJson(jsonParse(msg[8]));
ev.win = Win::fromJson(jsonParse(msg[9]));
ev.campaignEvents = CampaignEvents::fromJson(jsonParse(msg[10]));
const Json::Value& visits = jsonParse(msg[11]);
for (size_t i = 0; i < visits.size(); ++i)
ev.visits.push_back(Visit::fromJson(visits[i]));
return ev;
}
<commit_msg>break after handling "w"<commit_after>/* post_auction_loop.h -*- C++ -*-
Jeremy Barnes, 31 May 2012
Copyright (c) 2012 Datacratic. All rights reserved.
*AuctionEvent and related classes
*/
#include <ostream>
#include <string>
#include "jml/utils/pair_utils.h"
#include "auction_events.h"
using namespace std;
using namespace ML;
using namespace RTBKIT;
/*****************************************************************************/
/* SUBMITTED AUCTION EVENT */
/*****************************************************************************/
void
SubmittedAuctionEvent::
serialize(ML::DB::Store_Writer & store) const
{
store << (unsigned char)0
<< auctionId << adSpotId << lossTimeout << augmentations
<< bidRequestStr << bidResponse << bidRequestStrFormat;
}
void
SubmittedAuctionEvent::
reconstitute(ML::DB::Store_Reader & store)
{
unsigned char version;
store >> version;
if (version != 0)
throw ML::Exception("unknown SubmittedAuctionEvent type");
store >> auctionId >> adSpotId >> lossTimeout >> augmentations
>> bidRequestStr >> bidResponse >> bidRequestStrFormat;
bidRequest.reset(BidRequest::parse(bidRequestStrFormat, bidRequestStr));
}
/*****************************************************************************/
/* POST AUCTION EVENT TYPE */
/*****************************************************************************/
const char *
RTBKIT::
print(PostAuctionEventType type)
{
switch (type) {
case PAE_INVALID: return "INVALID";
case PAE_WIN: return "WIN";
case PAE_LOSS: return "LOSS";
case PAE_CAMPAIGN_EVENT: return "EVENT";
default:
return "UNKNOWN";
}
}
namespace RTBKIT {
COMPACT_PERSISTENT_ENUM_IMPL(PostAuctionEventType);
}
/*****************************************************************************/
/* POST AUCTION EVENT */
/*****************************************************************************/
PostAuctionEvent::
PostAuctionEvent()
: type(PAE_INVALID)
{
}
PostAuctionEvent::
PostAuctionEvent(Json::Value const & json)
: type(PAE_INVALID)
{
for (auto it = json.begin(), end = json.end(); it != end; ++it) {
if (it.memberName() == "type")
type = (PostAuctionEventType) it->asInt();
else if (it.memberName() == "label")
label = it->asString();
else if (it.memberName() == "auctionId")
auctionId.parse(it->asString());
else if (it.memberName() == "adSpotId")
adSpotId.parse(it->asString());
else if (it.memberName() == "timestamp")
timestamp = Date::fromSecondsSinceEpoch(it->asDouble());
else if (it.memberName() == "account")
account = AccountKey::fromJson(*it);
else if (it.memberName() == "winPrice")
winPrice = Amount::fromJson(*it);
else if (it.memberName() == "uids")
uids = UserIds::createFromJson(*it);
else if (it.memberName() == "channels")
channels = SegmentList::createFromJson(*it);
else if (it.memberName() == "bidTimestamp")
bidTimestamp = Date::fromSecondsSinceEpoch(it->asDouble());
else throw ML::Exception("unknown location field " + it.memberName());
}
}
Json::Value
PostAuctionEvent::
toJson() const
{
Json::Value result;
result["type"] = (int) type;
if (!label.empty()) result["label"] = label;
result["auctionId"] = auctionId.toString();
result["adSpotId"] = adSpotId.toString();
result["timestamp"] = timestamp.secondsSinceEpoch();
result["account"] = account.toJson();
result["winPrice"] = winPrice.toJson();
result["uids"] = uids.toJson();
result["channels"] = channels.toJson();
result["bidTimestamp"] = bidTimestamp.secondsSinceEpoch();
return result;
}
void
PostAuctionEvent::
serialize(ML::DB::Store_Writer & store) const
{
unsigned char version = 2;
store << version << type;
if (type == PAE_CAMPAIGN_EVENT) {
store << label;
}
store << auctionId << adSpotId << timestamp
<< metadata << account << winPrice
<< uids << channels << bidTimestamp;
}
void
PostAuctionEvent::
reconstitute(ML::DB::Store_Reader & store)
{
unsigned char version;
store >> version;
if (version > 2)
throw ML::Exception("reconstituting unknown version of "
"PostAuctionEvent");
if (version <= 1) {
string campaign, strategy;
store >> type >> auctionId >> adSpotId >> timestamp
>> metadata >> campaign >> strategy;
account = { campaign, strategy };
}
else {
store >> type;
if (type == PAE_CAMPAIGN_EVENT) {
store >> label;
}
store >> auctionId >> adSpotId >> timestamp
>> metadata >> account;
}
if (version == 0) {
int winCpmInMillis;
store >> winCpmInMillis;
winPrice = MicroUSD(winCpmInMillis);
}
else store >> winPrice;
store >> uids >> channels >> bidTimestamp;
}
std::string
PostAuctionEvent::
print() const
{
std::string result = RTBKIT::print(type);
auto addVal = [&] (const std::string & val)
{
result += '\t' + val;
};
if (auctionId) {
addVal(auctionId.toString());
addVal(adSpotId.toString());
}
addVal(timestamp.print(6));
if (metadata.isNonNull())
addVal(metadata.toString());
if (!account.empty())
addVal(account.toString());
if (type == PAE_WIN)
addVal(winPrice.toString());
if (!uids.empty())
addVal(uids.toString());
if (!channels.empty())
addVal(channels.toString());
if (bidTimestamp != Date())
addVal(bidTimestamp.print(6));
return result;
}
std::ostream &
RTBKIT::
operator << (std::ostream & stream, const PostAuctionEvent & event)
{
return stream << event.print();
}
DB::Store_Writer &
RTBKIT::
operator << (DB::Store_Writer & store, shared_ptr<PostAuctionEvent> event)
{
event->serialize(store);
return store;
}
DB::Store_Reader &
RTBKIT::
operator >> (DB::Store_Reader & store, shared_ptr<PostAuctionEvent> & event)
{
event.reset(new PostAuctionEvent());
event->reconstitute(store);
return store;
}
/******************************************************************************/
/* CAMPAIGN EVENTS */
/******************************************************************************/
CampaignEvent
CampaignEvent::
fromJson(const Json::Value & jsonValue)
{
double timeSeconds(jsonValue["time"].asDouble());
CampaignEvent event(
jsonValue["label"].asString(),
Date::fromSecondsSinceEpoch(timeSeconds),
jsonValue["meta"]);
return event;
}
Json::Value
CampaignEvent::
toJson() const
{
Json::Value json(Json::ValueType::objectValue);
json["label"] = label_;
json["timestamp"] = time_.secondsSinceEpoch();
json["meta"] = meta_.toJson();
return json;
}
void
CampaignEvent::
serialize(DB::Store_Writer & writer) const
{
writer << label_ << time_.secondsSinceEpoch();
meta_.serialize(writer);
}
void
CampaignEvent::
reconstitute(DB::Store_Reader & store)
{
double timeSeconds;
string metaStr;
store >> label_ >> timeSeconds;
time_ = Date::fromSecondsSinceEpoch(timeSeconds);
meta_.reconstitute(store);
}
Json::Value
CampaignEvents::
toJson() const
{
Json::Value json(Json::ValueType::arrayValue);
for (const CampaignEvent & history: *this) {
json.append(history.toJson());
}
return json;
}
CampaignEvents
CampaignEvents::
fromJson(const Json::Value& json)
{
CampaignEvents events;
ExcCheck(json.isArray(), "invalid format for a campaign events object");
for (size_t i = 0; i < json.size(); ++i)
events.push_back(CampaignEvent::fromJson(json[i]));
return events;
}
bool
CampaignEvents::
hasEvent(const std::string & label) const
{
for (const CampaignEvent & history: *this) {
if (history.label_ == label) {
return true;
}
}
return false;
}
void
CampaignEvents::
setEvent(const std::string & label,
Date eventTime,
const JsonHolder & eventMeta)
{
if (hasEvent(label))
throw ML::Exception("already has event '" + label + "'");
emplace_back(label, eventTime, eventMeta);
}
/******************************************************************************/
/* DELIVERY EVENTS */
/******************************************************************************/
DeliveryEvent::Bid
DeliveryEvent::Bid::
fromJson(const Json::Value& json)
{
Bid bid;
if (!json) return bid;
bid.present = true;
const auto& members = json.getMemberNames();
for (const auto& m : members) {
const Json::Value& member = json[m];
bool invalid = false;
switch(m[0]) {
case 'a':
if (m == "agent") bid.agent = member.asString();
else if (m == "account") bid.account = AccountKey::fromJson(member);
else invalid = true;
break;
case 'b':
if (m == "bidData") bid.bids = Bids::fromJson(member.asString());
else invalid = true;
break;
case 'c':
if (m == "creativeId") bid.creativeId = member.asInt();
else if (m == "creativeName") bid.creativeName = member.asString();
else invalid = true;
break;
case 'l':
if (m == "localStatus") {
string status = member.asString();
if (status == "PENDING") bid.localStatus = Auction::PENDING;
else if (status == "WIN") bid.localStatus = Auction::WIN;
else if (status == "LOSS") bid.localStatus = Auction::LOSS;
else if (status == "TOOLATE") bid.localStatus = Auction::TOOLATE;
else if (status == "INVALID") bid.localStatus = Auction::INVALID;
else throw Exception("invalid localStatus value: " + status);
}
else invalid = true;
break;
case 'm':
if (m == "meta") bid.meta = member.asString();
else invalid = true;
break;
case 'p':
if (m == "price") bid.price = Auction::Price::fromJson(member);
else invalid = true;
break;
case 't':
if (m == "timestamp")
bid.time = Date::fromSecondsSinceEpoch(member.asDouble());
else if (m == "test") bid.test = member.asBool();
else if (m == "tagId") bid.test = member.asInt();
else invalid = true;
break;
case 'w':
if (m == "wcm") {
bid.wcm = WinCostModel::fromJson(member);
}
else {
invalid = true;
}
break;
default:
invalid = true;
break;
}
ExcCheck(!invalid, "Unknown member: " + m);
}
return bid;
}
Json::Value
DeliveryEvent::Bid::
toJson() const
{
Json::Value json;
if (!present) return json;
json["timestamp"] = time.secondsSinceEpoch();
json["price"] = price.toJson();
json["test"] = test;
json["tagId"] = tagId;
json["bidData"] = bids.toJson();
json["agent"] = agent;
json["account"] = account.toJson();
json["meta"] = meta;
json["creativeId"] = creativeId;
json["creativeName"] = creativeName;
json["localStatus"] = Auction::Response::print(localStatus);
return json;
}
DeliveryEvent::Win
DeliveryEvent::Win::
fromJson(const Json::Value& json)
{
Win win;
if (!json) return win;
win.present = true;
const auto& members = json.getMemberNames();
for (const auto& m : members) {
const Json::Value& member = json[m];
bool invalid = false;
switch(m[0]) {
case 'm':
if (m == "meta") win.meta = member.asString();
else invalid = true;
break;
case 't':
if (m == "timestamp")
win.time = Date::fromSecondsSinceEpoch(member.asDouble());
else invalid = true;
break;
case 'r':
if (m == "reportedStatus")
win.reportedStatus = bidStatusFromString(member.asString());
else invalid = true;
break;
case 'w':
if (m == "winPrice") win.price = Amount::fromJson(member);
else invalid = true;
break;
default:
invalid = true;
break;
}
ExcCheck(!invalid, "Unknown member: " + m);
}
return win;
}
Json::Value
DeliveryEvent::Win::
toJson() const
{
Json::Value json;
if (!present) return json;
json["timestamp"] = time.secondsSinceEpoch();
json["reportedStatus"] = (reportedStatus == BS_WIN ? "WIN" : "LOSS");
json["winPrice"] = price.toJson();
json["meta"] = meta;
return json;
}
Json::Value
DeliveryEvent::
impressionToJson() const
{
Json::Value json;
for (const CampaignEvent& ev : campaignEvents) {
if (ev.label_ != "IMPRESSION") continue;
json = ev.toJson();
break;
}
return json;
}
Json::Value
DeliveryEvent::
clickToJson() const
{
Json::Value json;
for (const CampaignEvent& ev : campaignEvents) {
if (ev.label_ != "CLICK") continue;
json = ev.toJson();
break;
}
return json;
}
DeliveryEvent::Visit
DeliveryEvent::Visit::
fromJson(const Json::Value& json)
{
Visit visit;
if (!json) return visit;
const auto& members = json.getMemberNames();
for (const auto& m : members) {
const Json::Value& member = json[m];
bool invalid = false;
switch(m[0]) {
case 'c':
if (m == "channels")
visit.channels = SegmentList::createFromJson(member);
else invalid = true;
break;
case 'm':
if (m == "meta") visit.meta = member.asString();
else invalid = true;
break;
case 't':
if (m == "timestamp")
visit.time = Date::fromSecondsSinceEpoch(member.asDouble());
else invalid = true;
break;
default:
invalid = true;
break;
}
ExcCheck(!invalid, "Unknown member: " + m);
}
return visit;
}
Json::Value
DeliveryEvent::Visit::
toJson() const
{
Json::Value json;
json["timestamp"] = time.secondsSinceEpoch();
json["channels"] = channels.toJson();
json["meta"] = meta;
return json;
}
Json::Value
DeliveryEvent::
visitsToJson() const
{
Json::Value json;
for (const auto& visit : visits)
json.append(visit.toJson());
return json;
}
DeliveryEvent
DeliveryEvent::
parse(const std::vector<std::string>& msg)
{
DeliveryEvent ev;
ExcCheckGreaterEqual(msg.size(), 12, "Invalid message size");
using boost::lexical_cast;
ev.event = msg[0];
ev.timestamp = Date::fromSecondsSinceEpoch(lexical_cast<double>(msg[1]));
ev.auctionId = Id(msg[2]);
ev.spotId = Id(msg[3]);
ev.spotIndex = lexical_cast<int>(msg[4]);
string bidRequestSource = msg[5];
ev.bidRequest.reset(BidRequest::parse(bidRequestSource, msg[6]));
ev.augmentations = msg[7];
auto jsonParse = [] (const string& str)
{
if (str.empty()) return Json::Value();
return Json::parse(str);
};
ev.bid = Bid::fromJson(jsonParse(msg[8]));
ev.win = Win::fromJson(jsonParse(msg[9]));
ev.campaignEvents = CampaignEvents::fromJson(jsonParse(msg[10]));
const Json::Value& visits = jsonParse(msg[11]);
for (size_t i = 0; i < visits.size(); ++i)
ev.visits.push_back(Visit::fromJson(visits[i]));
return ev;
}
<|endoftext|> |
<commit_before>// Copyright 2016 Tom Barthel-Steer
// http://www.tomsteer.net
//
// 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 "gridwidget.h"
#include <QPainter>
#include <QMouseEvent>
#include <QPalette>
#include <QApplication>
#include <QStyle>
#define FIRST_COL_WIDTH 60
#define ROW_COUNT 16
#define COL_COUNT 32
#define CELL_WIDTH 25
#define CELL_COUNT 512
GridWidget::GridWidget(QWidget *parent)
: QWidget(parent)
, m_selectedAddress(-1)
, m_colors(CELL_COUNT, Qt::white)
, m_cellHeight(18)
{
for(int i=0; i<CELL_COUNT; i++)
{
m_values << QString();
}
}
QSize GridWidget::minimumSizeHint() const
{
return QWidget::minimumSizeHint(); //sizeHint();
}
QSize GridWidget::sizeHint() const
{
return QWidget::sizeHint();
//return QSize( FIRST_COL_WIDTH + CELL_WIDTH * COL_COUNT, CELL_HEIGHT * (ROW_COUNT + 1));
}
void GridWidget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter painter(this);
QPalette pal = this->palette();
qreal wantedHeight = m_cellHeight * (ROW_COUNT + 1);
qreal wantedWidth = FIRST_COL_WIDTH + CELL_WIDTH * COL_COUNT;
qreal scaleWidth = width()/wantedWidth;
qreal scaleHeight = height()/ wantedHeight;
qreal minScale = qMin(scaleWidth, scaleHeight);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.translate((width()-minScale*wantedWidth) /2,0);
painter.scale(minScale,minScale);
painter.fillRect(QRectF(0,0, wantedWidth, wantedHeight), pal.color(QPalette::Base));
painter.setPen(pal.color(QPalette::Text));
painter.setFont(QFont("Segoe UI", 8));
for(int row=1; row<ROW_COUNT+1; row++)
{
QRect textRect(0, row*m_cellHeight, FIRST_COL_WIDTH, m_cellHeight);
QString rowLabel = QString("%1 - %2")
.arg(1+(row-1)*32)
.arg((row)*32);
painter.drawText(textRect, rowLabel, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter));
}
for(int col=0; col<COL_COUNT; col++)
{
QRect textRect(FIRST_COL_WIDTH + col*CELL_WIDTH, 0, CELL_WIDTH, m_cellHeight);
QString rowLabel = QString("%1")
.arg(col+1);
painter.drawText(textRect, rowLabel, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter));
}
for(int row=0; row<ROW_COUNT; row++)
for(int col=0; col<COL_COUNT; col++)
{
int address = row*COL_COUNT + col;
QRect textRect(FIRST_COL_WIDTH + col*CELL_WIDTH, (row+1)*m_cellHeight, CELL_WIDTH, m_cellHeight);
QString value = m_values[address];
if(!value.isEmpty())
{
QColor fillColor = m_colors[address];
QString rowLabel = value;
painter.fillRect(textRect, fillColor);
painter.drawText(textRect, rowLabel, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter));
}
}
painter.setPen(pal.color(QPalette::AlternateBase));
for(int row=0; row<ROW_COUNT + 1; row++)
{
QPoint start(0, row*m_cellHeight);
QPoint end(wantedWidth, row*m_cellHeight);
painter.drawLine(start, end);
}
for(int col=0; col<COL_COUNT + 1; col++)
{
QPoint start(FIRST_COL_WIDTH + col*CELL_WIDTH, 0);
QPoint end(FIRST_COL_WIDTH + col*CELL_WIDTH, wantedHeight);
painter.drawLine(start, end);
}
// Draw the highlight for the selected one
if(m_selectedAddress>-1)
{
int col = m_selectedAddress % 32;
int row = m_selectedAddress / 32;
QRect textRect(FIRST_COL_WIDTH + col*CELL_WIDTH, (row+1)*m_cellHeight, CELL_WIDTH, m_cellHeight);
painter.setPen(pal.color(QPalette::Highlight));
painter.drawRect(textRect);
}
}
int GridWidget::cellHitTest(const QPoint &point)
{
qreal wantedHeight = m_cellHeight * (ROW_COUNT + 1);
qreal wantedWidth = FIRST_COL_WIDTH + CELL_WIDTH * COL_COUNT;
qreal scaleWidth = width()/wantedWidth;
qreal scaleHeight = height()/ wantedHeight;
qreal minScale = qMin(scaleWidth, scaleHeight);
QRectF drawnRect(0, 0, wantedWidth*minScale, wantedHeight*minScale);
drawnRect.moveCenter(this->rect().center());
drawnRect.moveTop(0);
if(!drawnRect.contains(point))
return -1;
qreal cellWidth = (drawnRect.width() - FIRST_COL_WIDTH * minScale) / COL_COUNT;
qreal firstColWidth = drawnRect.width() - (COL_COUNT * cellWidth);
qreal cellHeight = drawnRect.height() / (ROW_COUNT + 1);
int col = (point.x() - drawnRect.left() - firstColWidth) / cellWidth;
int row = (point.y() - drawnRect.top() - cellHeight) / cellHeight;
if(col<0) return -1;
if(row<0) return -1;
int address = (row * 32) + col;
if(address>511 || address<0) return -1;
return address;
}
void GridWidget::mousePressEvent(QMouseEvent *event)
{
QWidget::mousePressEvent(event);
if(event->buttons() & Qt::LeftButton)
{
int address = cellHitTest(event->pos());
if(m_selectedAddress!=address)
{
m_selectedAddress = address;
emit selectedCellChanged(m_selectedAddress);
update();
}
}
}
void GridWidget::mouseMoveEvent(QMouseEvent *event)
{
QWidget::mouseMoveEvent(event);
if(event->buttons() & Qt::LeftButton)
{
int address = cellHitTest(event->pos());
if(m_selectedAddress!=address)
{
m_selectedAddress = address;
emit selectedCellChanged(m_selectedAddress);
update();
}
}
}
void GridWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
QWidget::mousePressEvent(event);
if(event->buttons() & Qt::LeftButton)
{
quint16 address = cellHitTest(event->pos());
emit cellDoubleClick(address);
}
}
void GridWidget::setCellColor(int cell, const QColor &color)
{
m_colors[cell] = color;
}
void GridWidget::setCellValue(int cell, const QString &value)
{
m_values[cell] = value;
}
QString GridWidget::cellValue(int cell)
{
return m_values[cell];
}
<commit_msg>Universe display grid ignores aspect ratio<commit_after>// Copyright 2016 Tom Barthel-Steer
// http://www.tomsteer.net
//
// 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 "gridwidget.h"
#include <QPainter>
#include <QMouseEvent>
#include <QPalette>
#include <QApplication>
#include <QStyle>
#define FIRST_COL_WIDTH 60
#define ROW_COUNT 16
#define COL_COUNT 32
#define CELL_WIDTH 25
#define CELL_COUNT 512
GridWidget::GridWidget(QWidget *parent)
: QWidget(parent)
, m_selectedAddress(-1)
, m_colors(CELL_COUNT, Qt::white)
, m_cellHeight(18)
{
for(int i=0; i<CELL_COUNT; i++)
{
m_values << QString();
}
}
QSize GridWidget::minimumSizeHint() const
{
return QWidget::minimumSizeHint(); //sizeHint();
}
QSize GridWidget::sizeHint() const
{
return QWidget::sizeHint();
//return QSize( FIRST_COL_WIDTH + CELL_WIDTH * COL_COUNT, CELL_HEIGHT * (ROW_COUNT + 1));
}
void GridWidget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter painter(this);
QPalette pal = this->palette();
qreal wantedHeight = m_cellHeight * (ROW_COUNT + 1);
qreal wantedWidth = FIRST_COL_WIDTH + CELL_WIDTH * COL_COUNT;
qreal scaleWidth = width()/wantedWidth;
qreal scaleHeight = height()/ wantedHeight;
qreal minScale = qMin(scaleWidth, scaleHeight);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.scale(scaleWidth,scaleHeight);
painter.fillRect(QRectF(0,0, wantedWidth, wantedHeight), pal.color(QPalette::Base));
painter.setPen(pal.color(QPalette::Text));
painter.setFont(QFont("Segoe UI", 8));
for(int row=1; row<ROW_COUNT+1; row++)
{
QRect textRect(0, row*m_cellHeight, FIRST_COL_WIDTH, m_cellHeight);
QString rowLabel = QString("%1 - %2")
.arg(1+(row-1)*32)
.arg((row)*32);
painter.drawText(textRect, rowLabel, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter));
}
for(int col=0; col<COL_COUNT; col++)
{
QRect textRect(FIRST_COL_WIDTH + col*CELL_WIDTH, 0, CELL_WIDTH, m_cellHeight);
QString rowLabel = QString("%1")
.arg(col+1);
painter.drawText(textRect, rowLabel, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter));
}
for(int row=0; row<ROW_COUNT; row++)
for(int col=0; col<COL_COUNT; col++)
{
int address = row*COL_COUNT + col;
QRect textRect(FIRST_COL_WIDTH + col*CELL_WIDTH, (row+1)*m_cellHeight, CELL_WIDTH, m_cellHeight);
QString value = m_values[address];
if(!value.isEmpty())
{
QColor fillColor = m_colors[address];
QString rowLabel = value;
painter.fillRect(textRect, fillColor);
painter.drawText(textRect, rowLabel, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter));
}
}
painter.setPen(pal.color(QPalette::AlternateBase));
for(int row=0; row<ROW_COUNT + 1; row++)
{
QPoint start(0, row*m_cellHeight);
QPoint end(wantedWidth, row*m_cellHeight);
painter.drawLine(start, end);
}
for(int col=0; col<COL_COUNT + 1; col++)
{
QPoint start(FIRST_COL_WIDTH + col*CELL_WIDTH, 0);
QPoint end(FIRST_COL_WIDTH + col*CELL_WIDTH, wantedHeight);
painter.drawLine(start, end);
}
// Draw the highlight for the selected one
if(m_selectedAddress>-1)
{
int col = m_selectedAddress % 32;
int row = m_selectedAddress / 32;
QRect textRect(FIRST_COL_WIDTH + col*CELL_WIDTH, (row+1)*m_cellHeight, CELL_WIDTH, m_cellHeight);
painter.setPen(pal.color(QPalette::Highlight));
painter.drawRect(textRect);
}
}
int GridWidget::cellHitTest(const QPoint &point)
{
qreal wantedHeight = m_cellHeight * (ROW_COUNT + 1);
qreal wantedWidth = FIRST_COL_WIDTH + CELL_WIDTH * COL_COUNT;
qreal scaleWidth = width()/wantedWidth;
qreal scaleHeight = height()/ wantedHeight;
qreal minScale = qMin(scaleWidth, scaleHeight);
QRectF drawnRect(0, 0, wantedWidth*minScale, wantedHeight*minScale);
drawnRect.moveCenter(this->rect().center());
drawnRect.moveTop(0);
if(!drawnRect.contains(point))
return -1;
qreal cellWidth = (drawnRect.width() - FIRST_COL_WIDTH * minScale) / COL_COUNT;
qreal firstColWidth = drawnRect.width() - (COL_COUNT * cellWidth);
qreal cellHeight = drawnRect.height() / (ROW_COUNT + 1);
int col = (point.x() - drawnRect.left() - firstColWidth) / cellWidth;
int row = (point.y() - drawnRect.top() - cellHeight) / cellHeight;
if(col<0) return -1;
if(row<0) return -1;
int address = (row * 32) + col;
if(address>511 || address<0) return -1;
return address;
}
void GridWidget::mousePressEvent(QMouseEvent *event)
{
QWidget::mousePressEvent(event);
if(event->buttons() & Qt::LeftButton)
{
int address = cellHitTest(event->pos());
if(m_selectedAddress!=address)
{
m_selectedAddress = address;
emit selectedCellChanged(m_selectedAddress);
update();
}
}
}
void GridWidget::mouseMoveEvent(QMouseEvent *event)
{
QWidget::mouseMoveEvent(event);
if(event->buttons() & Qt::LeftButton)
{
int address = cellHitTest(event->pos());
if(m_selectedAddress!=address)
{
m_selectedAddress = address;
emit selectedCellChanged(m_selectedAddress);
update();
}
}
}
void GridWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
QWidget::mousePressEvent(event);
if(event->buttons() & Qt::LeftButton)
{
quint16 address = cellHitTest(event->pos());
emit cellDoubleClick(address);
}
}
void GridWidget::setCellColor(int cell, const QColor &color)
{
m_colors[cell] = color;
}
void GridWidget::setCellValue(int cell, const QString &value)
{
m_values[cell] = value;
}
QString GridWidget::cellValue(int cell)
{
return m_values[cell];
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <SFML/Window/Mouse.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
#include "gui/button.hpp"
namespace qrw
{
Button::Button(sf::Window* window,std::string text,
const sf::Texture* textureactive,
const sf::Texture* textureinactive,
const sf::Texture* texturehover)
: Sprite(),
text(text),
window(window),
state(ES_INACTIVE)
{
if(textureactive != NULL && textureinactive != NULL
&& texturehover != NULL)
setTextures(textureactive, textureinactive, texturehover);
for(int i = 0; i < 3; ++i)
textures[i] = 0;
}
Button::~Button()
{}
void Button::setText(std::string text)
{
this->text = text;
}
std::string Button::getText()
{
return text;
}
void Button::setTextures(const sf::Texture* textureinactive,
const sf::Texture* textureactive, const sf::Texture* texturehover)
{
textures[ES_INACTIVE] = textureinactive;
textures[ES_ACTIVE] = textureactive;
textures[ES_HOVER] = texturehover;
}
// void Button::draw(sf::RenderTarget& target, sf::RenderStates states) const
// {
// target.draw(*(sf::Sprite*)this, states);
// }
void Button::handleEvent(const sf::Event& event)
{
if(mouseOnButton() == false)
{
state = ES_INACTIVE;
updateSprite();
return;
}
if(sf::Mouse::isButtonPressed(sf::Mouse::Left) == false
&& event.type == sf::Event::MouseMoved)
{
state = ES_HOVER;
}
else if(event.type == sf::Event::MouseButtonPressed
&& event.mouseButton.button == sf::Mouse::Left)
{
state = ES_ACTIVE;
signalclicked.emit();
}
else if(event.type == sf::Event::MouseButtonReleased
&& event.mouseButton.button == sf::Mouse::Left)
{
state = ES_INACTIVE;
}
updateSprite();
}
bool Button::mouseOnButton()
{
sf::FloatRect bounds = getGlobalBounds();
sf::Vector2f mousepos;
mousepos.x = (float)sf::Mouse::getPosition(*window).x;
mousepos.y = (float)sf::Mouse::getPosition(*window).y;
if(getGlobalBounds().contains(mousepos) == true)
{
return false;
}
return true;
}
void Button::updateSprite()
{
if(textures[state] != 0)
setTexture(*textures[state]);
}
}<commit_msg>Fixed bug introduced with previous commit.<commit_after>#include <stdio.h>
#include <SFML/Window/Mouse.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
#include "gui/button.hpp"
namespace qrw
{
Button::Button(sf::Window* window,std::string text,
const sf::Texture* textureactive,
const sf::Texture* textureinactive,
const sf::Texture* texturehover)
: Sprite(),
text(text),
window(window),
state(ES_INACTIVE)
{
if(textureactive != NULL && textureinactive != NULL
&& texturehover != NULL)
setTextures(textureactive, textureinactive, texturehover);
for(int i = 0; i < 3; ++i)
textures[i] = 0;
}
Button::~Button()
{}
void Button::setText(std::string text)
{
this->text = text;
}
std::string Button::getText()
{
return text;
}
void Button::setTextures(const sf::Texture* textureinactive,
const sf::Texture* textureactive, const sf::Texture* texturehover)
{
textures[ES_INACTIVE] = textureinactive;
textures[ES_ACTIVE] = textureactive;
textures[ES_HOVER] = texturehover;
}
// void Button::draw(sf::RenderTarget& target, sf::RenderStates states) const
// {
// target.draw(*(sf::Sprite*)this, states);
// }
void Button::handleEvent(const sf::Event& event)
{
if(mouseOnButton() == false)
{
state = ES_INACTIVE;
updateSprite();
return;
}
if(sf::Mouse::isButtonPressed(sf::Mouse::Left) == false
&& event.type == sf::Event::MouseMoved)
{
state = ES_HOVER;
}
else if(event.type == sf::Event::MouseButtonPressed
&& event.mouseButton.button == sf::Mouse::Left)
{
state = ES_ACTIVE;
signalclicked.emit();
}
else if(event.type == sf::Event::MouseButtonReleased
&& event.mouseButton.button == sf::Mouse::Left)
{
state = ES_INACTIVE;
}
updateSprite();
}
bool Button::mouseOnButton()
{
sf::FloatRect bounds = getGlobalBounds();
sf::Vector2f mousepos;
mousepos.x = (float)sf::Mouse::getPosition(*window).x;
mousepos.y = (float)sf::Mouse::getPosition(*window).y;
return getGlobalBounds().contains(mousepos);
}
void Button::updateSprite()
{
if(textures[state] != 0)
setTexture(*textures[state]);
}
}<|endoftext|> |
<commit_before>#pragma once
#include <boost/asio/buffers_iterator.hpp>
#include <boost/system/error_code.hpp>
#include <iostream>
#include <string>
#include <utility>
namespace bredis {
namespace test {
template <typename NextLayer> class SocketWithLogging {
NextLayer stream_;
template <typename BufferSequence, typename Handler>
struct HandlerWithLogging {
Handler next_handler_;
const BufferSequence buffers_;
const char *prefix_;
HandlerWithLogging(const char *prefix, Handler hander,
const BufferSequence &buffers)
: prefix_(prefix), next_handler_(hander), buffers_(buffers) {}
void operator()(const boost::system::error_code &error_code,
std::size_t bytes_transferred) {
dump(prefix_, buffers_, bytes_transferred);
next_handler_(error_code, bytes_transferred);
}
};
public:
template <typename... Args>
SocketWithLogging(Args &&... args) : stream_(std::forward<Args>(args)...) {}
template <typename BufferSequence>
static void dump(const char *prefix, const BufferSequence &buffers,
std::size_t size) {
using boost::asio::buffer_cast;
using boost::asio::buffer_size;
std::string content;
content.reserve(size);
for (auto const &buffer : buffers) {
content.append(buffer_cast<char const *>(buffer), size);
}
std::cout << "{" << prefix << " " << size << " bytes}[" << content
<< "]" << std::endl;
}
template <typename MutableBufferSequence, typename ReadHandler>
void async_read_some(const MutableBufferSequence &buffers,
ReadHandler handler) {
stream_.async_read_some(
buffers, HandlerWithLogging<MutableBufferSequence, ReadHandler>(
"async_read_some", handler, buffers));
}
template <typename ConstBufferSequence, typename WriteHandler>
void async_write_some(const ConstBufferSequence &buffers,
WriteHandler handler) {
stream_.async_write_some(
buffers, HandlerWithLogging<ConstBufferSequence, WriteHandler>(
"async_write_some", handler, buffers));
}
template <typename ConstBufferSequence>
std::size_t write_some(const ConstBufferSequence &buffers) {
auto bytes_transferred = stream_.write_some(buffers);
dump("write_some", buffers, bytes_transferred);
return bytes_transferred;
}
template <typename ConstBufferSequence>
std::size_t write_some(const ConstBufferSequence &buffers,
boost::system::error_code &ec) {
auto bytes_transferred = stream_.write_some(buffers, ec);
dump("write_some", buffers, bytes_transferred);
return bytes_transferred;
}
template <typename MutableBufferSequence>
std::size_t read_some(const MutableBufferSequence &buffers) {
auto bytes_transferred = stream_.read_some(buffers);
dump("read_some", buffers, bytes_transferred);
return bytes_transferred;
}
template <typename MutableBufferSequence>
std::size_t read_some(const MutableBufferSequence &buffers,
boost::system::error_code &ec) {
auto bytes_transferred = stream_.read_some(buffers, ec);
dump("read_some", buffers, bytes_transferred);
return bytes_transferred;
}
};
} // namespace test
} // namespace bredis
<commit_msg>Intoduce log policy<commit_after>#pragma once
#include <boost/asio/buffers_iterator.hpp>
#include <boost/system/error_code.hpp>
#include <iostream>
#include <string>
#include <utility>
namespace bredis {
namespace test {
class DefaultLogPolicy {
public:
static void log(const char *prefix, const std::string &content) {
std::cout << "{" << prefix << " " << content.size() << " bytes}["
<< content << "]" << std::endl;
}
};
template <typename NextLayer, typename LogPolicy = DefaultLogPolicy>
class SocketWithLogging {
NextLayer stream_;
template <typename BufferSequence, typename Handler>
struct HandlerWithLogging {
Handler next_handler_;
const BufferSequence buffers_;
const char *prefix_;
HandlerWithLogging(const char *prefix, Handler hander,
const BufferSequence &buffers)
: prefix_(prefix), next_handler_(hander), buffers_(buffers) {}
void operator()(const boost::system::error_code &error_code,
std::size_t bytes_transferred) {
dump(prefix_, buffers_, bytes_transferred);
next_handler_(error_code, bytes_transferred);
}
};
public:
template <typename... Args>
SocketWithLogging(Args &&... args) : stream_(std::forward<Args>(args)...) {}
template <typename BufferSequence>
static void dump(const char *prefix, const BufferSequence &buffers,
std::size_t size) {
using boost::asio::buffer_cast;
using boost::asio::buffer_size;
std::string content;
content.reserve(size);
for (auto const &buffer : buffers) {
content.append(buffer_cast<char const *>(buffer), size);
}
LogPolicy::log(prefix, content);
}
template <typename MutableBufferSequence, typename ReadHandler>
void async_read_some(const MutableBufferSequence &buffers,
ReadHandler handler) {
stream_.async_read_some(
buffers, HandlerWithLogging<MutableBufferSequence, ReadHandler>(
"async_read_some", handler, buffers));
}
template <typename ConstBufferSequence, typename WriteHandler>
void async_write_some(const ConstBufferSequence &buffers,
WriteHandler handler) {
stream_.async_write_some(
buffers, HandlerWithLogging<ConstBufferSequence, WriteHandler>(
"async_write_some", handler, buffers));
}
template <typename ConstBufferSequence>
std::size_t write_some(const ConstBufferSequence &buffers) {
auto bytes_transferred = stream_.write_some(buffers);
dump("write_some", buffers, bytes_transferred);
return bytes_transferred;
}
template <typename ConstBufferSequence>
std::size_t write_some(const ConstBufferSequence &buffers,
boost::system::error_code &ec) {
auto bytes_transferred = stream_.write_some(buffers, ec);
dump("write_some", buffers, bytes_transferred);
return bytes_transferred;
}
template <typename MutableBufferSequence>
std::size_t read_some(const MutableBufferSequence &buffers) {
auto bytes_transferred = stream_.read_some(buffers);
dump("read_some", buffers, bytes_transferred);
return bytes_transferred;
}
template <typename MutableBufferSequence>
std::size_t read_some(const MutableBufferSequence &buffers,
boost::system::error_code &ec) {
auto bytes_transferred = stream_.read_some(buffers, ec);
dump("read_some", buffers, bytes_transferred);
return bytes_transferred;
}
};
} // namespace test
} // namespace bredis
<|endoftext|> |
<commit_before>#ifndef TURBO_CONTAINER_MPMC_RING_QUEUE_HPP
#define TURBO_CONTAINER_MPMC_RING_QUEUE_HPP
#include <cstdint>
#include <atomic>
#include <functional>
#include <memory>
#include <utility>
#include <vector>
#include <turbo/toolset/attribute.hpp>
namespace turbo {
namespace container {
template <class value_t>
struct alignas(LEVEL1_DCACHE_LINESIZE) node
{
enum class status : uint8_t
{
used,
unused
};
std::atomic<status> guard;
value_t value;
};
template <class value_t>
struct alignas(LEVEL1_DCACHE_LINESIZE) atomic_node
{
std::atomic<value_t> value;
};
template <class value_t, template <class type_t> class allocator_t = std::allocator> class mpmc_key;
template <class value_t, template <class type_t> class allocator_t = std::allocator> class mpmc_ring_queue;
template <class value_t, template <class type_t> class allocator_t = std::allocator>
class alignas(LEVEL1_DCACHE_LINESIZE) mpmc_producer
{
public:
typedef value_t value_type;
typedef mpmc_key<value_t, allocator_t> key;
enum class result
{
success,
beaten,
busy,
queue_full
};
mpmc_producer(const key&, mpmc_ring_queue<value_t, allocator_t>& queue);
mpmc_producer(const mpmc_producer& other);
result try_enqueue_copy(const value_t& input);
result try_enqueue_move(value_t&& input);
private:
mpmc_producer() = delete;
mpmc_producer& operator=(const mpmc_producer& other) = delete;
mpmc_ring_queue<value_t, allocator_t>& queue_;
};
template <class value_t, template <class type_t> class allocator_t = std::allocator>
class alignas(LEVEL1_DCACHE_LINESIZE) mpmc_consumer
{
public:
typedef value_t value_type;
typedef mpmc_key<value_t, allocator_t> key;
enum class result
{
success,
beaten,
busy,
queue_empty
};
mpmc_consumer(const key&, mpmc_ring_queue<value_t, allocator_t>& queue);
mpmc_consumer(const mpmc_consumer& other);
result try_dequeue_copy(value_t& output);
result try_dequeue_move(value_t& output);
private:
mpmc_consumer() = delete;
mpmc_consumer& operator=(const mpmc_consumer& other) = delete;
mpmc_ring_queue<value_t, allocator_t>& queue_;
};
template <class value_t, template <class type_t> class allocator_t>
class TURBO_SYMBOL_DECL mpmc_ring_queue
{
public:
typedef value_t value_type;
typedef node<value_t> node_type;
typedef mpmc_producer<value_t, allocator_t> producer;
typedef mpmc_consumer<value_t, allocator_t> consumer;
typedef mpmc_key<value_t, allocator_t> key;
mpmc_ring_queue(uint32_t capacity);
mpmc_ring_queue(uint32_t capacity, uint16_t handle_limit);
producer& get_producer();
consumer& get_consumer();
typename producer::result try_enqueue_copy(const value_t& input);
typename producer::result try_enqueue_move(value_t&& input);
typename consumer::result try_dequeue_copy(value_t& output);
typename consumer::result try_dequeue_move(value_t& output);
private:
typedef std::vector<value_t, allocator_t<value_t>> vector_type;
template <class handle_t>
struct handle_list
{
handle_list(uint16_t limit, const key& the_key, mpmc_ring_queue<value_t, allocator_t>& queue);
std::atomic<uint16_t> counter;
std::vector<handle_t, allocator_t<handle_t>> list;
};
alignas(LEVEL1_DCACHE_LINESIZE) std::vector<node_type, allocator_t<node_type>> buffer_;
alignas(LEVEL1_DCACHE_LINESIZE) std::atomic<uint32_t> head_;
alignas(LEVEL1_DCACHE_LINESIZE) std::atomic<uint32_t> tail_;
alignas(LEVEL1_DCACHE_LINESIZE) handle_list<mpmc_producer<value_t, allocator_t>> producer_list;
alignas(LEVEL1_DCACHE_LINESIZE) handle_list<mpmc_consumer<value_t, allocator_t>> consumer_list;
};
template <template <class type_t> class allocator_t>
class TURBO_SYMBOL_DECL mpmc_ring_queue<std::uint32_t, allocator_t>
{
public:
typedef std::uint32_t value_type;
typedef atomic_node<std::uint32_t> node_type;
typedef mpmc_producer<std::uint32_t, allocator_t> producer;
typedef mpmc_consumer<std::uint32_t, allocator_t> consumer;
typedef mpmc_key<std::uint32_t, allocator_t> key;
mpmc_ring_queue(uint32_t capacity);
mpmc_ring_queue(uint32_t capacity, uint16_t handle_limit);
producer& get_producer();
consumer& get_consumer();
typename producer::result try_enqueue_copy(value_type input);
typename producer::result try_enqueue_move(value_type&& input);
typename consumer::result try_dequeue_copy(value_type& output);
typename consumer::result try_dequeue_move(value_type& output);
private:
typedef std::vector<std::uint32_t, allocator_t<std::uint32_t>> vector_type;
template <class handle_t>
struct handle_list
{
handle_list(uint16_t limit, const key& the_key, mpmc_ring_queue<std::uint32_t, allocator_t>& queue);
std::atomic<uint16_t> counter;
std::vector<handle_t, allocator_t<handle_t>> list;
};
alignas(LEVEL1_DCACHE_LINESIZE) std::vector<node_type, allocator_t<node_type>> buffer_;
alignas(LEVEL1_DCACHE_LINESIZE) std::atomic<uint32_t> head_;
alignas(LEVEL1_DCACHE_LINESIZE) std::atomic<uint32_t> tail_;
alignas(LEVEL1_DCACHE_LINESIZE) handle_list<mpmc_producer<std::uint32_t, allocator_t>> producer_list;
alignas(LEVEL1_DCACHE_LINESIZE) handle_list<mpmc_consumer<std::uint32_t, allocator_t>> consumer_list;
};
template <template <class type_t> class allocator_t>
class TURBO_SYMBOL_DECL mpmc_ring_queue<std::uint64_t, allocator_t>
{
public:
typedef std::uint64_t value_type;
typedef atomic_node<std::uint64_t> node_type;
typedef mpmc_producer<std::uint64_t, allocator_t> producer;
typedef mpmc_consumer<std::uint64_t, allocator_t> consumer;
typedef mpmc_key<std::uint64_t, allocator_t> key;
mpmc_ring_queue(uint32_t capacity);
mpmc_ring_queue(uint32_t capacity, uint16_t handle_limit);
producer& get_producer();
consumer& get_consumer();
typename producer::result try_enqueue_copy(value_type input);
typename producer::result try_enqueue_move(value_type&& input);
typename consumer::result try_dequeue_copy(value_type& output);
typename consumer::result try_dequeue_move(value_type& output);
private:
typedef std::vector<std::uint64_t, allocator_t<std::uint64_t>> vector_type;
template <class handle_t>
struct handle_list
{
handle_list(uint16_t limit, const key& the_key, mpmc_ring_queue<std::uint64_t, allocator_t>& queue);
std::atomic<uint16_t> counter;
std::vector<handle_t, allocator_t<handle_t>> list;
};
alignas(LEVEL1_DCACHE_LINESIZE) std::vector<node_type, allocator_t<node_type>> buffer_;
alignas(LEVEL1_DCACHE_LINESIZE) std::atomic<uint32_t> head_;
alignas(LEVEL1_DCACHE_LINESIZE) std::atomic<uint32_t> tail_;
alignas(LEVEL1_DCACHE_LINESIZE) handle_list<mpmc_producer<std::uint64_t, allocator_t>> producer_list;
alignas(LEVEL1_DCACHE_LINESIZE) handle_list<mpmc_consumer<std::uint64_t, allocator_t>> consumer_list;
};
} // namespace container
} // namespace turbo
#endif
<commit_msg>reducing structure sizes for members where cache line alignment doesn't matter<commit_after>#ifndef TURBO_CONTAINER_MPMC_RING_QUEUE_HPP
#define TURBO_CONTAINER_MPMC_RING_QUEUE_HPP
#include <cstdint>
#include <atomic>
#include <functional>
#include <memory>
#include <utility>
#include <vector>
#include <turbo/toolset/attribute.hpp>
namespace turbo {
namespace container {
template <class value_t>
struct alignas(LEVEL1_DCACHE_LINESIZE) node
{
enum class status : uint8_t
{
used,
unused
};
std::atomic<status> guard;
value_t value;
};
template <class value_t>
struct alignas(LEVEL1_DCACHE_LINESIZE) atomic_node
{
std::atomic<value_t> value;
};
template <class value_t, template <class type_t> class allocator_t = std::allocator> class mpmc_key;
template <class value_t, template <class type_t> class allocator_t = std::allocator> class mpmc_ring_queue;
template <class value_t, template <class type_t> class allocator_t = std::allocator>
class alignas(LEVEL1_DCACHE_LINESIZE) mpmc_producer
{
public:
typedef value_t value_type;
typedef mpmc_key<value_t, allocator_t> key;
enum class result
{
success,
beaten,
busy,
queue_full
};
mpmc_producer(const key&, mpmc_ring_queue<value_t, allocator_t>& queue);
mpmc_producer(const mpmc_producer& other);
result try_enqueue_copy(const value_t& input);
result try_enqueue_move(value_t&& input);
private:
mpmc_producer() = delete;
mpmc_producer& operator=(const mpmc_producer& other) = delete;
mpmc_ring_queue<value_t, allocator_t>& queue_;
};
template <class value_t, template <class type_t> class allocator_t = std::allocator>
class alignas(LEVEL1_DCACHE_LINESIZE) mpmc_consumer
{
public:
typedef value_t value_type;
typedef mpmc_key<value_t, allocator_t> key;
enum class result
{
success,
beaten,
busy,
queue_empty
};
mpmc_consumer(const key&, mpmc_ring_queue<value_t, allocator_t>& queue);
mpmc_consumer(const mpmc_consumer& other);
result try_dequeue_copy(value_t& output);
result try_dequeue_move(value_t& output);
private:
mpmc_consumer() = delete;
mpmc_consumer& operator=(const mpmc_consumer& other) = delete;
mpmc_ring_queue<value_t, allocator_t>& queue_;
};
template <class value_t, template <class type_t> class allocator_t>
class TURBO_SYMBOL_DECL mpmc_ring_queue
{
public:
typedef value_t value_type;
typedef node<value_t> node_type;
typedef mpmc_producer<value_t, allocator_t> producer;
typedef mpmc_consumer<value_t, allocator_t> consumer;
typedef mpmc_key<value_t, allocator_t> key;
mpmc_ring_queue(uint32_t capacity);
mpmc_ring_queue(uint32_t capacity, uint16_t handle_limit);
producer& get_producer();
consumer& get_consumer();
typename producer::result try_enqueue_copy(const value_t& input);
typename producer::result try_enqueue_move(value_t&& input);
typename consumer::result try_dequeue_copy(value_t& output);
typename consumer::result try_dequeue_move(value_t& output);
private:
typedef std::vector<value_t, allocator_t<value_t>> vector_type;
template <class handle_t>
struct handle_list
{
handle_list(uint16_t limit, const key& the_key, mpmc_ring_queue<value_t, allocator_t>& queue);
std::atomic<uint16_t> counter;
std::vector<handle_t, allocator_t<handle_t>> list;
};
std::vector<node_type, allocator_t<node_type>> buffer_;
std::atomic<uint32_t> head_;
std::atomic<uint32_t> tail_;
handle_list<mpmc_producer<value_t, allocator_t>> producer_list;
handle_list<mpmc_consumer<value_t, allocator_t>> consumer_list;
};
template <template <class type_t> class allocator_t>
class TURBO_SYMBOL_DECL mpmc_ring_queue<std::uint32_t, allocator_t>
{
public:
typedef std::uint32_t value_type;
typedef atomic_node<std::uint32_t> node_type;
typedef mpmc_producer<std::uint32_t, allocator_t> producer;
typedef mpmc_consumer<std::uint32_t, allocator_t> consumer;
typedef mpmc_key<std::uint32_t, allocator_t> key;
mpmc_ring_queue(uint32_t capacity);
mpmc_ring_queue(uint32_t capacity, uint16_t handle_limit);
producer& get_producer();
consumer& get_consumer();
typename producer::result try_enqueue_copy(value_type input);
typename producer::result try_enqueue_move(value_type&& input);
typename consumer::result try_dequeue_copy(value_type& output);
typename consumer::result try_dequeue_move(value_type& output);
private:
typedef std::vector<std::uint32_t, allocator_t<std::uint32_t>> vector_type;
template <class handle_t>
struct handle_list
{
handle_list(uint16_t limit, const key& the_key, mpmc_ring_queue<std::uint32_t, allocator_t>& queue);
std::atomic<uint16_t> counter;
std::vector<handle_t, allocator_t<handle_t>> list;
};
std::vector<node_type, allocator_t<node_type>> buffer_;
std::atomic<uint32_t> head_;
std::atomic<uint32_t> tail_;
handle_list<mpmc_producer<std::uint32_t, allocator_t>> producer_list;
handle_list<mpmc_consumer<std::uint32_t, allocator_t>> consumer_list;
};
template <template <class type_t> class allocator_t>
class TURBO_SYMBOL_DECL mpmc_ring_queue<std::uint64_t, allocator_t>
{
public:
typedef std::uint64_t value_type;
typedef atomic_node<std::uint64_t> node_type;
typedef mpmc_producer<std::uint64_t, allocator_t> producer;
typedef mpmc_consumer<std::uint64_t, allocator_t> consumer;
typedef mpmc_key<std::uint64_t, allocator_t> key;
mpmc_ring_queue(uint32_t capacity);
mpmc_ring_queue(uint32_t capacity, uint16_t handle_limit);
producer& get_producer();
consumer& get_consumer();
typename producer::result try_enqueue_copy(value_type input);
typename producer::result try_enqueue_move(value_type&& input);
typename consumer::result try_dequeue_copy(value_type& output);
typename consumer::result try_dequeue_move(value_type& output);
private:
typedef std::vector<std::uint64_t, allocator_t<std::uint64_t>> vector_type;
template <class handle_t>
struct handle_list
{
handle_list(uint16_t limit, const key& the_key, mpmc_ring_queue<std::uint64_t, allocator_t>& queue);
std::atomic<uint16_t> counter;
std::vector<handle_t, allocator_t<handle_t>> list;
};
std::vector<node_type, allocator_t<node_type>> buffer_;
std::atomic<uint32_t> head_;
std::atomic<uint32_t> tail_;
handle_list<mpmc_producer<std::uint64_t, allocator_t>> producer_list;
handle_list<mpmc_consumer<std::uint64_t, allocator_t>> consumer_list;
};
} // namespace container
} // namespace turbo
#endif
<|endoftext|> |
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QApplication>
#include <QDebug>
#include <QDesktopWidget>
#include <QFile>
#include <QFileDialog>
#include <QIcon>
#include <QKeySequence>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QProcess>
#include <QSettings>
#include <QTextStream>
#include "aseconfigdialog.h"
#include "codeeditwidget.h"
MainWindow::MainWindow(QWidget* parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
editor(0)
{
ui->setupUi(this);
connectSignalsAndSlots();
setupActions();
readSettings();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::closeEvent(QCloseEvent* event)
{
// Attempt to close all tabs before we accept the close event
while (ui->tabWidget->count() > 0)
{
if (!closeTab(0)) {
event->ignore();
return;
}
}
writeSettings();
event->accept();
}
void MainWindow::showEvent(QShowEvent* event)
{
Q_UNUSED(event);
if (currentFile.isEmpty())
newFile();
}
void MainWindow::newFile()
{
loadFile(QString());
}
void MainWindow::open()
{
QString fileName = QFileDialog::getOpenFileName(this,
tr("Select an assembly file"),
pathToMostRecentFile,
tr("E100 Assembly Files (*.e)"));
if (!fileName.isEmpty()) {
pathToMostRecentFile = fileName;
loadFile(fileName);
}
}
bool MainWindow::save()
{
if (editor->save()) {
statusBar()->showMessage(tr("File saved"), 2000);
return true;
}
return false;
}
bool MainWindow::saveAs()
{
if (editor->saveAs()) {
updateCurrentFile();
statusBar()->showMessage(tr("File saved"), 2000);
return true;
}
return false;
}
bool MainWindow::closeTab(int index)
{
switchToTab(index);
QWidget* tab = ui->tabWidget->widget(index);
if (tab->close()) {
ui->tabWidget->removeTab(index);
// If all tabs have been closed, set editor to null and reset the window title
if (ui->tabWidget->count() == 0) {
editor = NULL;
updateCurrentFile();
}
return true;
}
return false;
}
bool MainWindow::closeActiveTab()
{
if (ui->tabWidget->count() > 0)
return closeTab(ui->tabWidget->currentIndex());
else
return 0;
}
void MainWindow::switchToTab(int index)
{
ui->tabWidget->setCurrentIndex(index);
}
void MainWindow::onTabSwitched(int index)
{
QWidget* tab = ui->tabWidget->widget(index);
CodeEditWidget* codeEdit = qobject_cast<CodeEditWidget*>(tab);
setEditor(codeEdit);
}
void MainWindow::setEditor(CodeEditWidget* codeEdit)
{
if (codeEdit) {
// Disconnect signals and slots from the previous editor
if (editor) {
QPlainTextEdit* textEdit = editor->textEdit();
disconnect(ui->actionCut, SIGNAL(triggered(bool)), textEdit, SLOT(cut()));
disconnect(ui->actionCopy, SIGNAL(triggered(bool)), textEdit, SLOT(copy()));
disconnect(ui->actionPaste, SIGNAL(triggered(bool)), textEdit, SLOT(paste()));
disconnect(textEdit, SIGNAL(textChanged()), this, SLOT(onModifyCurrentFile()));
}
editor = codeEdit;
updateCurrentFile();
// Hook up the necessary signals and slots for the code editor
QPlainTextEdit* textEdit = editor->textEdit();
connect(ui->actionCut, SIGNAL(triggered(bool)), textEdit, SLOT(cut()));
connect(ui->actionCopy, SIGNAL(triggered(bool)), textEdit, SLOT(copy()));
connect(ui->actionPaste, SIGNAL(triggered(bool)), textEdit, SLOT(paste()));
connect(textEdit, SIGNAL(textChanged()), this, SLOT(onModifyCurrentFile()));
}
}
bool MainWindow::assemble()
{
// Assembly using ase100 is only supported on Windows and Linux
#if defined(Q_OS_LINUX) || defined(Q_OS_WIN)
QProcess process;
if (!pathToAse100.isEmpty()) {
process.setProcessChannelMode(QProcess::MergedChannels);
process.start(pathToAse100, QStringList() << "-a" << currentFile);
process.waitForFinished();
QString output = process.readAll();
if (!output.isEmpty()) {
QMessageBox::critical(this, tr("ase100"), output, QMessageBox::Ok);
statusBar()->showMessage(tr("File assembly via ase100 failed."), 3000);
} else {
QMessageBox::information(this, tr("ase100"),
tr("File successfully assembled!"),
QMessageBox::Ok);
statusBar()->showMessage(tr("File successfully assembled."), 3000);
}
}
return true;
#else
return false;
#endif
}
void MainWindow::configureAse()
{
AseConfigDialog* dialog = new AseConfigDialog(this, pathToAse100);
dialog->setWindowTitle("Configure ase100");
if (dialog->exec() == QDialog::Accepted) {
pathToAse100 = dialog->getPath();
}
}
void MainWindow::onModifyCurrentFile()
{
updateCurrentFile();
}
void MainWindow::connectSignalsAndSlots()
{
// Pair each action with a corresponding behavior in the MainWindow
connect(ui->actionNew, SIGNAL(triggered(bool)), this, SLOT(newFile()));
connect(ui->actionOpen, SIGNAL(triggered(bool)), this, SLOT(open()));
connect(ui->actionSave, SIGNAL(triggered(bool)), this, SLOT(save()));
connect(ui->actionSaveAs, SIGNAL(triggered(bool)), this, SLOT(saveAs()));
connect(ui->actionCloseFile, SIGNAL(triggered(bool)), this, SLOT(closeActiveTab()));
connect(ui->actionQuit, SIGNAL(triggered(bool)), QApplication::instance(), SLOT(quit()));
connect(ui->actionAssemble, SIGNAL(triggered(bool)), this, SLOT(assemble()));
connect(ui->actionConfigureAse, SIGNAL(triggered(bool)), this, SLOT(configureAse()));
connect(ui->tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int)));
connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(onTabSwitched(int)));
}
void MainWindow::setupActions()
{
// Set up keyboard shortcuts
ui->actionNew->setShortcut(QKeySequence::New);
ui->actionOpen->setShortcut(QKeySequence::Open);
ui->actionSave->setShortcut(QKeySequence::Save);
ui->actionSaveAs->setShortcut(QKeySequence::SaveAs);
ui->actionCloseFile->setShortcut(QKeySequence::Close);
ui->actionQuit->setShortcut(QKeySequence::Quit);
ui->actionCut->setShortcut(QKeySequence::Cut);
ui->actionCopy->setShortcut(QKeySequence::Copy);
ui->actionPaste->setShortcut(QKeySequence::Paste);
ui->actionAssemble->setShortcut(QKeySequence::Refresh);
// User should only be able to "assemble" on Linux or Windows
#if defined(Q_OS_LINUX) || defined(Q_OS_WIN)
ui->actionAssemble->setEnabled(true);
#else
ui->actionAssemble->setEnabled(false);
#endif
}
void MainWindow::readSettings()
{
QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
const QByteArray geometry = settings.value("geometry", QByteArray()).toByteArray();
if (geometry.isEmpty()) {
const QRect availableGeometry = QApplication::desktop()->availableGeometry(this);
resize(availableGeometry.width() / 3, availableGeometry.height() / 2);
move((availableGeometry.width() - width()) / 2,
(availableGeometry.height() - height()) / 2);
} else {
restoreGeometry(geometry);
}
QString defaultPathToAse100;
#if defined(Q_OS_LINUX)
defaultPathToAse100 = "ase100";
#elif defined(Q_OS_WIN)
defaultPathToAse100 = "ase100";
#else
defaultPathToAse100 = QString();
#endif
pathToAse100 = settings.value("pathToAse100", defaultPathToAse100).toString();
pathToMostRecentFile = settings.value("pathToMostRecentFile", QDir::homePath()).toString();
}
void MainWindow::writeSettings()
{
QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
settings.setValue("geometry", saveGeometry());
settings.setValue("pathToAse100", pathToAse100);
settings.setValue("pathToMostRecentFile", pathToMostRecentFile);
}
void MainWindow::updateCurrentFile()
{
currentFile = (editor) ? editor->fullFileName() : QString();
setWindowModified(false);
QString shownName = currentFile;
setWindowFilePath(shownName);
QString stripped = (editor) ? editor->fileName() : QString();
if (!stripped.isEmpty()) {
if (editor->textEdit()->document()->isModified())
stripped += "*";
setWindowTitle(stripped + " - asIDE");
ui->tabWidget->setTabText(ui->tabWidget->currentIndex(), stripped);
} else {
setWindowTitle("asIDE");
}
}
void MainWindow::loadFile(const QString& fileName)
{
CodeEditWidget* codeEdit;
if (ui->tabWidget->count() == 1 && editor->textEdit()->document()->isEmpty())
codeEdit = editor;
else
codeEdit = new CodeEditWidget();
codeEdit->setFileName(fileName);
if (codeEdit->load()) {
if (!fileName.isEmpty())
statusBar()->showMessage(tr("File loaded"), 2000);
setEditor(codeEdit);
const int index = ui->tabWidget->addTab(editor, editor->fileName());
switchToTab(index);
} else {
delete codeEdit;
statusBar()->showMessage(tr("File failed to load"), 3000);
}
}
<commit_msg>Added a check to the ase100 executable path<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QApplication>
#include <QDebug>
#include <QDesktopWidget>
#include <QFile>
#include <QFileDialog>
#include <QIcon>
#include <QKeySequence>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QProcess>
#include <QSettings>
#include <QTextStream>
#include "aseconfigdialog.h"
#include "codeeditwidget.h"
MainWindow::MainWindow(QWidget* parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
editor(0)
{
ui->setupUi(this);
connectSignalsAndSlots();
setupActions();
readSettings();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::closeEvent(QCloseEvent* event)
{
// Attempt to close all tabs before we accept the close event
while (ui->tabWidget->count() > 0)
{
if (!closeTab(0)) {
event->ignore();
return;
}
}
writeSettings();
event->accept();
}
void MainWindow::showEvent(QShowEvent* event)
{
Q_UNUSED(event);
if (currentFile.isEmpty())
newFile();
}
void MainWindow::newFile()
{
loadFile(QString());
}
void MainWindow::open()
{
QString fileName = QFileDialog::getOpenFileName(this,
tr("Select an assembly file"),
pathToMostRecentFile,
tr("E100 Assembly Files (*.e)"));
if (!fileName.isEmpty()) {
pathToMostRecentFile = fileName;
loadFile(fileName);
}
}
bool MainWindow::save()
{
if (editor->save()) {
statusBar()->showMessage(tr("File saved"), 2000);
return true;
}
return false;
}
bool MainWindow::saveAs()
{
if (editor->saveAs()) {
updateCurrentFile();
statusBar()->showMessage(tr("File saved"), 2000);
return true;
}
return false;
}
bool MainWindow::closeTab(int index)
{
switchToTab(index);
QWidget* tab = ui->tabWidget->widget(index);
if (tab->close()) {
ui->tabWidget->removeTab(index);
// If all tabs have been closed, set editor to null and reset the window title
if (ui->tabWidget->count() == 0) {
editor = NULL;
updateCurrentFile();
}
return true;
}
return false;
}
bool MainWindow::closeActiveTab()
{
if (ui->tabWidget->count() > 0)
return closeTab(ui->tabWidget->currentIndex());
else
return 0;
}
void MainWindow::switchToTab(int index)
{
ui->tabWidget->setCurrentIndex(index);
}
void MainWindow::onTabSwitched(int index)
{
QWidget* tab = ui->tabWidget->widget(index);
CodeEditWidget* codeEdit = qobject_cast<CodeEditWidget*>(tab);
setEditor(codeEdit);
}
void MainWindow::setEditor(CodeEditWidget* codeEdit)
{
if (codeEdit) {
// Disconnect signals and slots from the previous editor
if (editor) {
QPlainTextEdit* textEdit = editor->textEdit();
disconnect(ui->actionCut, SIGNAL(triggered(bool)), textEdit, SLOT(cut()));
disconnect(ui->actionCopy, SIGNAL(triggered(bool)), textEdit, SLOT(copy()));
disconnect(ui->actionPaste, SIGNAL(triggered(bool)), textEdit, SLOT(paste()));
disconnect(textEdit, SIGNAL(textChanged()), this, SLOT(onModifyCurrentFile()));
}
editor = codeEdit;
updateCurrentFile();
// Hook up the necessary signals and slots for the code editor
QPlainTextEdit* textEdit = editor->textEdit();
connect(ui->actionCut, SIGNAL(triggered(bool)), textEdit, SLOT(cut()));
connect(ui->actionCopy, SIGNAL(triggered(bool)), textEdit, SLOT(copy()));
connect(ui->actionPaste, SIGNAL(triggered(bool)), textEdit, SLOT(paste()));
connect(textEdit, SIGNAL(textChanged()), this, SLOT(onModifyCurrentFile()));
}
}
bool MainWindow::assemble()
{
// Assembly using ase100 is only supported on Windows and Linux
#if defined(Q_OS_LINUX) || defined(Q_OS_WIN)
QProcess process;
if (!pathToAse100.isEmpty()) {
process.setProcessChannelMode(QProcess::MergedChannels);
process.start(pathToAse100, QStringList() << "-a" << currentFile);
process.waitForFinished();
QString output = process.readAll();
if (!output.isEmpty()) {
QMessageBox::critical(this, tr("ase100"), output, QMessageBox::Ok);
statusBar()->showMessage(tr("File assembly via ase100 failed."), 3000);
} else {
QMessageBox::information(this, tr("ase100"),
tr("File successfully assembled!"),
QMessageBox::Ok);
statusBar()->showMessage(tr("File successfully assembled."), 3000);
}
} else {
const QMessageBox::StandardButton ret
= QMessageBox::warning(this, tr("asIDE"),
tr("The path to the ase100 "
"executable has not been set.\n"
"Do you want to set it now?"),
QMessageBox::Cancel | QMessageBox::Yes);
switch(ret)
{
case QMessageBox::Yes:
ui->actionConfigureAse->trigger();
break;
default:
break;
}
}
return true;
#else
return false;
#endif
}
void MainWindow::configureAse()
{
AseConfigDialog* dialog = new AseConfigDialog(this, pathToAse100);
dialog->setWindowTitle("Configure ase100");
if (dialog->exec() == QDialog::Accepted) {
pathToAse100 = dialog->getPath();
}
}
void MainWindow::onModifyCurrentFile()
{
updateCurrentFile();
}
void MainWindow::connectSignalsAndSlots()
{
// Pair each action with a corresponding behavior in the MainWindow
connect(ui->actionNew, SIGNAL(triggered(bool)), this, SLOT(newFile()));
connect(ui->actionOpen, SIGNAL(triggered(bool)), this, SLOT(open()));
connect(ui->actionSave, SIGNAL(triggered(bool)), this, SLOT(save()));
connect(ui->actionSaveAs, SIGNAL(triggered(bool)), this, SLOT(saveAs()));
connect(ui->actionCloseFile, SIGNAL(triggered(bool)), this, SLOT(closeActiveTab()));
connect(ui->actionQuit, SIGNAL(triggered(bool)), QApplication::instance(), SLOT(quit()));
connect(ui->actionAssemble, SIGNAL(triggered(bool)), this, SLOT(assemble()));
connect(ui->actionConfigureAse, SIGNAL(triggered(bool)), this, SLOT(configureAse()));
connect(ui->tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int)));
connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(onTabSwitched(int)));
}
void MainWindow::setupActions()
{
// Set up keyboard shortcuts
ui->actionNew->setShortcut(QKeySequence::New);
ui->actionOpen->setShortcut(QKeySequence::Open);
ui->actionSave->setShortcut(QKeySequence::Save);
ui->actionSaveAs->setShortcut(QKeySequence::SaveAs);
ui->actionCloseFile->setShortcut(QKeySequence::Close);
ui->actionQuit->setShortcut(QKeySequence::Quit);
ui->actionCut->setShortcut(QKeySequence::Cut);
ui->actionCopy->setShortcut(QKeySequence::Copy);
ui->actionPaste->setShortcut(QKeySequence::Paste);
ui->actionAssemble->setShortcut(QKeySequence::Refresh);
// User should only be able to "assemble" on Linux or Windows
#if defined(Q_OS_LINUX) || defined(Q_OS_WIN)
ui->actionAssemble->setEnabled(true);
#else
ui->actionAssemble->setEnabled(false);
#endif
}
void MainWindow::readSettings()
{
QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
const QByteArray geometry = settings.value("geometry", QByteArray()).toByteArray();
if (geometry.isEmpty()) {
const QRect availableGeometry = QApplication::desktop()->availableGeometry(this);
resize(availableGeometry.width() / 3, availableGeometry.height() / 2);
move((availableGeometry.width() - width()) / 2,
(availableGeometry.height() - height()) / 2);
} else {
restoreGeometry(geometry);
}
QString defaultPathToAse100;
#if defined(Q_OS_LINUX)
defaultPathToAse100 = "ase100";
#elif defined(Q_OS_WIN)
defaultPathToAse100 = "ase100";
#else
defaultPathToAse100 = QString();
#endif
pathToAse100 = settings.value("pathToAse100", defaultPathToAse100).toString();
pathToMostRecentFile = settings.value("pathToMostRecentFile", QDir::homePath()).toString();
}
void MainWindow::writeSettings()
{
QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
settings.setValue("geometry", saveGeometry());
settings.setValue("pathToAse100", pathToAse100);
settings.setValue("pathToMostRecentFile", pathToMostRecentFile);
}
void MainWindow::updateCurrentFile()
{
currentFile = (editor) ? editor->fullFileName() : QString();
setWindowModified(false);
QString shownName = currentFile;
setWindowFilePath(shownName);
QString stripped = (editor) ? editor->fileName() : QString();
if (!stripped.isEmpty()) {
if (editor->textEdit()->document()->isModified())
stripped += "*";
setWindowTitle(stripped + " - asIDE");
ui->tabWidget->setTabText(ui->tabWidget->currentIndex(), stripped);
} else {
setWindowTitle("asIDE");
}
}
void MainWindow::loadFile(const QString& fileName)
{
CodeEditWidget* codeEdit;
if (ui->tabWidget->count() == 1 && editor->textEdit()->document()->isEmpty())
codeEdit = editor;
else
codeEdit = new CodeEditWidget();
codeEdit->setFileName(fileName);
if (codeEdit->load()) {
if (!fileName.isEmpty())
statusBar()->showMessage(tr("File loaded"), 2000);
setEditor(codeEdit);
const int index = ui->tabWidget->addTab(editor, editor->fileName());
switchToTab(index);
} else {
delete codeEdit;
statusBar()->showMessage(tr("File failed to load"), 3000);
}
}
<|endoftext|> |
<commit_before>#include "math3d.h"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
float u[3];
u[0] = atof(argv[1]);
u[1] = atof(argv[2]);
u[2] = atof(argv[3]);
float v[3];
v[0] = atof(argv[4]);
v[1] = atof(argv[5]);
v[2] = atof(argv[6]);
Vector3 x(u[0], u[1], u[2]);
Vector3 y(v[0], v[1], v[2]);
Vector3 r = x + y;
printf("r = %.5f, %.5f, %.5f\n", r.x, r.y, r.z);
return 0;
}
<commit_msg>re-arranged driver a bit for easier debugging of disassembly.<commit_after>#include "math3d.h"
#include <stdio.h>
#include <stdlib.h>
float u[3];
float v[3];
Vector3 x;
Vector3 y;
Vector3 r;
int main(int argc, char* argv[])
{
u[0] = atof(argv[1]);
u[1] = atof(argv[2]);
u[2] = atof(argv[3]);
v[0] = atof(argv[4]);
v[1] = atof(argv[5]);
v[2] = atof(argv[6]);
x.Set(u[0], u[1], u[2]);
y.Set(v[0], v[1], v[2]);
r = x + y;
printf("r = %.5f, %.5f, %.5f\n", r.x, r.y, r.z);
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Part: [skip ci] include missing header file<commit_after><|endoftext|> |
<commit_before>/* Copyright (c) 2018 PaddlePaddle Authors. 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 "paddle/fluid/framework/data_layout_transform.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/memory/malloc.h"
#include "paddle/fluid/operators/transpose_op.h"
#include "paddle/fluid/platform/mkldnn_reuse.h"
namespace paddle {
namespace operators {
using Tensor = framework::Tensor;
using framework::DataLayout;
template <typename T>
class TransposeMKLDNNOpKernel : public paddle::framework::OpKernel<T> {
public:
void Compute(const paddle::framework::ExecutionContext& ctx) const override {
PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),
"It must use CPUPlace.");
auto& dev_ctx =
ctx.template device_context<paddle::platform::MKLDNNDeviceContext>();
const auto& mkldnn_engine = dev_ctx.GetEngine();
std::vector<int> axis = ctx.Attr<std::vector<int>>("axis");
int ndims = axis.size();
auto* input = ctx.Input<Tensor>("X");
auto* output = ctx.Output<Tensor>("Out");
const T* input_data = input->data<T>();
if (ndims == 1) {
output->ShareDataWith(*input);
return;
}
auto nchw_tz = paddle::framework::vectorize<int64_t>(input->dims());
const std::string key = platform::CreateKey(nchw_tz, ctx.OutputName("Out"));
platform::TransposeMKLDNNHandler<T> handler(nchw_tz, axis, dev_ctx,
mkldnn_engine, key);
auto transpose_src_memory_p = handler.AcquireSrcMemory(
input->format(), platform::to_void_cast<T>(input_data));
auto transpose_dst_memory_p =
handler.AcquireDstMemory(output, ctx.GetPlace());
auto transpose_p = handler.AcquireTranspose(transpose_dst_memory_p,
transpose_src_memory_p);
mkldnn::stream astream(mkldnn_engine);
transpose_p->execute(astream, *transpose_src_memory_p,
*transpose_dst_memory_p);
astream.wait();
output->set_layout(DataLayout::kNCHW);
output->set_format(MKLDNNMemoryFormat::undef);
}
};
template <typename T>
class TransposeMKLDNNGradOpKernel : public paddle::framework::OpKernel<T> {
public:
void Compute(const paddle::framework::ExecutionContext& ctx) const override {
PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),
"It must use CPUPlace.");
auto* out_grad =
ctx.Input<framework::Tensor>(framework::GradVarName("Out"));
auto* x_grad = ctx.Output<framework::Tensor>(framework::GradVarName("X"));
if (!x_grad) return;
auto& dev_ctx =
ctx.template device_context<paddle::platform::MKLDNNDeviceContext>();
const auto& mkldnn_engine = dev_ctx.GetEngine();
std::vector<int> axis = ctx.Attr<std::vector<int>>("axis");
std::vector<int> reversed_axis(axis);
int ndims = axis.size();
if (ndims == 1) {
x_grad->ShareDataWith(*out_grad);
return;
}
for (size_t i = 0; i < axis.size(); i++) {
reversed_axis[axis[i]] = i;
}
const T* out_grad_data = out_grad->data<T>();
x_grad->mutable_data<T>(ctx.GetPlace());
auto nchw_tz = paddle::framework::vectorize<int64_t>(out_grad->dims());
const std::string key = platform::CreateKey(
nchw_tz, ctx.OutputName(framework::GradVarName("X")));
platform::TransposeMKLDNNHandler<T> handler(nchw_tz, reversed_axis, dev_ctx,
mkldnn_engine, key);
auto transpose_src_memory_p = handler.AcquireSrcMemory(
out_grad->format(), platform::to_void_cast<T>(out_grad_data));
auto transpose_dst_memory_p =
handler.AcquireDstMemory(x_grad, ctx.GetPlace());
auto transpose_p = handler.AcquireTranspose(transpose_dst_memory_p,
transpose_src_memory_p);
mkldnn::stream astream(mkldnn_engine);
transpose_p->execute(astream, *transpose_src_memory_p,
*transpose_dst_memory_p);
astream.wait();
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(transpose2, MKLDNN,
::paddle::platform::CPUPlace, FP32,
ops::kTransposeMKLDNNFP32,
ops::TransposeMKLDNNOpKernel<float>);
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(transpose2, MKLDNN,
::paddle::platform::CPUPlace, U8,
ops::kTransposeMKLDNNINT8,
ops::TransposeMKLDNNOpKernel<uint8_t>);
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(transpose2, MKLDNN,
::paddle::platform::CPUPlace, S8,
ops::kTransposeMKLDNNINT8,
ops::TransposeMKLDNNOpKernel<int8_t>);
REGISTER_OP_KERNEL(transpose, MKLDNN, ::paddle::platform::CPUPlace,
ops::TransposeMKLDNNOpKernel<float>);
REGISTER_OP_KERNEL(transpose_grad, MKLDNN, ::paddle::platform::CPUPlace,
ops::TransposeMKLDNNGradOpKernel<float>);
REGISTER_OP_KERNEL(transpose2_grad, MKLDNN, ::paddle::platform::CPUPlace,
ops::TransposeMKLDNNGradOpKernel<float>);
<commit_msg>transpose_mkldnn code change to meet Paddle standards (#22591)<commit_after>/* Copyright (c) 2018 PaddlePaddle Authors. 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 "paddle/fluid/framework/data_layout_transform.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/memory/malloc.h"
#include "paddle/fluid/operators/transpose_op.h"
#include "paddle/fluid/platform/mkldnn_reuse.h"
namespace paddle {
namespace operators {
using Tensor = framework::Tensor;
using framework::DataLayout;
template <typename T>
class TransposeMKLDNNOpKernel : public paddle::framework::OpKernel<T> {
public:
void Compute(const paddle::framework::ExecutionContext& ctx) const override {
PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),
"It must use CPUPlace.");
auto& dev_ctx =
ctx.template device_context<paddle::platform::MKLDNNDeviceContext>();
const auto& mkldnn_engine = dev_ctx.GetEngine();
std::vector<int> axis = ctx.Attr<std::vector<int>>("axis");
int ndims = axis.size();
auto* input = ctx.Input<Tensor>("X");
auto* output = ctx.Output<Tensor>("Out");
const T* input_data = input->data<T>();
if (ndims == 1) {
framework::TensorCopy(*input, input->place(), output);
output->set_format(input->format());
return;
}
auto nchw_tz = paddle::framework::vectorize<int64_t>(input->dims());
const std::string key = platform::CreateKey(nchw_tz, ctx.OutputName("Out"));
platform::TransposeMKLDNNHandler<T> handler(nchw_tz, axis, dev_ctx,
mkldnn_engine, key);
auto transpose_src_memory_p = handler.AcquireSrcMemory(
input->format(), platform::to_void_cast<T>(input_data));
auto transpose_dst_memory_p =
handler.AcquireDstMemory(output, ctx.GetPlace());
auto transpose_p = handler.AcquireTranspose(transpose_dst_memory_p,
transpose_src_memory_p);
mkldnn::stream astream(mkldnn_engine);
transpose_p->execute(astream, *transpose_src_memory_p,
*transpose_dst_memory_p);
astream.wait();
output->set_layout(DataLayout::kNCHW);
output->set_format(MKLDNNMemoryFormat::undef);
}
};
template <typename T>
class TransposeMKLDNNGradOpKernel : public paddle::framework::OpKernel<T> {
public:
void Compute(const paddle::framework::ExecutionContext& ctx) const override {
PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),
"It must use CPUPlace.");
auto* out_grad =
ctx.Input<framework::Tensor>(framework::GradVarName("Out"));
auto* x_grad = ctx.Output<framework::Tensor>(framework::GradVarName("X"));
if (!x_grad) return;
auto& dev_ctx =
ctx.template device_context<paddle::platform::MKLDNNDeviceContext>();
const auto& mkldnn_engine = dev_ctx.GetEngine();
std::vector<int> axis = ctx.Attr<std::vector<int>>("axis");
std::vector<int> reversed_axis(axis);
int ndims = axis.size();
if (ndims == 1) {
framework::TensorCopy(*out_grad, out_grad->place(), x_grad);
x_grad->set_format(out_grad->format());
return;
}
for (size_t i = 0; i < axis.size(); i++) {
reversed_axis[axis[i]] = i;
}
const T* out_grad_data = out_grad->data<T>();
x_grad->mutable_data<T>(ctx.GetPlace());
auto nchw_tz = paddle::framework::vectorize<int64_t>(out_grad->dims());
const std::string key = platform::CreateKey(
nchw_tz, ctx.OutputName(framework::GradVarName("X")));
platform::TransposeMKLDNNHandler<T> handler(nchw_tz, reversed_axis, dev_ctx,
mkldnn_engine, key);
auto transpose_src_memory_p = handler.AcquireSrcMemory(
out_grad->format(), platform::to_void_cast<T>(out_grad_data));
auto transpose_dst_memory_p =
handler.AcquireDstMemory(x_grad, ctx.GetPlace());
auto transpose_p = handler.AcquireTranspose(transpose_dst_memory_p,
transpose_src_memory_p);
mkldnn::stream astream(mkldnn_engine);
transpose_p->execute(astream, *transpose_src_memory_p,
*transpose_dst_memory_p);
astream.wait();
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(transpose2, MKLDNN,
::paddle::platform::CPUPlace, FP32,
ops::kTransposeMKLDNNFP32,
ops::TransposeMKLDNNOpKernel<float>);
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(transpose2, MKLDNN,
::paddle::platform::CPUPlace, U8,
ops::kTransposeMKLDNNINT8,
ops::TransposeMKLDNNOpKernel<uint8_t>);
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(transpose2, MKLDNN,
::paddle::platform::CPUPlace, S8,
ops::kTransposeMKLDNNINT8,
ops::TransposeMKLDNNOpKernel<int8_t>);
REGISTER_OP_KERNEL(transpose, MKLDNN, ::paddle::platform::CPUPlace,
ops::TransposeMKLDNNOpKernel<float>);
REGISTER_OP_KERNEL(transpose_grad, MKLDNN, ::paddle::platform::CPUPlace,
ops::TransposeMKLDNNGradOpKernel<float>);
REGISTER_OP_KERNEL(transpose2_grad, MKLDNN, ::paddle::platform::CPUPlace,
ops::TransposeMKLDNNGradOpKernel<float>);
<|endoftext|> |
<commit_before>/* Nom: main.cpp
* Description: module sous-système de contrôle: gestion du dialogue
avec l'utilisateur et interface graphique
* Date: 22.03.2014
* version : 1.0
* responsable du module : Pauline Maury Laribière
* groupe : Alexandre Devienne, Pauline Maury Laribière
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <GL/glui.h>
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
extern "C"
{
#include "sim.h"
#include "constantes.h"
}
// id for all callbacks
// file_cb
#define SAVE 0
#define LOAD 1
// simulation_cb
#define START 0
#define STEP 1
void next_step(void);
//fonction pour GLUI
void display(void);
void reshape(int w, int h);
void file_cb(int id);
void simulation_cb(int id);
void idle(void);
//fonction pour le mode GRAPHIC
static void initOpenGl(void);
static void initGlui();
// Mode of the simulation to be ran on, see specs sheet for details
typedef enum Mode {ERROR, FORCE, INTEGRATION, GRAPHIC, SIMULATION, MODE_UNSET} MODE;
// Return the mode read from a string (argv[1])
// return MODE_UNSET if string wasn't valid
static MODE read_mode(const char string[]);
namespace
{
//GLUI* glui;
int main_window;
GLUI_Panel *file;
GLUI_Panel *simulation;
GLUI_Panel *information;
GLUI_EditText *saveFile;
GLUI_EditText *loadFile;
GLUI_EditText *nb_trou_noir;
GLUI_EditText *nb_generateur;
GLUI_EditText *nb_particule;
bool simulation_running = false;
GLfloat left = -50,
right= 50,
down = -50,
up = 50;
double aspect_ratio;
}
int main (int argc, char *argv[])
{
MODE mode = MODE_UNSET;
if(argc==3) {
mode = read_mode(argv[1]);
}
switch(mode) {
case ERROR: sim_error(argv[2]);
break;
case FORCE: sim_force(argv[2]);
break;
case INTEGRATION: //sim_integration(argv[2]);
break;
case GRAPHIC:
sim_graphic(argv[2]);
glutInit(&argc, argv);
initOpenGl();
glutMainLoop();
break;
case SIMULATION:
sim_simulation(argv[2]);
break;
case MODE_UNSET:
default :
printf("Syntaxe attendue : sim.x "
"[Error|Force|Integration|Graphic|Simulation,"
"nom_fichier]\n");
}
return EXIT_SUCCESS;
}
static MODE read_mode(const char string[])
{
MODE mode = MODE_UNSET;
if (strcmp(string, "Error" ) == 0) {
mode = ERROR;
} else if (strcmp(string, "Force" ) == 0) {
mode = FORCE;
} else if (strcmp(string, "Integration" ) == 0) {
mode = INTEGRATION;
} else if (strcmp(string, "Graphic" ) == 0) {
mode = GRAPHIC;
} else if (strcmp(string, "Simulation" ) == 0) {
mode = SIMULATION;
} else {
mode = MODE_UNSET;
}
return mode;
}
static void initOpenGl()
{
/*Initialise Glut and Create Window*/
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowPosition(200, 200);
glutInitWindowSize(250, 250);
main_window = glutCreateWindow("Microcosmos");
glClearColor(1.0, 1.0, 1.0, 0.0);
#ifdef DEBUG
printf("initOpengl\n");
#endif
/* Fonctions callback*/
GLUI_Master.set_glutDisplayFunc(display);
GLUI_Master.set_glutReshapeFunc(reshape);
//GLUI_Master.set_glutMouseFunc(mouse);
//glutMotionFunc(move_entity);
//GLUI_Master.set_glutKeyboardFunc(keyboard);
GLUI_Master.set_glutIdleFunc(idle);
initGlui();
}
static void initGlui() {
/*Code GLUI pour l'interface*/
GLUI *glui = GLUI_Master.create_glui( "GLUI", 0, 400, 50 );
//File
file = glui->add_panel("File" );
loadFile = glui-> add_edittext_to_panel(file, "Filename",
GLUI_EDITTEXT_TEXT);
glui-> add_button_to_panel(file,"Load", LOAD, file_cb);
saveFile = glui-> add_edittext_to_panel(file, "Filename",
GLUI_EDITTEXT_TEXT);
glui-> add_button_to_panel(file,"Save", SAVE, file_cb);
//Simulation
simulation = glui->add_panel("Simulation");
glui->add_button_to_panel(simulation ,"Start", START, simulation_cb);
glui->add_button_to_panel(simulation ,"Step", STEP, simulation_cb);
//Information
information = glui->add_panel("Information" );
nb_particule = glui-> add_edittext_to_panel(information, "Nb Particule",
GLUI_EDITTEXT_INT);
nb_generateur = glui-> add_edittext_to_panel(information, "Nb Generateur",
GLUI_EDITTEXT_INT);
nb_trou_noir = glui-> add_edittext_to_panel(information, "Nb Trou noir",
GLUI_EDITTEXT_INT);
glui->add_button( "Quit", EXIT_SUCCESS, (GLUI_Update_CB) exit);
glui->set_main_gfx_window( main_window );
}
void update_nbEntities() {
int nbEntities[ENTITY_NB] = {0};
sim_nbEntities(nbEntities);
nb_generateur->set_int_val(nbEntities[GEN_SLOT]);
nb_trou_noir ->set_int_val(nbEntities[BCKH_SLOT]);
nb_particule ->set_int_val(nbEntities[PART_SLOT]);
}
void idle()
{
if ( glutGetWindow() != main_window )
glutSetWindow(main_window);
if (simulation_running) {
next_step();
}
glutPostRedisplay();
}
void next_step(void)
{
//met a jour simulation
sim_next_step();
//met a jour affichage
glutPostRedisplay();
}
//Réponse à l'interface utilisateur partie simulation
void simulation_cb(int id)
{
switch(id)
{
case START:
if (simulation_running) {
glutIdleFunc(NULL);
simulation_running = false;
} else {
glutIdleFunc(idle);
simulation_running = true;
}
// TODO change name of button
// via hiding/showing the button ?
break;
case STEP:
next_step();
break;
exit(0);
break;
default:
printf("Wrong ID in %s\n", __func__);
}
}
void display(void)
{
POINT bottom_left;
POINT up_right;
glClearColor ( 1., 1., 1., 0. ); // specifie la couleur
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
bottom_left = sim_bottom_left();
up_right = sim_up_right();
left = bottom_left.x - RMAX;
right = up_right.x + RMAX;
down = bottom_left.y - RMAX;
up = up_right.y + RMAX;
// update glOrtho
if (aspect_ratio <= 1.)
glOrtho(left, right, down/aspect_ratio, up/aspect_ratio, -1.0, 1.0);
else
glOrtho(left*aspect_ratio, right*aspect_ratio, down, up, -1.0, 1.0);
sim_display();
//met à jour nb éléments
update_nbEntities();
glutSwapBuffers();
}
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
aspect_ratio = (float) w/h;
glutPostRedisplay();
}
//Réponse à l'interface utilisateur partie fichier
void file_cb(int id) {
switch(id) {
case SAVE:
glutIdleFunc(NULL);
sim_save(saveFile->get_text());
break;
case LOAD:
glutIdleFunc(NULL);
sim_clean();
sim_simulation(loadFile->get_text());
simulation_running = false;
reshape(glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT));
break;
default:
printf("Wrong id in %s\n",__func__);
}
glutPostRedisplay();
}
<commit_msg>juste corrégé erreur reshape<commit_after>/* Nom: main.cpp
* Description: module sous-système de contrôle: gestion du dialogue
avec l'utilisateur et interface graphique
* Date: 22.03.2014
* version : 1.0
* responsable du module : Pauline Maury Laribière
* groupe : Alexandre Devienne, Pauline Maury Laribière
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <GL/glui.h>
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
extern "C"
{
#include "sim.h"
#include "constantes.h"
}
// id for all callbacks
// file_cb
#define SAVE 0
#define LOAD 1
// simulation_cb
#define START 0
#define STEP 1
void next_step(void);
//fonction pour GLUI
void display(void);
void reshape(int w, int h);
void file_cb(int id);
void simulation_cb(int id);
void idle(void);
//fonction pour le mode GRAPHIC
static void initOpenGl(void);
static void initGlui();
// Mode of the simulation to be ran on, see specs sheet for details
typedef enum Mode {ERROR, FORCE, INTEGRATION, GRAPHIC, SIMULATION, MODE_UNSET} MODE;
// Return the mode read from a string (argv[1])
// return MODE_UNSET if string wasn't valid
static MODE read_mode(const char string[]);
namespace
{
//GLUI* glui;
int main_window;
GLUI_Panel *file;
GLUI_Panel *simulation;
GLUI_Panel *information;
GLUI_EditText *saveFile;
GLUI_EditText *loadFile;
GLUI_EditText *nb_trou_noir;
GLUI_EditText *nb_generateur;
GLUI_EditText *nb_particule;
bool simulation_running = false;
GLfloat left = -50,
right= 50,
down = -50,
up = 50;
double aspect_ratio;
}
int main (int argc, char *argv[])
{
MODE mode = MODE_UNSET;
if(argc==3) {
mode = read_mode(argv[1]);
}
switch(mode) {
case ERROR: sim_error(argv[2]);
break;
case FORCE: sim_force(argv[2]);
break;
case INTEGRATION: //sim_integration(argv[2]);
break;
case GRAPHIC:
sim_graphic(argv[2]);
glutInit(&argc, argv);
initOpenGl();
glutMainLoop();
break;
case SIMULATION:
sim_simulation(argv[2]);
break;
case MODE_UNSET:
default :
printf("Syntaxe attendue : sim.x "
"[Error|Force|Integration|Graphic|Simulation,"
"nom_fichier]\n");
}
return EXIT_SUCCESS;
}
static MODE read_mode(const char string[])
{
MODE mode = MODE_UNSET;
if (strcmp(string, "Error" ) == 0) {
mode = ERROR;
} else if (strcmp(string, "Force" ) == 0) {
mode = FORCE;
} else if (strcmp(string, "Integration" ) == 0) {
mode = INTEGRATION;
} else if (strcmp(string, "Graphic" ) == 0) {
mode = GRAPHIC;
} else if (strcmp(string, "Simulation" ) == 0) {
mode = SIMULATION;
} else {
mode = MODE_UNSET;
}
return mode;
}
static void initOpenGl()
{
/*Initialise Glut and Create Window*/
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowPosition(200, 200);
glutInitWindowSize(250, 250);
main_window = glutCreateWindow("Microcosmos");
glClearColor(1.0, 1.0, 1.0, 0.0);
#ifdef DEBUG
printf("initOpengl\n");
#endif
/* Fonctions callback*/
GLUI_Master.set_glutDisplayFunc(display);
GLUI_Master.set_glutReshapeFunc(reshape);
//GLUI_Master.set_glutMouseFunc(mouse);
//glutMotionFunc(move_entity);
//GLUI_Master.set_glutKeyboardFunc(keyboard);
GLUI_Master.set_glutIdleFunc(idle);
initGlui();
}
static void initGlui() {
/*Code GLUI pour l'interface*/
GLUI *glui = GLUI_Master.create_glui( "GLUI", 0, 400, 50 );
//File
file = glui->add_panel("File" );
loadFile = glui-> add_edittext_to_panel(file, "Filename",
GLUI_EDITTEXT_TEXT);
glui-> add_button_to_panel(file,"Load", LOAD, file_cb);
saveFile = glui-> add_edittext_to_panel(file, "Filename",
GLUI_EDITTEXT_TEXT);
glui-> add_button_to_panel(file,"Save", SAVE, file_cb);
//Simulation
simulation = glui->add_panel("Simulation");
glui->add_button_to_panel(simulation ,"Start", START, simulation_cb);
glui->add_button_to_panel(simulation ,"Step", STEP, simulation_cb);
//Information
information = glui->add_panel("Information" );
nb_particule = glui-> add_edittext_to_panel(information, "Nb Particule",
GLUI_EDITTEXT_INT);
nb_generateur = glui-> add_edittext_to_panel(information, "Nb Generateur",
GLUI_EDITTEXT_INT);
nb_trou_noir = glui-> add_edittext_to_panel(information, "Nb Trou noir",
GLUI_EDITTEXT_INT);
glui->add_button( "Quit", EXIT_SUCCESS, (GLUI_Update_CB) exit);
glui->set_main_gfx_window( main_window );
}
void update_nbEntities() {
int nbEntities[ENTITY_NB] = {0};
sim_nbEntities(nbEntities);
nb_generateur->set_int_val(nbEntities[GEN_SLOT]);
nb_trou_noir ->set_int_val(nbEntities[BCKH_SLOT]);
nb_particule ->set_int_val(nbEntities[PART_SLOT]);
}
void idle()
{
if ( glutGetWindow() != main_window )
glutSetWindow(main_window);
if (simulation_running) {
next_step();
}
glutPostRedisplay();
}
void next_step(void)
{
//met a jour simulation
sim_next_step();
//met a jour affichage
glutPostRedisplay();
}
//Réponse à l'interface utilisateur partie simulation
void simulation_cb(int id)
{
switch(id)
{
case START:
if (simulation_running) {
glutIdleFunc(NULL);
simulation_running = false;
} else {
glutIdleFunc(idle);
simulation_running = true;
}
// TODO change name of button
// via hiding/showing the button ?
break;
case STEP:
next_step();
break;
exit(0);
break;
default:
printf("Wrong ID in %s\n", __func__);
}
}
void display(void)
{
glClearColor ( 1., 1., 1., 0. ); // specifie la couleur
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
// update glOrtho
if (aspect_ratio <= 1.)
glOrtho(left, right, down/aspect_ratio, up/aspect_ratio, -1.0, 1.0);
else
glOrtho(left*aspect_ratio, right*aspect_ratio, down, up, -1.0, 1.0);
sim_display();
//met à jour nb éléments
update_nbEntities();
glutSwapBuffers();
}
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
POINT bottom_left;
POINT up_right;
bottom_left = sim_bottom_left();
up_right = sim_up_right();
left = bottom_left.x - RMAX;
right = up_right.x + RMAX;
down = bottom_left.y - RMAX;
up = up_right.y + RMAX;
aspect_ratio = (float) w/h;
glutPostRedisplay();
}
//Réponse à l'interface utilisateur partie fichier
void file_cb(int id) {
switch(id) {
case SAVE:
glutIdleFunc(NULL);
sim_save(saveFile->get_text());
break;
case LOAD:
glutIdleFunc(NULL);
sim_clean();
sim_simulation(loadFile->get_text());
simulation_running = false;
reshape(glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT));
break;
default:
printf("Wrong id in %s\n",__func__);
}
glutPostRedisplay();
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <GL/gl.h>
#include <X11/X.h>
#include <X11/Xlib.h>
#include <GL/glx.h>
#include <unistd.h>
// Required GL 2.1 funcs
typedef GLuint (*GlCreateShader)(GLenum);
GlCreateShader glCreateShader;
typedef void (*GlShaderSource)(GLuint, GLsizei, const GLchar**, const GLint*);
GlShaderSource glShaderSource;
typedef void (*GlCompileShader)(GLuint);
GlCompileShader glCompileShader;
typedef GLuint (*GlCreateProgram)();
GlCreateProgram glCreateProgram;
typedef void (*GlAttachShader)(GLuint, GLuint);
GlAttachShader glAttachShader;
typedef void (*GlLinkProgram)(GLuint);
GlLinkProgram glLinkProgram;
typedef void (*GlUseProgram)(GLuint);
GlUseProgram glUseProgram;
typedef void (*GlGetShaderiv)(GLuint, GLenum, GLint*);
GlGetShaderiv glGetShaderiv;
typedef void (*GlGetProgramiv)(GLuint, GLenum, GLint*);
GlGetProgramiv glGetProgramiv;
typedef void (*GlGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*);
GlGetShaderInfoLog glGetShaderInfoLog;
typedef void (*GlGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*);
GlGetProgramInfoLog glGetProgramInfoLog;
typedef void (*GlDetachShader)(GLuint, GLuint);
GlDetachShader glDetachShader;
typedef void (*GlDeleteShader)(GLuint);
GlDeleteShader glDeleteShader;
typedef void (*GlDeleteProgram)(GLuint);
GlDeleteProgram glDeleteProgram;
typedef GLuint (*GlGetUniformLocation)(GLuint, const GLchar*);
GlGetUniformLocation glGetUniformLocation;
typedef void (*GlUniform1f)(GLuint, GLfloat);
GlUniform1f glUniform1f;
namespace qm {
struct Env {
Display* dpy;
Window win;
GLXContext ctx;
};
struct Shader {
GLuint vs;
GLuint fs;
GLuint prog;
GLuint phaseLoc;
};
const GLchar* g_vs= "\
#version 120\n\
varying vec3 v_pos; \
varying vec3 v_normal; \
void main() \
{ \
gl_Position= vec4(gl_Vertex.xy, 0.0, 1.0); \
v_pos= (gl_ModelViewMatrix*gl_Vertex).xyz; \
v_normal= mat3(gl_ModelViewMatrix)*vec3(gl_Vertex.xy, -1.0); \
} \
\n";
const GLchar* g_fs= "\
#version 120\n\
uniform float u_phase; \
varying vec3 v_pos; \
varying vec3 v_normal; \
/* x emission, y translucency */ \
vec2 sample(vec3 p) \
{ \
float beam_a= \
abs(cos(p.x*10.0 - sign(p.x)*u_phase)*0.5 + 1.0)* \
0.001/(p.z*p.z + p.y*p.y) + \
0.01/((p.x*p.x + 0.01)*(p.z*p.z + p.y*p.y)*100.0 + 0.1); \
float hole_a= pow(min(1.0, 0.1/(dot(p, p))), 10.0); \
float lerp= clamp((1.0 - hole_a), 0.0, 1.0); \
return vec2(beam_a*lerp, lerp); \
} \
void main() \
{ \
vec3 n= normalize(v_normal); \
vec3 color= vec3(0.3, 0.8, 1.0); \
vec3 accum= vec3(0, 0, 0); \
float transparency= 1.0; \
const int steps= 45; \
for (int i= 0; i < steps; ++i) { \
vec2 s= sample(v_pos + n*2.0*float(i)/steps); \
accum += color*s.x*transparency; \
transparency *= s.y; \
} \
gl_FragColor= vec4(accum, 1.0); \
} \
\n";
typedef void (*voidFunc)();
voidFunc queryGlFunc(const char* name)
{
voidFunc f= glXGetProcAddressARB((const GLubyte*)name);
if (!f) {
std::printf("Failed to query function: %s", name);
std::abort();
}
return f;
}
void checkShaderStatus(GLuint shd)
{
GLint status;
glGetShaderiv(shd, GL_COMPILE_STATUS, &status);
if (!status) {
const GLsizei max_len= 512;
GLchar log[max_len];
glGetShaderInfoLog(shd, max_len, NULL, log);
std::printf("Shader compilation failed: %s", log);
std::abort();
}
}
void checkProgramStatus(GLuint prog)
{
GLint link_status;
glGetProgramiv(prog, GL_LINK_STATUS, &link_status);
if (!link_status) {
const GLsizei size= 512;
GLchar log[size];
glGetProgramInfoLog(prog, size, NULL, log);
std::printf("Program link failed: %s", log);
std::abort();
}
}
void init(Env& env, Shader& shd)
{
{ // Create window
env.dpy= XOpenDisplay(NULL);
if(env.dpy == NULL)
std::abort();
Window root= DefaultRootWindow(env.dpy);
GLint att[]= { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
XVisualInfo* vi= glXChooseVisual(env.dpy, 0, att);
if(vi == NULL)
std::abort();
Colormap cmap;
cmap= XCreateColormap(env.dpy, root, vi->visual, AllocNone);
XSetWindowAttributes swa;
swa.colormap= cmap;
swa.event_mask= ExposureMask | KeyPressMask;
env.win=
XCreateWindow( env.dpy,
root,
0, 0, 600, 600, 0,
vi->depth,
InputOutput,
vi->visual,
CWColormap | CWEventMask,
&swa);
XMapWindow(env.dpy, env.win);
XStoreName(env.dpy, env.win, "QM Test");
env.ctx= glXCreateContext(env.dpy, vi, NULL, GL_TRUE);
glXMakeCurrent(env.dpy, env.win, env.ctx);
}
{ // Query necessary GL functions
glCreateShader= (GlCreateShader)queryGlFunc("glCreateShader");
glShaderSource= (GlShaderSource)queryGlFunc("glShaderSource");
glCompileShader= (GlCompileShader)queryGlFunc("glCompileShader");
glCreateProgram= (GlCreateProgram)queryGlFunc("glCreateProgram");
glAttachShader= (GlAttachShader)queryGlFunc("glAttachShader");
glLinkProgram= (GlLinkProgram)queryGlFunc("glLinkProgram");
glUseProgram= (GlUseProgram)queryGlFunc("glUseProgram");
glGetShaderiv= (GlGetShaderiv)queryGlFunc("glGetShaderiv");
glGetProgramiv= (GlGetProgramiv)queryGlFunc("glGetProgramiv");
glGetShaderInfoLog= (GlGetShaderInfoLog)queryGlFunc("glGetShaderInfoLog");
glGetProgramInfoLog= (GlGetProgramInfoLog)queryGlFunc("glGetProgramInfoLog");
glDetachShader= (GlDetachShader)queryGlFunc("glDetachShader");
glDeleteShader= (GlDeleteShader)queryGlFunc("glDeleteShader");
glDeleteProgram= (GlDeleteProgram)queryGlFunc("glDeleteProgram");
glGetUniformLocation= (GlGetUniformLocation)queryGlFunc("glGetUniformLocation");
glUniform1f= (GlUniform1f)queryGlFunc("glUniform1f");
}
{ // Create shaders
{ // Vertex
shd.vs= glCreateShader(GL_VERTEX_SHADER);
glShaderSource(shd.vs, 1, &g_vs, NULL);
glCompileShader(shd.vs);
checkShaderStatus(shd.vs);
}
{ // Fragment
shd.fs= glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(shd.fs, 1, &g_fs, NULL);
glCompileShader(shd.fs);
checkShaderStatus(shd.fs);
}
{ // Shader program
shd.prog= glCreateProgram();
glAttachShader(shd.prog, shd.vs);
glAttachShader(shd.prog, shd.fs);
glLinkProgram(shd.prog);
checkProgramStatus(shd.prog);
shd.phaseLoc= glGetUniformLocation(shd.prog, "u_phase");
}
}
{ // Setup initial GL state
glClearColor(0.0, 0.0, 0.0, 0.0);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
}
void quit(const Env& env, const Shader& shd)
{
{ // Close window
glXMakeCurrent(env.dpy, None, NULL);
glXDestroyContext(env.dpy, env.ctx);
XDestroyWindow(env.dpy, env.win);
XCloseDisplay(env.dpy);
}
{ // Destroy shaders
glDetachShader(shd.prog, shd.vs);
glDeleteShader(shd.vs);
glDetachShader(shd.prog, shd.fs);
glDeleteShader(shd.fs);
glDeleteProgram(shd.prog);
}
}
void draw(const Shader& shd, float x, float y)
{
static float phase;
static float prev_x, prev_y;
phase += 0.3;
// Smooth rotating
x= prev_x*0.5 + x*0.5;
y= prev_y*0.5 + y*0.5;
prev_x= x;
prev_y= y;
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(std::sqrt(x*x + y*y)*200.0, y, -x, 0.0);
glUseProgram(shd.prog);
glUniform1f(shd.phaseLoc, phase);
glBegin(GL_QUADS);
glVertex3f(-1, -1, 1);
glVertex3f(1, -1, 1);
glVertex3f(1, 1, 1);
glVertex3f(-1, 1, 1);
glEnd();
}
bool loop(const Env& env, const Shader& shd)
{
int root_x= 0, root_y= 0;
Window w;
int win_x, win_y;
unsigned int mask_return;
XQueryPointer( env.dpy, env.win, &w,
&w, &root_x, &root_y, &win_x, &win_y,
&mask_return);
XWindowAttributes gwa;
XGetWindowAttributes(env.dpy, env.win, &gwa);
glViewport(0, 0, gwa.width, gwa.height);
qm::draw( shd,
2.0*win_x/gwa.width - 1.0,
1.0 - 2.0*win_y/gwa.height);
usleep(1);
glXSwapBuffers(env.dpy, env.win);
while(XPending(env.dpy)) {
XEvent xev;
XNextEvent(env.dpy, &xev);
if(xev.type == KeyPress)
return false;
}
return true;
}
} // qm
int main()
{
qm::Env env;
qm::Shader shd;
qm::init(env, shd);
while(loop(env, shd));
qm::quit(env, shd);
}
<commit_msg>Cosmetic changes<commit_after>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <GL/gl.h>
#include <X11/X.h>
#include <X11/Xlib.h>
#include <GL/glx.h>
#include <unistd.h>
// Required GL 2.1 funcs
typedef GLuint (*GlCreateShader)(GLenum);
GlCreateShader glCreateShader;
typedef void (*GlShaderSource)(GLuint, GLsizei, const GLchar**, const GLint*);
GlShaderSource glShaderSource;
typedef void (*GlCompileShader)(GLuint);
GlCompileShader glCompileShader;
typedef GLuint (*GlCreateProgram)();
GlCreateProgram glCreateProgram;
typedef void (*GlAttachShader)(GLuint, GLuint);
GlAttachShader glAttachShader;
typedef void (*GlLinkProgram)(GLuint);
GlLinkProgram glLinkProgram;
typedef void (*GlUseProgram)(GLuint);
GlUseProgram glUseProgram;
typedef void (*GlGetShaderiv)(GLuint, GLenum, GLint*);
GlGetShaderiv glGetShaderiv;
typedef void (*GlGetProgramiv)(GLuint, GLenum, GLint*);
GlGetProgramiv glGetProgramiv;
typedef void (*GlGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*);
GlGetShaderInfoLog glGetShaderInfoLog;
typedef void (*GlGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*);
GlGetProgramInfoLog glGetProgramInfoLog;
typedef void (*GlDetachShader)(GLuint, GLuint);
GlDetachShader glDetachShader;
typedef void (*GlDeleteShader)(GLuint);
GlDeleteShader glDeleteShader;
typedef void (*GlDeleteProgram)(GLuint);
GlDeleteProgram glDeleteProgram;
typedef GLuint (*GlGetUniformLocation)(GLuint, const GLchar*);
GlGetUniformLocation glGetUniformLocation;
typedef void (*GlUniform1f)(GLuint, GLfloat);
GlUniform1f glUniform1f;
namespace qm {
struct Env {
Display* dpy;
Window win;
GLXContext ctx;
};
struct Shader {
GLuint vs;
GLuint fs;
GLuint prog;
GLuint phaseLoc;
};
const GLchar* g_vs= "\
#version 120\n\
varying vec3 v_pos; \
varying vec3 v_normal; \
void main() \
{ \
gl_Position= vec4(gl_Vertex.xy, 0.0, 1.0); \
v_pos= (gl_ModelViewMatrix*gl_Vertex).xyz; \
v_normal= mat3(gl_ModelViewMatrix)*vec3(gl_Vertex.xy, -1.0); \
} \
\n";
const GLchar* g_fs= "\
#version 120\n\
uniform float u_phase; \
varying vec3 v_pos; \
varying vec3 v_normal; \
/* x emission, y translucency */ \
vec2 sample(vec3 p) \
{ \
float beam_a= \
abs(cos(p.x*10.0 - sign(p.x)*u_phase)*0.5 + 1.0)* \
0.001/(p.z*p.z + p.y*p.y); \
float disc_a= \
0.01/((p.x*p.x + 0.01)*(p.z*p.z + p.y*p.y)*100.0 + 0.1); \
float hole_a= pow(min(1.0, 0.1/(dot(p, p))), 10.0); \
float lerp= clamp((1.0 - hole_a), 0.0, 1.0); \
return vec2((disc_a + beam_a)*lerp, lerp); \
} \
void main() \
{ \
vec3 n= normalize(v_normal); \
vec3 color= vec3(0.3, 0.8, 1.0); \
vec3 accum= vec3(0, 0, 0); \
float transparency= 1.0; \
const int steps= 45; \
for (int i= 0; i < steps; ++i) { \
vec2 s= sample(v_pos + n*2.0*float(i)/steps); \
accum += color*s.x*transparency; \
transparency *= s.y; \
} \
gl_FragColor= vec4(accum, 1.0); \
} \
\n";
typedef void (*voidFunc)();
voidFunc queryGlFunc(const char* name)
{
voidFunc f= glXGetProcAddressARB((const GLubyte*)name);
if (!f) {
std::printf("Failed to query function: %s", name);
std::abort();
}
return f;
}
void checkShaderStatus(GLuint shd)
{
GLint status;
glGetShaderiv(shd, GL_COMPILE_STATUS, &status);
if (!status) {
const GLsizei max_len= 512;
GLchar log[max_len];
glGetShaderInfoLog(shd, max_len, NULL, log);
std::printf("Shader compilation failed: %s", log);
std::abort();
}
}
void checkProgramStatus(GLuint prog)
{
GLint link_status;
glGetProgramiv(prog, GL_LINK_STATUS, &link_status);
if (!link_status) {
const GLsizei size= 512;
GLchar log[size];
glGetProgramInfoLog(prog, size, NULL, log);
std::printf("Program link failed: %s", log);
std::abort();
}
}
void init(Env& env, Shader& shd)
{
{ // Create window
env.dpy= XOpenDisplay(NULL);
if(env.dpy == NULL)
std::abort();
Window root= DefaultRootWindow(env.dpy);
GLint att[]= { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
XVisualInfo* vi= glXChooseVisual(env.dpy, 0, att);
if(vi == NULL)
std::abort();
Colormap cmap;
cmap= XCreateColormap(env.dpy, root, vi->visual, AllocNone);
XSetWindowAttributes swa;
swa.colormap= cmap;
swa.event_mask= ExposureMask | KeyPressMask;
env.win=
XCreateWindow( env.dpy,
root,
0, 0, 600, 600, 0,
vi->depth,
InputOutput,
vi->visual,
CWColormap | CWEventMask,
&swa);
XMapWindow(env.dpy, env.win);
XStoreName(env.dpy, env.win, "QM Test");
env.ctx= glXCreateContext(env.dpy, vi, NULL, GL_TRUE);
glXMakeCurrent(env.dpy, env.win, env.ctx);
}
{ // Query necessary GL functions
glCreateShader= (GlCreateShader)queryGlFunc("glCreateShader");
glShaderSource= (GlShaderSource)queryGlFunc("glShaderSource");
glCompileShader= (GlCompileShader)queryGlFunc("glCompileShader");
glCreateProgram= (GlCreateProgram)queryGlFunc("glCreateProgram");
glAttachShader= (GlAttachShader)queryGlFunc("glAttachShader");
glLinkProgram= (GlLinkProgram)queryGlFunc("glLinkProgram");
glUseProgram= (GlUseProgram)queryGlFunc("glUseProgram");
glGetShaderiv= (GlGetShaderiv)queryGlFunc("glGetShaderiv");
glGetProgramiv= (GlGetProgramiv)queryGlFunc("glGetProgramiv");
glGetShaderInfoLog= (GlGetShaderInfoLog)queryGlFunc("glGetShaderInfoLog");
glGetProgramInfoLog= (GlGetProgramInfoLog)queryGlFunc("glGetProgramInfoLog");
glDetachShader= (GlDetachShader)queryGlFunc("glDetachShader");
glDeleteShader= (GlDeleteShader)queryGlFunc("glDeleteShader");
glDeleteProgram= (GlDeleteProgram)queryGlFunc("glDeleteProgram");
glGetUniformLocation= (GlGetUniformLocation)queryGlFunc("glGetUniformLocation");
glUniform1f= (GlUniform1f)queryGlFunc("glUniform1f");
}
{ // Create shaders
{ // Vertex
shd.vs= glCreateShader(GL_VERTEX_SHADER);
glShaderSource(shd.vs, 1, &g_vs, NULL);
glCompileShader(shd.vs);
checkShaderStatus(shd.vs);
}
{ // Fragment
shd.fs= glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(shd.fs, 1, &g_fs, NULL);
glCompileShader(shd.fs);
checkShaderStatus(shd.fs);
}
{ // Shader program
shd.prog= glCreateProgram();
glAttachShader(shd.prog, shd.vs);
glAttachShader(shd.prog, shd.fs);
glLinkProgram(shd.prog);
checkProgramStatus(shd.prog);
shd.phaseLoc= glGetUniformLocation(shd.prog, "u_phase");
}
}
{ // Setup initial GL state
glClearColor(0.0, 0.0, 0.0, 0.0);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
}
void quit(const Env& env, const Shader& shd)
{
{ // Close window
glXMakeCurrent(env.dpy, None, NULL);
glXDestroyContext(env.dpy, env.ctx);
XDestroyWindow(env.dpy, env.win);
XCloseDisplay(env.dpy);
}
{ // Destroy shaders
glDetachShader(shd.prog, shd.vs);
glDeleteShader(shd.vs);
glDetachShader(shd.prog, shd.fs);
glDeleteShader(shd.fs);
glDeleteProgram(shd.prog);
}
}
void draw(const Shader& shd, float x, float y)
{
static float phase;
static float prev_x, prev_y;
phase += 0.3;
// Smooth rotating
x= prev_x*0.5 + x*0.5;
y= prev_y*0.5 + y*0.5;
prev_x= x;
prev_y= y;
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(std::sqrt(x*x + y*y)*200.0, y, -x, 0.0);
glUseProgram(shd.prog);
glUniform1f(shd.phaseLoc, phase);
glBegin(GL_QUADS);
glVertex3f(-1, -1, 1);
glVertex3f(1, -1, 1);
glVertex3f(1, 1, 1);
glVertex3f(-1, 1, 1);
glEnd();
}
bool loop(const Env& env, const Shader& shd)
{
int root_x= 0, root_y= 0;
Window w;
int win_x, win_y;
unsigned int mask_return;
XQueryPointer( env.dpy, env.win, &w,
&w, &root_x, &root_y, &win_x, &win_y,
&mask_return);
XWindowAttributes gwa;
XGetWindowAttributes(env.dpy, env.win, &gwa);
glViewport(0, 0, gwa.width, gwa.height);
qm::draw( shd,
2.0*win_x/gwa.width - 1.0,
1.0 - 2.0*win_y/gwa.height);
usleep(1);
glXSwapBuffers(env.dpy, env.win);
while(XPending(env.dpy)) {
XEvent xev;
XNextEvent(env.dpy, &xev);
if(xev.type == KeyPress)
return false;
}
return true;
}
} // qm
int main()
{
qm::Env env;
qm::Shader shd;
qm::init(env, shd);
while(loop(env, shd));
qm::quit(env, shd);
}
<|endoftext|> |
<commit_before>/**
* Copyright (C) 2012 by INdT
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This 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 Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @author Rodrigo Goncalves de Oliveira <[email protected]>
* @author Roger Felipe Zanoni da Silva <[email protected]>
*/
#include "imagelayer.h"
#include <QtCore/QDebug>
ImageLayer::ImageLayer(Layer *parent)
: Layer((QQuickItem *)parent)
, m_currentImage(0)
, m_tileWidth(32)
, m_tileHeight(32)
, m_drawType(Bacon2D::TiledDrawType)
, m_areaToDraw(2.0)
, m_columnOffset(0)
, m_latestPoint(0)
, m_globalXPos(0.0)
, m_localXPos(0.0)
, m_localYPos(0.0)
, m_initialized(false)
{
connect(this, SIGNAL(horizontalDirectionChanged()),
this, SLOT(onHorizontalDirectionChanged()));
}
ImageLayer::~ImageLayer()
{
m_pixmaps.clear();
}
//! Stores the source path for the image
/*!
* \param source the image path
*/
void ImageLayer::setSource(const QString &source)
{
if (m_source == source)
return;
m_source = source;
emit sourceChanged();
}
//! Gets the image source path
/*!
* \return the source path for the image
*/
QString ImageLayer::source() const
{
return m_source;
}
//! Stores the layer type
/*!
* \param drawType can be Tiled (default) or Plane
*/
void ImageLayer::setDrawType(Bacon2D::DrawType drawType)
{
if (m_drawType != drawType)
m_drawType = drawType;
}
//! Gets the layer type
/*!
* \return Tiled or Plane according the layer draw type
*/
Bacon2D::DrawType ImageLayer::drawType() const
{
return m_drawType;
}
void ImageLayer::setTileHeight(const int &value)
{
if (value == m_tileHeight)
return;
m_tileHeight = value;
emit tilesChanged();
}
void ImageLayer::setTileWidth(const int &value)
{
if (value == m_tileWidth)
return;
m_tileWidth = value;
emit tilesChanged();
}
//! Adds a tile on the list
/*!
* \param pix the pixmap to append on the list
* \return the list actual size or -1 if the layer can not accept tiled pixmaps
*/
int ImageLayer::addTile(const QPixmap &pixmap)
{
m_pixmaps.append(pixmap);
return m_pixmaps.size();
}
//! Gets a tile from the list
/*!
* \param pos the tile position on the list
* \return the tile pixmap of position pos on the list or null, if none
*/
QPixmap ImageLayer::getTile(int pos) const
{
return m_pixmaps.at(pos);
}
void ImageLayer::setDrawGrid(bool draw)
{
if (draw == m_drawGrid)
return;
m_drawGrid = draw;
}
void ImageLayer::setGridColor(const QColor &color)
{
if (color == m_gridColor)
return;
m_gridColor = color;
}
//! Gets the tiles pixmap list size
/*!
* \return the tiles pixmap list size
*/
int ImageLayer::count() const
{
return m_pixmaps.size();
}
void ImageLayer::generateOffsets()
{
bool completed = false;
int start = 0;
int step = m_numColumns;
int max = m_totalColumns;
int count = 0;
int maxCount = step * (int) m_areaToDraw;
bool first = true;
Offsets::OffsetsList firstPoint;
while (!completed) {
Offsets::OffsetsList offsetsList;
int size;
int end = 0;
bool finished = false;
while (count < maxCount) {
end = (start + step) % max;
if (end - start > 0) {
size = step;
count += size;
// TODO check this comparison. Is it really needed?
if (finished || count != maxCount) {
offsetsList.append(Offsets(start, size));
if (!finished)
start = end;
finished = false;
} else {
offsetsList.append(Offsets(start, size));
}
} else {
int oldStart = start;
size = max - start;
count += size;
offsetsList.append(Offsets(start, size));
size = step - size;
start = 0;
count += size;
if (size != 0) {
offsetsList.append(Offsets(0, size));
}
if (count <= maxCount / 2) {
start = size;
finished = true;
} else
start = oldStart;
}
}
count = 0;
if (offsetsList == firstPoint)
completed = true;
else
m_offsets.append(offsetsList);
if (first) {
firstPoint = offsetsList;
first = false;
}
}
}
void ImageLayer::updateTiles()
{
if ((boundingRect().width() == 0) || (boundingRect().height() == 0))
return;
// TODO create enums to define image aspect, auto tile, etc...
QPixmap pixmap(source()); // TODO
// If item height doesn't match pixmap height, scaleToHeight
if (pixmap.height() != (int)height()) {
pixmap = pixmap.scaledToHeight(height());
}
if (m_drawType == Bacon2D::PlaneDrawType) {
m_tileWidth = width();
m_tileHeight = height();
if (pixmap.width() % (int)width() != 0) {
// XXX create some log system?
qCritical() << QString("Bacon2D>>Image \'%1\' doesn't contains a proper size... CROPPING!").arg(source());
int newWidth = pixmap.width() - (pixmap.width() % (int)width());
pixmap = pixmap.copy(0, 0, newWidth, height());
}
}
if (pixmap.width() < boundingRect().width()) {
QPixmap temp(boundingRect().width(), boundingRect().height());
QPainter p(&temp);
p.drawTiledPixmap(boundingRect(), pixmap, QPoint(0,0));
p.end();
pixmap = temp;
}
if (m_type == Bacon2D::MirroredType) {
QPixmap temp(pixmap.width() * 2, pixmap.height());
QPainter p(&temp);
p.drawPixmap(0, 0, pixmap.width(), pixmap.height(), pixmap);
p.drawPixmap(pixmap.width(), 0, pixmap.width(), pixmap.height(),
pixmap.transformed(QTransform().scale(-1, 1), Qt::FastTransformation));
p.end();
pixmap = temp;
}
// visible tiles
m_numColumns = boundingRect().width() / m_tileWidth;
m_numRows = boundingRect().height() / m_tileHeight;
// total of columns and rows
m_totalColumns = pixmap.width() / m_tileWidth;
m_totalRows = pixmap.height() / m_tileHeight;
int i, j;
for (i = 0; i < m_totalRows; i++) {
for (j = 0; j < m_totalColumns; j++) {
QPixmap temp(m_tileWidth, m_tileHeight);
QPainter p(&temp);
p.setCompositionMode(QPainter::CompositionMode_Source);
p.drawPixmap(0, 0, m_tileWidth, m_tileHeight,
pixmap, j * m_tileWidth, i * m_tileHeight, m_tileWidth, m_tileHeight);
p.end();
addTile(temp);
}
}
generateOffsets();
drawPixmap();
}
QPixmap ImageLayer::generatePartialPixmap(int startPoint, int size)
{
QPixmap temp(m_tileWidth * size, boundingRect().height());
QPainter p(&temp);
int i, j;
int index = 0;
for (i = 0; i < m_numRows; i++) {
for (j = 0; j < size; j++) {
index = ((i * m_totalColumns) + (j + startPoint));
p.drawPixmap(j * m_tileWidth, i * m_tileHeight, getTile(index));
// just draw a grid
// XXX chech the possibility of drawn it only on a debug mode
if (m_drawGrid) {
p.setPen(m_gridColor);
p.drawRect(j * m_tileWidth, i * m_tileHeight, m_tileWidth, m_tileHeight);
}
}
}
p.end();
return temp;
}
void ImageLayer::drawPixmap()
{
if ((boundingRect().width() == 0) || (boundingRect().height() == 0))
return;
if (m_currentImage)
delete m_currentImage;
m_currentImage = new QImage(boundingRect().width() * m_areaToDraw,
boundingRect().height(), QImage::Format_ARGB32_Premultiplied);
QPainter p(m_currentImage);
int xPoint = 0;
for (int i = 0; i < m_offsets[m_columnOffset].size(); i++) {
Offsets offset = m_offsets[m_columnOffset].at(i);
QPixmap pixmap = generatePartialPixmap(offset.point(), offset.size());
p.drawPixmap(xPoint, 0, pixmap);
xPoint += pixmap.width();
m_latestPoint = offset.point();
}
if (m_horizontalStep > 0)
m_columnOffset = (m_columnOffset - 1 < 0) ? m_offsets.size() - 1 : m_columnOffset - 1;
else
m_columnOffset = (m_columnOffset + 1) % m_offsets.size();
p.end();
}
// move to a X value
void ImageLayer::moveX(const qreal &x)
{
qreal newValue = x;
qreal delta = m_globalXPos + newValue;
m_globalXPos = newValue * -1;
m_localXPos -= delta;
if (m_localXPos <= -width()) {
drawPixmap();
m_localXPos = width() + m_localXPos;
} else if (m_localXPos >= 0) {
if (m_globalXPos != 0) {
drawPixmap();
m_localXPos = -width() + m_localXPos;
} else
m_localXPos = 0;
}
}
void ImageLayer::moveY(const qreal &y)
{
Q_UNUSED(y);
// TBD
}
void ImageLayer::updateHorizontalStep()
{
m_currentHorizontalStep += m_horizontalStep;
if (m_currentHorizontalStep <= -width()) {
drawPixmap();
m_currentHorizontalStep = 0;
} else if (m_currentHorizontalStep >= 0) {
drawPixmap();
m_currentHorizontalStep = -width();
}
}
void ImageLayer::onHorizontalDirectionChanged()
{
if (m_offsets.count() != 0)
m_columnOffset = (m_columnOffset + 2) % m_offsets.size();
}
void ImageLayer::paint(QPainter *painter)
{
if (!m_currentImage)
return;
if (m_isAnimated)
updateHorizontalStep();
painter->drawImage(m_currentHorizontalStep, 0, *m_currentImage);
}
void ImageLayer::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
if (newGeometry.isEmpty() || m_initialized || !isComponentComplete())
return;
updateTiles();
m_initialized = true;
Layer::geometryChanged(newGeometry, oldGeometry);
}
void ImageLayer::componentComplete()
{
Layer::componentComplete();
if (m_initialized || boundingRect().isEmpty())
return;
updateTiles();
m_initialized = true;
}
<commit_msg>Don't ignore geometry changes to ImageLayer<commit_after>/**
* Copyright (C) 2012 by INdT
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This 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 Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @author Rodrigo Goncalves de Oliveira <[email protected]>
* @author Roger Felipe Zanoni da Silva <[email protected]>
*/
#include "imagelayer.h"
#include <QtCore/QDebug>
ImageLayer::ImageLayer(Layer *parent)
: Layer((QQuickItem *)parent)
, m_currentImage(0)
, m_tileWidth(32)
, m_tileHeight(32)
, m_drawType(Bacon2D::TiledDrawType)
, m_areaToDraw(2.0)
, m_columnOffset(0)
, m_latestPoint(0)
, m_globalXPos(0.0)
, m_localXPos(0.0)
, m_localYPos(0.0)
, m_initialized(false)
{
connect(this, SIGNAL(horizontalDirectionChanged()),
this, SLOT(onHorizontalDirectionChanged()));
}
ImageLayer::~ImageLayer()
{
m_pixmaps.clear();
}
//! Stores the source path for the image
/*!
* \param source the image path
*/
void ImageLayer::setSource(const QString &source)
{
if (m_source == source)
return;
m_source = source;
emit sourceChanged();
}
//! Gets the image source path
/*!
* \return the source path for the image
*/
QString ImageLayer::source() const
{
return m_source;
}
//! Stores the layer type
/*!
* \param drawType can be Tiled (default) or Plane
*/
void ImageLayer::setDrawType(Bacon2D::DrawType drawType)
{
if (m_drawType != drawType)
m_drawType = drawType;
}
//! Gets the layer type
/*!
* \return Tiled or Plane according the layer draw type
*/
Bacon2D::DrawType ImageLayer::drawType() const
{
return m_drawType;
}
void ImageLayer::setTileHeight(const int &value)
{
if (value == m_tileHeight)
return;
m_tileHeight = value;
emit tilesChanged();
}
void ImageLayer::setTileWidth(const int &value)
{
if (value == m_tileWidth)
return;
m_tileWidth = value;
emit tilesChanged();
}
//! Adds a tile on the list
/*!
* \param pix the pixmap to append on the list
* \return the list actual size or -1 if the layer can not accept tiled pixmaps
*/
int ImageLayer::addTile(const QPixmap &pixmap)
{
m_pixmaps.append(pixmap);
return m_pixmaps.size();
}
//! Gets a tile from the list
/*!
* \param pos the tile position on the list
* \return the tile pixmap of position pos on the list or null, if none
*/
QPixmap ImageLayer::getTile(int pos) const
{
return m_pixmaps.at(pos);
}
void ImageLayer::setDrawGrid(bool draw)
{
if (draw == m_drawGrid)
return;
m_drawGrid = draw;
}
void ImageLayer::setGridColor(const QColor &color)
{
if (color == m_gridColor)
return;
m_gridColor = color;
}
//! Gets the tiles pixmap list size
/*!
* \return the tiles pixmap list size
*/
int ImageLayer::count() const
{
return m_pixmaps.size();
}
void ImageLayer::generateOffsets()
{
bool completed = false;
int start = 0;
int step = m_numColumns;
int max = m_totalColumns;
int count = 0;
int maxCount = step * (int) m_areaToDraw;
bool first = true;
Offsets::OffsetsList firstPoint;
while (!completed) {
Offsets::OffsetsList offsetsList;
int size;
int end = 0;
bool finished = false;
while (count < maxCount) {
end = (start + step) % max;
if (end - start > 0) {
size = step;
count += size;
// TODO check this comparison. Is it really needed?
if (finished || count != maxCount) {
offsetsList.append(Offsets(start, size));
if (!finished)
start = end;
finished = false;
} else {
offsetsList.append(Offsets(start, size));
}
} else {
int oldStart = start;
size = max - start;
count += size;
offsetsList.append(Offsets(start, size));
size = step - size;
start = 0;
count += size;
if (size != 0) {
offsetsList.append(Offsets(0, size));
}
if (count <= maxCount / 2) {
start = size;
finished = true;
} else
start = oldStart;
}
}
count = 0;
if (offsetsList == firstPoint)
completed = true;
else
m_offsets.append(offsetsList);
if (first) {
firstPoint = offsetsList;
first = false;
}
}
}
void ImageLayer::updateTiles()
{
if ((boundingRect().width() == 0) || (boundingRect().height() == 0))
return;
// TODO create enums to define image aspect, auto tile, etc...
QPixmap pixmap(source()); // TODO
// If item height doesn't match pixmap height, scaleToHeight
if (pixmap.height() != (int)height()) {
pixmap = pixmap.scaledToHeight(height());
}
if (m_drawType == Bacon2D::PlaneDrawType) {
m_tileWidth = width();
m_tileHeight = height();
if (pixmap.width() % (int)width() != 0) {
// XXX create some log system?
qCritical() << QString("Bacon2D>>Image \'%1\' doesn't contains a proper size... CROPPING!").arg(source());
int newWidth = pixmap.width() - (pixmap.width() % (int)width());
pixmap = pixmap.copy(0, 0, newWidth, height());
}
}
if (pixmap.width() < boundingRect().width()) {
QPixmap temp(boundingRect().width(), boundingRect().height());
QPainter p(&temp);
p.drawTiledPixmap(boundingRect(), pixmap, QPoint(0,0));
p.end();
pixmap = temp;
}
if (m_type == Bacon2D::MirroredType) {
QPixmap temp(pixmap.width() * 2, pixmap.height());
QPainter p(&temp);
p.drawPixmap(0, 0, pixmap.width(), pixmap.height(), pixmap);
p.drawPixmap(pixmap.width(), 0, pixmap.width(), pixmap.height(),
pixmap.transformed(QTransform().scale(-1, 1), Qt::FastTransformation));
p.end();
pixmap = temp;
}
// visible tiles
m_numColumns = boundingRect().width() / m_tileWidth;
m_numRows = boundingRect().height() / m_tileHeight;
// total of columns and rows
m_totalColumns = pixmap.width() / m_tileWidth;
m_totalRows = pixmap.height() / m_tileHeight;
int i, j;
for (i = 0; i < m_totalRows; i++) {
for (j = 0; j < m_totalColumns; j++) {
QPixmap temp(m_tileWidth, m_tileHeight);
QPainter p(&temp);
p.setCompositionMode(QPainter::CompositionMode_Source);
p.drawPixmap(0, 0, m_tileWidth, m_tileHeight,
pixmap, j * m_tileWidth, i * m_tileHeight, m_tileWidth, m_tileHeight);
p.end();
addTile(temp);
}
}
generateOffsets();
drawPixmap();
}
QPixmap ImageLayer::generatePartialPixmap(int startPoint, int size)
{
QPixmap temp(m_tileWidth * size, boundingRect().height());
QPainter p(&temp);
int i, j;
int index = 0;
for (i = 0; i < m_numRows; i++) {
for (j = 0; j < size; j++) {
index = ((i * m_totalColumns) + (j + startPoint));
p.drawPixmap(j * m_tileWidth, i * m_tileHeight, getTile(index));
// just draw a grid
// XXX chech the possibility of drawn it only on a debug mode
if (m_drawGrid) {
p.setPen(m_gridColor);
p.drawRect(j * m_tileWidth, i * m_tileHeight, m_tileWidth, m_tileHeight);
}
}
}
p.end();
return temp;
}
void ImageLayer::drawPixmap()
{
if ((boundingRect().width() == 0) || (boundingRect().height() == 0))
return;
if (m_currentImage)
delete m_currentImage;
m_currentImage = new QImage(boundingRect().width() * m_areaToDraw,
boundingRect().height(), QImage::Format_ARGB32_Premultiplied);
QPainter p(m_currentImage);
int xPoint = 0;
for (int i = 0; i < m_offsets[m_columnOffset].size(); i++) {
Offsets offset = m_offsets[m_columnOffset].at(i);
QPixmap pixmap = generatePartialPixmap(offset.point(), offset.size());
p.drawPixmap(xPoint, 0, pixmap);
xPoint += pixmap.width();
m_latestPoint = offset.point();
}
if (m_horizontalStep > 0)
m_columnOffset = (m_columnOffset - 1 < 0) ? m_offsets.size() - 1 : m_columnOffset - 1;
else
m_columnOffset = (m_columnOffset + 1) % m_offsets.size();
p.end();
}
// move to a X value
void ImageLayer::moveX(const qreal &x)
{
qreal newValue = x;
qreal delta = m_globalXPos + newValue;
m_globalXPos = newValue * -1;
m_localXPos -= delta;
if (m_localXPos <= -width()) {
drawPixmap();
m_localXPos = width() + m_localXPos;
} else if (m_localXPos >= 0) {
if (m_globalXPos != 0) {
drawPixmap();
m_localXPos = -width() + m_localXPos;
} else
m_localXPos = 0;
}
}
void ImageLayer::moveY(const qreal &y)
{
Q_UNUSED(y);
// TBD
}
void ImageLayer::updateHorizontalStep()
{
m_currentHorizontalStep += m_horizontalStep;
if (m_currentHorizontalStep <= -width()) {
drawPixmap();
m_currentHorizontalStep = 0;
} else if (m_currentHorizontalStep >= 0) {
drawPixmap();
m_currentHorizontalStep = -width();
}
}
void ImageLayer::onHorizontalDirectionChanged()
{
if (m_offsets.count() != 0)
m_columnOffset = (m_columnOffset + 2) % m_offsets.size();
}
void ImageLayer::paint(QPainter *painter)
{
if (!m_currentImage)
return;
if (m_isAnimated)
updateHorizontalStep();
painter->drawImage(m_currentHorizontalStep, 0, *m_currentImage);
}
void ImageLayer::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
if (newGeometry.isEmpty() || !isComponentComplete())
return;
updateTiles();
m_initialized = true;
Layer::geometryChanged(newGeometry, oldGeometry);
}
void ImageLayer::componentComplete()
{
Layer::componentComplete();
if (m_initialized || boundingRect().isEmpty())
return;
updateTiles();
m_initialized = true;
}
<|endoftext|> |
<commit_before>#include <ncurses.h>
#include "../../../src/contents.hh"
#include "../../../src/key_aliases.hh"
#include "../../vick-move/src/move.hh"
void enter_insert_mode(contents& contents, boost::optional<int>) {
char ch;
while((ch = getch()) != _escape) {
contents.cont[contents.y].insert(contents.x, 1, ch);
mvf(contents);
if(get_contents().refresh) {
print_contents(get_contents());
}
}
}
void enter_replace_mode(contents& contents, boost::optional<int>) {
char ch;
while((ch = getch()) != _escape) {
if(contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
} else {
contents.cont[contents.y][contents.x] = ch;
}
if(get_contents().refresh) {
print_contents(get_contents());
}
}
}
<commit_msg>Edit ``contents.is_inserting`` in insert modes<commit_after>#include <ncurses.h>
#include "../../../src/contents.hh"
#include "../../../src/key_aliases.hh"
#include "../../vick-move/src/move.hh"
void enter_insert_mode(contents& contents, boost::optional<int>) {
char ch;
contents.is_inserting = true;
while((ch = getch()) != _escape) {
contents.cont[contents.y].insert(contents.x, 1, ch);
mvf(contents);
if(get_contents().refresh) {
print_contents(get_contents());
}
}
contents.is_inserting = false;
}
void enter_replace_mode(contents& contents, boost::optional<int>) {
char ch;
contents.is_inserting = true;
while((ch = getch()) != _escape) {
if(contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
} else {
contents.cont[contents.y][contents.x] = ch;
}
if(get_contents().refresh) {
print_contents(get_contents());
}
}
contents.is_inserting = false;
}
<|endoftext|> |
<commit_before>/*!
* Copyright (c) 2018 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#include <LightGBM/utils/file_io.h>
#include <LightGBM/utils/log.h>
#include <algorithm>
#include <sstream>
#include <unordered_map>
#ifdef USE_HDFS
#include <hdfs.h>
#endif
namespace LightGBM {
struct LocalFile : VirtualFileReader, VirtualFileWriter {
LocalFile(const std::string& filename, const std::string& mode) : filename_(filename), mode_(mode) {}
virtual ~LocalFile() {
if (file_ != NULL) {
fclose(file_);
}
}
bool Init() {
if (file_ == NULL) {
#if _MSC_VER
fopen_s(&file_, filename_.c_str(), mode_.c_str());
#else
file_ = fopen(filename_.c_str(), mode_.c_str());
#endif
}
return file_ != NULL;
}
bool Exists() const {
LocalFile file(filename_, "rb");
return file.Init();
}
size_t Read(void* buffer, size_t bytes) const {
return fread(buffer, 1, bytes, file_);
}
size_t Write(const void* buffer, size_t bytes) const {
return fwrite(buffer, bytes, 1, file_) == 1 ? bytes : 0;
}
private:
FILE* file_ = NULL;
const std::string filename_;
const std::string mode_;
};
const std::string kHdfsProto = "hdfs://";
#ifdef USE_HDFS
struct HDFSFile : VirtualFileReader, VirtualFileWriter {
HDFSFile(const std::string& filename, int flags) : filename_(filename), flags_(flags) {}
~HDFSFile() {
if (file_ != NULL) {
hdfsCloseFile(fs_, file_);
}
}
bool Init() {
if (file_ == NULL) {
if (fs_ == NULL) {
fs_ = GetHDFSFileSystem(filename_);
}
if (fs_ != NULL && (flags_ == O_WRONLY || 0 == hdfsExists(fs_, filename_.c_str()))) {
file_ = hdfsOpenFile(fs_, filename_.c_str(), flags_, 0, 0, 0);
}
}
return file_ != NULL;
}
bool Exists() const {
if (fs_ == NULL) {
fs_ = GetHDFSFileSystem(filename_);
}
return fs_ != NULL && 0 == hdfsExists(fs_, filename_.c_str());
}
size_t Read(void* data, size_t bytes) const {
return FileOperation<void*>(data, bytes, &hdfsRead);
}
size_t Write(const void* data, size_t bytes) const {
return FileOperation<const void*>(data, bytes, &hdfsWrite);
}
private:
template <typename BufferType>
using fileOp = tSize(*)(hdfsFS, hdfsFile, BufferType, tSize);
template <typename BufferType>
inline size_t FileOperation(BufferType data, size_t bytes, fileOp<BufferType> op) const {
char* buffer = reinterpret_cast<char *>(data);
size_t remain = bytes;
while (remain != 0) {
size_t nmax = static_cast<size_t>(std::numeric_limits<tSize>::max());
tSize ret = op(fs_, file_, buffer, std::min(nmax, remain));
if (ret > 0) {
size_t n = static_cast<size_t>(ret);
remain -= n;
buffer += n;
} else if (ret == 0) {
break;
} else if (errno != EINTR) {
Log::Fatal("Failed HDFS file operation [%s]", strerror(errno));
}
}
return bytes - remain;
}
static hdfsFS GetHDFSFileSystem(const std::string& uri) {
size_t end = uri.find("/", kHdfsProto.length());
if (uri.find(kHdfsProto) != 0 || end == std::string::npos) {
Log::Warning("Bad HDFS uri, no namenode found [%s]", uri.c_str());
return NULL;
}
std::string hostport = uri.substr(kHdfsProto.length(), end - kHdfsProto.length());
if (fs_cache_.count(hostport) == 0) {
fs_cache_[hostport] = MakeHDFSFileSystem(hostport);
}
return fs_cache_[hostport];
}
static hdfsFS MakeHDFSFileSystem(const std::string& hostport) {
std::istringstream iss(hostport);
std::string host;
tPort port = 0;
std::getline(iss, host, ':');
iss >> port;
hdfsFS fs = iss.eof() ? hdfsConnect(host.c_str(), port) : NULL;
if (fs == NULL) {
Log::Warning("Could not connect to HDFS namenode [%s]", hostport.c_str());
}
return fs;
}
mutable hdfsFS fs_ = NULL;
hdfsFile file_ = NULL;
const std::string filename_;
const int flags_;
static std::unordered_map<std::string, hdfsFS> fs_cache_;
};
std::unordered_map<std::string, hdfsFS> HDFSFile::fs_cache_ = std::unordered_map<std::string, hdfsFS>();
#define WITH_HDFS(x) x
#else
#define WITH_HDFS(x) Log::Fatal("HDFS support is not enabled")
#endif // USE_HDFS
std::unique_ptr<VirtualFileReader> VirtualFileReader::Make(const std::string& filename) {
if (0 == filename.find(kHdfsProto)) {
WITH_HDFS(return std::unique_ptr<VirtualFileReader>(new HDFSFile(filename, O_RDONLY)));
} else {
return std::unique_ptr<VirtualFileReader>(new LocalFile(filename, "rb"));
}
}
std::unique_ptr<VirtualFileWriter> VirtualFileWriter::Make(const std::string& filename) {
if (0 == filename.find(kHdfsProto)) {
WITH_HDFS(return std::unique_ptr<VirtualFileWriter>(new HDFSFile(filename, O_WRONLY)));
} else {
return std::unique_ptr<VirtualFileWriter>(new LocalFile(filename, "wb"));
}
}
bool VirtualFileWriter::Exists(const std::string& filename) {
if (0 == filename.find(kHdfsProto)) {
WITH_HDFS(HDFSFile file(filename, O_RDONLY); return file.Exists());
} else {
LocalFile file(filename, "rb");
return file.Exists();
}
}
} // namespace LightGBM
<commit_msg>fixed cast error (#2186)<commit_after>/*!
* Copyright (c) 2018 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#include <LightGBM/utils/file_io.h>
#include <LightGBM/utils/log.h>
#include <algorithm>
#include <sstream>
#include <unordered_map>
#ifdef USE_HDFS
#include <hdfs.h>
#endif
namespace LightGBM {
struct LocalFile : VirtualFileReader, VirtualFileWriter {
LocalFile(const std::string& filename, const std::string& mode) : filename_(filename), mode_(mode) {}
virtual ~LocalFile() {
if (file_ != NULL) {
fclose(file_);
}
}
bool Init() {
if (file_ == NULL) {
#if _MSC_VER
fopen_s(&file_, filename_.c_str(), mode_.c_str());
#else
file_ = fopen(filename_.c_str(), mode_.c_str());
#endif
}
return file_ != NULL;
}
bool Exists() const {
LocalFile file(filename_, "rb");
return file.Init();
}
size_t Read(void* buffer, size_t bytes) const {
return fread(buffer, 1, bytes, file_);
}
size_t Write(const void* buffer, size_t bytes) const {
return fwrite(buffer, bytes, 1, file_) == 1 ? bytes : 0;
}
private:
FILE* file_ = NULL;
const std::string filename_;
const std::string mode_;
};
const std::string kHdfsProto = "hdfs://";
#ifdef USE_HDFS
struct HDFSFile : VirtualFileReader, VirtualFileWriter {
HDFSFile(const std::string& filename, int flags) : filename_(filename), flags_(flags) {}
~HDFSFile() {
if (file_ != NULL) {
hdfsCloseFile(fs_, file_);
}
}
bool Init() {
if (file_ == NULL) {
if (fs_ == NULL) {
fs_ = GetHDFSFileSystem(filename_);
}
if (fs_ != NULL && (flags_ == O_WRONLY || 0 == hdfsExists(fs_, filename_.c_str()))) {
file_ = hdfsOpenFile(fs_, filename_.c_str(), flags_, 0, 0, 0);
}
}
return file_ != NULL;
}
bool Exists() const {
if (fs_ == NULL) {
fs_ = GetHDFSFileSystem(filename_);
}
return fs_ != NULL && 0 == hdfsExists(fs_, filename_.c_str());
}
size_t Read(void* data, size_t bytes) const {
return FileOperation<void*>(data, bytes, &hdfsRead);
}
size_t Write(const void* data, size_t bytes) const {
return FileOperation<const void*>(data, bytes, &hdfsWrite);
}
private:
template <typename BufferType>
using fileOp = tSize(*)(hdfsFS, hdfsFile, BufferType, tSize);
template <typename BufferType>
inline size_t FileOperation(BufferType data, size_t bytes, fileOp<BufferType> op) const {
char* buffer = const_cast<char*>(static_cast<const char*>(data));
size_t remain = bytes;
while (remain != 0) {
size_t nmax = static_cast<size_t>(std::numeric_limits<tSize>::max());
tSize ret = op(fs_, file_, buffer, std::min(nmax, remain));
if (ret > 0) {
size_t n = static_cast<size_t>(ret);
remain -= n;
buffer += n;
} else if (ret == 0) {
break;
} else if (errno != EINTR) {
Log::Fatal("Failed HDFS file operation [%s]", strerror(errno));
}
}
return bytes - remain;
}
static hdfsFS GetHDFSFileSystem(const std::string& uri) {
size_t end = uri.find("/", kHdfsProto.length());
if (uri.find(kHdfsProto) != 0 || end == std::string::npos) {
Log::Warning("Bad HDFS uri, no namenode found [%s]", uri.c_str());
return NULL;
}
std::string hostport = uri.substr(kHdfsProto.length(), end - kHdfsProto.length());
if (fs_cache_.count(hostport) == 0) {
fs_cache_[hostport] = MakeHDFSFileSystem(hostport);
}
return fs_cache_[hostport];
}
static hdfsFS MakeHDFSFileSystem(const std::string& hostport) {
std::istringstream iss(hostport);
std::string host;
tPort port = 0;
std::getline(iss, host, ':');
iss >> port;
hdfsFS fs = iss.eof() ? hdfsConnect(host.c_str(), port) : NULL;
if (fs == NULL) {
Log::Warning("Could not connect to HDFS namenode [%s]", hostport.c_str());
}
return fs;
}
mutable hdfsFS fs_ = NULL;
hdfsFile file_ = NULL;
const std::string filename_;
const int flags_;
static std::unordered_map<std::string, hdfsFS> fs_cache_;
};
std::unordered_map<std::string, hdfsFS> HDFSFile::fs_cache_ = std::unordered_map<std::string, hdfsFS>();
#define WITH_HDFS(x) x
#else
#define WITH_HDFS(x) Log::Fatal("HDFS support is not enabled")
#endif // USE_HDFS
std::unique_ptr<VirtualFileReader> VirtualFileReader::Make(const std::string& filename) {
if (0 == filename.find(kHdfsProto)) {
WITH_HDFS(return std::unique_ptr<VirtualFileReader>(new HDFSFile(filename, O_RDONLY)));
} else {
return std::unique_ptr<VirtualFileReader>(new LocalFile(filename, "rb"));
}
}
std::unique_ptr<VirtualFileWriter> VirtualFileWriter::Make(const std::string& filename) {
if (0 == filename.find(kHdfsProto)) {
WITH_HDFS(return std::unique_ptr<VirtualFileWriter>(new HDFSFile(filename, O_WRONLY)));
} else {
return std::unique_ptr<VirtualFileWriter>(new LocalFile(filename, "wb"));
}
}
bool VirtualFileWriter::Exists(const std::string& filename) {
if (0 == filename.find(kHdfsProto)) {
WITH_HDFS(HDFSFile file(filename, O_RDONLY); return file.Exists());
} else {
LocalFile file(filename, "rb");
return file.Exists();
}
}
} // namespace LightGBM
<|endoftext|> |
<commit_before>#include "ircchannel.hpp"
#include "hub.hpp"
#include "messages.hpp"
#include <stdexcept>
#include <utility>
#include <typeinfo>
#include <regex>
#include <memory>
namespace ircChannel {
IrcChannel::IrcChannel(Hub::Hub* hub, const std::string& config):
channeling::Channel(hub, config),
_server(_config["server"]),
_port(_config["port"]),
_channel(_config["channel"])
{
}
std::future<void> IrcChannel::activate() {
return std::async(std::launch::async, [this]() {
if (_active)
return;
_fd = connect();
startPolling();
registerConnection();
_active = true;
});}
IrcChannel::~IrcChannel() {
disconnect();
stopPolling();
}
void IrcChannel::incoming(const messaging::message_ptr&& msg) {
char message[irc_message_max];
if (msg->type() == messaging::MessageType::Text) {
const auto textmsg = messaging::TextMessage::fromMessage(msg);
snprintf(message, irc_message_max, "PRIVMSG #%s :[%s]: %s\r\n", _channel.c_str(), textmsg->user()->name().c_str(), textmsg->data().c_str());
std::cerr << "[DEBUG] #irc" << _name << " " << textmsg->data() << " inside " << _name << std::endl;
sendMessage(message);
}
}
const messaging::message_ptr IrcChannel::parse(const char* line) const
{
// :[email protected] PRIVMSG #chatsync :ololo
const std::string toParse(line);
std::cerr << "[DEBUG] Parsing irc line:" << toParse << std::endl;
std::regex msgRe("^:(\\S+)!~(\\S+)\\s+PRIVMSG\\s+#(\\S+)\\s+:(.*)\r\n$");
std::regex pingRe("^PING\\s+:(.*)\r\n$");
std::smatch msgMatches;
std::string name = "irc";
std::string text = "parse error";
if (std::regex_match(toParse, msgMatches, msgRe)) {
name = msgMatches[1].str();
text = msgMatches[4].str();
std::cerr << "[DEBUG] #irc:" << name << ": " << text << std::endl;
} else if (std::regex_match(toParse, msgMatches, pingRe)) {
const std::string pong = "PONG " + msgMatches[1].str();
std::cerr << "[DEBUG] #irc: sending" << pong << std::endl;
sendMessage(pong);
}
const auto msg = std::make_shared<const messaging::TextMessage>(_id,
std::move(std::make_shared<const messaging::User>(messaging::User(name.c_str()))),
text.c_str());
return msg;
}
int IrcChannel::registerConnection() {
const std::string nick = _config.get("nickname", "chatsyncbot");
const std::string mode = _config.get("mode", "*");
const std::string hostname = _config.get("hostname", "chatsynchost");
const std::string servername = _config.get("servername", "chatsyncserver");
const std::string realname = _config.get("realname", "Chat Sync");
const auto passline = "PASS *\r\n";
const auto nickline = "NICK " + nick + "\r\n";
const auto userline = "USER " + nick + " " + hostname + " " + servername + ":" + realname + "\r\n";
const auto joinline = "JOIN #" + _channel + " \r\n";
sendMessage(passline);
sendMessage(nickline);
sendMessage(userline);
std::this_thread::sleep_for(std::chrono::milliseconds (500));
sendMessage(joinline);
std::this_thread::sleep_for(std::chrono::milliseconds (500));
sendMessage("PRIVMSG #" + _channel + " :Hello there\r\n");
return 0;
}
/* OS interaction code begins here */
namespace net {
extern "C" {
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <stropts.h>
}
}
int IrcChannel::connect() {
int sockfd, n;
struct net::hostent *server;
char buffer[256];
std::cerr << "[DEBUG] Joining" << _channel << std::endl;
/* IPv4 resolution */
server = net::gethostbyname2(_server.c_str(), AF_INET);
if (server != NULL) {
struct net::sockaddr_in serv_addr;
sockfd = net::socket(AF_INET, net::SOCK_STREAM, 0);
if (sockfd < 0)
throw channeling::activate_error(ERR_SOCK_CREATE);
::bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
::bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
{
/* Ugly workaround to use different optimization levels for compiler */
#ifndef htons
using net::htons;
#endif
serv_addr.sin_port = htons(_port);
}
if (net::connect(sockfd,(struct net::sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
throw channeling::activate_error(ERR_CONNECTION);
} else {
/* IPv6 resolution */
struct net::sockaddr_in6 serv_addr;
struct servent *sp;
server = net::gethostbyname2(_server.c_str(), AF_INET6);
if (server == NULL)
throw channeling::activate_error(ERR_HOST_NOT_FOUND);
sockfd = net::socket(AF_INET6, net::SOCK_STREAM, 0);
if (sockfd < 0)
throw channeling::activate_error(ERR_SOCK_CREATE);
::bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin6_family = AF_INET;
::bcopy((char *)server->h_addr,
(char *)&serv_addr.sin6_addr.s6_addr,
server->h_length);
{
/* Ugly workaround to use different optimization levels for compiler */
#ifndef htons
using net::htons;
#endif
serv_addr.sin6_port = htons(_port);
}
if (net::connect(sockfd,(struct net::sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
throw channeling::activate_error(ERR_CONNECTION);
}
return sockfd;
}
int IrcChannel::sendMessage(const std::string &msg) const {
const int n = net::write(_fd,msg.c_str(),msg.length());
if (n < 0)
throw std::runtime_error(ERR_SOCK_WRITE);
return n;
}
int IrcChannel::disconnect() {
if (_fd > 0)
net::close(_fd);
return 0;
}
}
<commit_msg>[IRC] IPv6 initialization bugfix<commit_after>#include "ircchannel.hpp"
#include "hub.hpp"
#include "messages.hpp"
#include <stdexcept>
#include <utility>
#include <typeinfo>
#include <regex>
#include <memory>
namespace ircChannel {
IrcChannel::IrcChannel(Hub::Hub* hub, const std::string& config):
channeling::Channel(hub, config),
_server(_config["server"]),
_port(_config["port"]),
_channel(_config["channel"])
{
}
std::future<void> IrcChannel::activate() {
return std::async(std::launch::async, [this]() {
if (_active)
return;
_fd = connect();
startPolling();
registerConnection();
_active = true;
});}
IrcChannel::~IrcChannel() {
disconnect();
stopPolling();
}
void IrcChannel::incoming(const messaging::message_ptr&& msg) {
char message[irc_message_max];
if (msg->type() == messaging::MessageType::Text) {
const auto textmsg = messaging::TextMessage::fromMessage(msg);
snprintf(message, irc_message_max, "PRIVMSG #%s :[%s]: %s\r\n", _channel.c_str(), textmsg->user()->name().c_str(), textmsg->data().c_str());
std::cerr << "[DEBUG] #irc" << _name << " " << textmsg->data() << " inside " << _name << std::endl;
sendMessage(message);
}
}
const messaging::message_ptr IrcChannel::parse(const char* line) const
{
// :[email protected] PRIVMSG #chatsync :ololo
const std::string toParse(line);
std::cerr << "[DEBUG] Parsing irc line:" << toParse << std::endl;
std::regex msgRe("^:(\\S+)!~(\\S+)\\s+PRIVMSG\\s+#(\\S+)\\s+:(.*)\r\n$");
std::regex pingRe("^PING\\s+:(.*)\r\n$");
std::smatch msgMatches;
std::string name = "irc";
std::string text = "parse error";
if (std::regex_match(toParse, msgMatches, msgRe)) {
name = msgMatches[1].str();
text = msgMatches[4].str();
std::cerr << "[DEBUG] #irc:" << name << ": " << text << std::endl;
} else if (std::regex_match(toParse, msgMatches, pingRe)) {
const std::string pong = "PONG " + msgMatches[1].str();
std::cerr << "[DEBUG] #irc: sending" << pong << std::endl;
sendMessage(pong);
}
const auto msg = std::make_shared<const messaging::TextMessage>(_id,
std::move(std::make_shared<const messaging::User>(messaging::User(name.c_str()))),
text.c_str());
return msg;
}
int IrcChannel::registerConnection() {
const std::string nick = _config.get("nickname", "chatsyncbot");
const std::string mode = _config.get("mode", "*");
const std::string hostname = _config.get("hostname", "chatsynchost");
const std::string servername = _config.get("servername", "chatsyncserver");
const std::string realname = _config.get("realname", "Chat Sync");
const auto passline = "PASS *\r\n";
const auto nickline = "NICK " + nick + "\r\n";
const auto userline = "USER " + nick + " " + hostname + " " + servername + ":" + realname + "\r\n";
const auto joinline = "JOIN #" + _channel + " \r\n";
sendMessage(passline);
sendMessage(nickline);
sendMessage(userline);
std::this_thread::sleep_for(std::chrono::milliseconds (500));
sendMessage(joinline);
std::this_thread::sleep_for(std::chrono::milliseconds (500));
sendMessage("PRIVMSG #" + _channel + " :Hello there\r\n");
return 0;
}
/* OS interaction code begins here */
namespace net {
extern "C" {
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <stropts.h>
}
}
int IrcChannel::connect() {
int sockfd, n;
struct net::hostent *server;
char buffer[256];
/* IPv4 resolution */
server = net::gethostbyname2(_server.c_str(), AF_INET);
if (server != NULL) {
std::cerr << "[DEBUG] Connecting through IPv4" << std::endl;
struct net::sockaddr_in serv_addr;
sockfd = net::socket(AF_INET, net::SOCK_STREAM, 0);
if (sockfd < 0)
throw channeling::activate_error(ERR_SOCK_CREATE);
::bzero((char *) &serv_addr, sizeof(struct net::sockaddr_in));
serv_addr.sin_family = AF_INET;
::bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
{
/* Ugly workaround to use different optimization levels for compiler */
#ifndef htons
using net::htons;
#endif
serv_addr.sin_port = htons(_port);
}
if (net::connect(sockfd,(struct net::sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
throw channeling::activate_error(ERR_CONNECTION);
} else {
/* IPv6 resolution */
std::cerr << "[DEBUG] Connecting through IPv6" << std::endl;
struct net::sockaddr_in6 serv_addr;
struct servent *sp;
server = net::gethostbyname2(_server.c_str(), AF_INET6);
if (server == NULL)
throw channeling::activate_error(ERR_HOST_NOT_FOUND);
sockfd = net::socket(AF_INET6, net::SOCK_STREAM, 0);
if (sockfd < 0)
throw channeling::activate_error(ERR_SOCK_CREATE);
::bzero((char *) &serv_addr, sizeof(struct net::sockaddr_in6));
serv_addr.sin6_family = AF_INET6;
::bcopy((char *)server->h_addr,
(char *)&serv_addr.sin6_addr,
server->h_length);
{
/* Ugly workaround to use different optimization levels for compiler */
#ifndef htons
using net::htons;
#endif
serv_addr.sin6_port = htons(_port);
}
if (net::connect(sockfd,(struct net::sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
throw channeling::activate_error(ERR_CONNECTION);
}
return sockfd;
}
int IrcChannel::sendMessage(const std::string &msg) const {
const int n = net::write(_fd,msg.c_str(),msg.length());
if (n < 0)
throw std::runtime_error(ERR_SOCK_WRITE);
return n;
}
int IrcChannel::disconnect() {
if (_fd > 0)
net::close(_fd);
return 0;
}
}
<|endoftext|> |
<commit_before>#include "ircchannel.hpp"
#include "hub.hpp"
#include "messages.hpp"
#include <stdexcept>
#include <utility>
#include <typeinfo>
#include <regex>
#include <memory>
namespace ircChannel {
IrcChannel::IrcChannel(Hub::Hub* hub, const std::string& config):
channeling::Channel(hub, config),
_server(_config["server"]),
_port(_config["port"]),
_channel(_config["channel"])
{
}
std::future<void> IrcChannel::activate() {
return std::async(std::launch::async, [this]() {
if (_active)
return;
_fd = connect();
startPolling();
std::async(std::launch::async, [this]() {
std::this_thread::sleep_for(std::chrono::milliseconds (1000));
registerConnection();
});
_active = true;
});}
IrcChannel::~IrcChannel() {
disconnect();
stopPolling();
}
void IrcChannel::incoming(const messaging::message_ptr&& msg) {
char message[irc_message_max];
if (msg->type() == messaging::MessageType::Text) {
const auto textmsg = messaging::TextMessage::fromMessage(msg);
snprintf(message, irc_message_max, "PRIVMSG #%s :[%s]: %s\r\n", _channel.c_str(), textmsg->user()->name().c_str(), textmsg->data().c_str());
std::cerr << "[DEBUG] #irc" << _name << " " << textmsg->data() << " inside " << _name << std::endl;
sendMessage(message);
}
}
const messaging::message_ptr IrcChannel::parse(const char* line) const
{
// :[email protected] PRIVMSG #chatsync :ololo
const std::string toParse(line);
std::cerr << "[DEBUG] Parsing irc line:" << toParse << std::endl;
std::regex msgRe("^:(\\S+)!~(\\S+)\\s+PRIVMSG\\s+#(\\S+)\\s+:(.*)\r\n$");
std::regex pingRe("PING\\s+:(.*)\r\n$");
std::smatch msgMatches;
std::string name = "irc";
std::string text = toParse;
if (std::regex_search(toParse, msgMatches, msgRe)) {
name = msgMatches[1].str();
text = msgMatches[4].str();
std::cerr << "[DEBUG] #irc:" << name << ": " << text << std::endl;
};
if (std::regex_search(toParse, msgMatches, pingRe)) {
const std::string pong = "PONG " + msgMatches[1].str();
std::cerr << "[DEBUG] #irc: sending " << pong << std::endl;
sendMessage(pong);
};
const auto msg = std::make_shared<const messaging::TextMessage>(_id,
std::move(std::make_shared<const messaging::User>(messaging::User(name.c_str()))),
text.c_str());
return msg;
}
int IrcChannel::registerConnection() {
const std::string nick = _config.get("nickname", "chatsyncbot");
const std::string mode = _config.get("mode", "*");
const std::string hostname = _config.get("hostname", "chatsynchost");
const std::string servername = _config.get("servername", "chatsyncserver");
const std::string realname = _config.get("realname", "Chat Sync");
const std::string servicePassword = _config.get("servicepassword", "");
const auto passline = "PASS *\r\n";
const auto nickline = "NICK " + nick + "\r\n";
const auto userline = "USER " + nick + " " + hostname + " " + servername + " :" + realname + "\r\n";
const auto loginline = "PRIVMSG nickserv :id " + servicePassword + " \r\n";
const auto joinline = "JOIN #" + _channel + " \r\n";
sendMessage(passline);
sendMessage(nickline);
sendMessage(userline);
std::this_thread::sleep_for(std::chrono::milliseconds (1000));
if (servicePassword.length() > 0) {
std::async(std::launch::async, [this,loginline]() {
std::this_thread::sleep_for(std::chrono::milliseconds (1000));
sendMessage(loginline);
});
}
sendMessage(joinline);
std::this_thread::sleep_for(std::chrono::milliseconds (500));
sendMessage("PRIVMSG #" + _channel + " :Hello there\r\n");
return 0;
}
/* OS interaction code begins here */
namespace net {
extern "C" {
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <stropts.h>
}
}
int IrcChannel::connect() {
int sockfd, n;
struct net::hostent *server;
char buffer[256];
/* IPv4 resolution */
server = net::gethostbyname2(_server.c_str(), AF_INET);
if (server != NULL) {
std::cerr << "[DEBUG] Connecting through IPv4" << std::endl;
struct net::sockaddr_in serv_addr;
sockfd = net::socket(AF_INET, net::SOCK_STREAM, 0);
if (sockfd < 0)
throw channeling::activate_error(ERR_SOCK_CREATE);
::bzero((char *) &serv_addr, sizeof(struct net::sockaddr_in));
serv_addr.sin_family = AF_INET;
::bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
{
/* Ugly workaround to use different optimization levels for compiler */
#ifndef htons
using net::htons;
#endif
serv_addr.sin_port = htons(_port);
}
if (net::connect(sockfd,(struct net::sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
throw channeling::activate_error(ERR_CONNECTION);
} else {
/* IPv6 resolution */
std::cerr << "[DEBUG] Connecting through IPv6" << std::endl;
struct net::sockaddr_in6 serv_addr;
struct servent *sp;
server = net::gethostbyname2(_server.c_str(), AF_INET6);
if (server == NULL)
throw channeling::activate_error(ERR_HOST_NOT_FOUND);
sockfd = net::socket(AF_INET6, net::SOCK_STREAM, 0);
if (sockfd < 0)
throw channeling::activate_error(ERR_SOCK_CREATE);
::bzero((char *) &serv_addr, sizeof(struct net::sockaddr_in6));
serv_addr.sin6_family = AF_INET6;
::bcopy((char *)server->h_addr,
(char *)&serv_addr.sin6_addr,
server->h_length);
{
/* Ugly workaround to use different optimization levels for compiler */
#ifndef htons
using net::htons;
#endif
serv_addr.sin6_port = htons(_port);
}
if (net::connect(sockfd,(struct net::sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
throw channeling::activate_error(ERR_CONNECTION);
}
return sockfd;
}
int IrcChannel::sendMessage(const std::string &msg) const {
const int n = net::write(_fd,msg.c_str(),msg.length());
if (n < 0)
throw std::runtime_error(ERR_SOCK_WRITE);
return n;
}
int IrcChannel::disconnect() {
if (_fd > 0)
net::close(_fd);
return 0;
}
}
<commit_msg>[IRC] Log in twice as Nickserv sometimes doesn't understand the first attempt<commit_after>#include "ircchannel.hpp"
#include "hub.hpp"
#include "messages.hpp"
#include <stdexcept>
#include <utility>
#include <typeinfo>
#include <regex>
#include <memory>
namespace ircChannel {
IrcChannel::IrcChannel(Hub::Hub* hub, const std::string& config):
channeling::Channel(hub, config),
_server(_config["server"]),
_port(_config["port"]),
_channel(_config["channel"])
{
}
std::future<void> IrcChannel::activate() {
return std::async(std::launch::async, [this]() {
if (_active)
return;
_fd = connect();
startPolling();
std::async(std::launch::async, [this]() {
std::this_thread::sleep_for(std::chrono::milliseconds (2000));
registerConnection();
});
_active = true;
});}
IrcChannel::~IrcChannel() {
disconnect();
stopPolling();
}
void IrcChannel::incoming(const messaging::message_ptr&& msg) {
char message[irc_message_max];
if (msg->type() == messaging::MessageType::Text) {
const auto textmsg = messaging::TextMessage::fromMessage(msg);
snprintf(message, irc_message_max, "PRIVMSG #%s :[%s]: %s\r\n", _channel.c_str(), textmsg->user()->name().c_str(), textmsg->data().c_str());
std::cerr << "[DEBUG] #irc" << _name << " " << textmsg->data() << " inside " << _name << std::endl;
sendMessage(message);
}
}
const messaging::message_ptr IrcChannel::parse(const char* line) const
{
// :[email protected] PRIVMSG #chatsync :ololo
const std::string toParse(line);
std::cerr << "[DEBUG] Parsing irc line:" << toParse << std::endl;
std::regex msgRe("^:(\\S+)!~(\\S+)\\s+PRIVMSG\\s+#(\\S+)\\s+:(.*)\r\n$");
std::regex pingRe("PING\\s+:(.*)\r\n$");
std::smatch msgMatches;
std::string name = "irc";
std::string text = toParse;
if (std::regex_search(toParse, msgMatches, msgRe)) {
name = msgMatches[1].str();
text = msgMatches[4].str();
std::cerr << "[DEBUG] #irc:" << name << ": " << text << std::endl;
};
if (std::regex_search(toParse, msgMatches, pingRe)) {
const std::string pong = "PONG " + msgMatches[1].str();
std::cerr << "[DEBUG] #irc: sending " << pong << std::endl;
sendMessage(pong);
};
const auto msg = std::make_shared<const messaging::TextMessage>(_id,
std::move(std::make_shared<const messaging::User>(messaging::User(name.c_str()))),
text.c_str());
return msg;
}
int IrcChannel::registerConnection() {
const std::string nick = _config.get("nickname", "chatsyncbot");
const std::string mode = _config.get("mode", "*");
const std::string hostname = _config.get("hostname", "chatsynchost");
const std::string servername = _config.get("servername", "chatsyncserver");
const std::string realname = _config.get("realname", "Chat Sync");
const std::string servicePassword = _config.get("servicepassword", "");
const auto passline = "PASS *\r\n";
const auto nickline = "NICK " + nick + "\r\n";
const auto userline = "USER " + nick + " " + hostname + " " + servername + " :" + realname + "\r\n";
const auto loginline = "PRIVMSG nickserv :id " + servicePassword + "\r\n";
const auto joinline = "JOIN #" + _channel + " \r\n";
sendMessage(passline);
sendMessage(nickline);
sendMessage(userline);
std::this_thread::sleep_for(std::chrono::milliseconds (1000));
if (servicePassword.length() > 0) {
std::async(std::launch::async, [this,loginline]() {
sendMessage(loginline);
std::this_thread::sleep_for(std::chrono::milliseconds (1000));
sendMessage(loginline);
});
}
sendMessage(joinline);
std::this_thread::sleep_for(std::chrono::milliseconds (500));
sendMessage("PRIVMSG #" + _channel + " :Hello there\r\n");
return 0;
}
/* OS interaction code begins here */
namespace net {
extern "C" {
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <stropts.h>
}
}
int IrcChannel::connect() {
int sockfd, n;
struct net::hostent *server;
char buffer[256];
/* IPv4 resolution */
server = net::gethostbyname2(_server.c_str(), AF_INET);
if (server != NULL) {
std::cerr << "[DEBUG] Connecting through IPv4" << std::endl;
struct net::sockaddr_in serv_addr;
sockfd = net::socket(AF_INET, net::SOCK_STREAM, 0);
if (sockfd < 0)
throw channeling::activate_error(ERR_SOCK_CREATE);
::bzero((char *) &serv_addr, sizeof(struct net::sockaddr_in));
serv_addr.sin_family = AF_INET;
::bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
{
/* Ugly workaround to use different optimization levels for compiler */
#ifndef htons
using net::htons;
#endif
serv_addr.sin_port = htons(_port);
}
if (net::connect(sockfd,(struct net::sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
throw channeling::activate_error(ERR_CONNECTION);
} else {
/* IPv6 resolution */
std::cerr << "[DEBUG] Connecting through IPv6" << std::endl;
struct net::sockaddr_in6 serv_addr;
struct servent *sp;
server = net::gethostbyname2(_server.c_str(), AF_INET6);
if (server == NULL)
throw channeling::activate_error(ERR_HOST_NOT_FOUND);
sockfd = net::socket(AF_INET6, net::SOCK_STREAM, 0);
if (sockfd < 0)
throw channeling::activate_error(ERR_SOCK_CREATE);
::bzero((char *) &serv_addr, sizeof(struct net::sockaddr_in6));
serv_addr.sin6_family = AF_INET6;
::bcopy((char *)server->h_addr,
(char *)&serv_addr.sin6_addr,
server->h_length);
{
/* Ugly workaround to use different optimization levels for compiler */
#ifndef htons
using net::htons;
#endif
serv_addr.sin6_port = htons(_port);
}
if (net::connect(sockfd,(struct net::sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
throw channeling::activate_error(ERR_CONNECTION);
}
return sockfd;
}
int IrcChannel::sendMessage(const std::string &msg) const {
const int n = net::write(_fd,msg.c_str(),msg.length());
if (n < 0)
throw std::runtime_error(ERR_SOCK_WRITE);
return n;
}
int IrcChannel::disconnect() {
if (_fd > 0)
net::close(_fd);
return 0;
}
}
<|endoftext|> |
<commit_before>#include <liblinear/linear.h>
#include <opencv2/imgproc/imgproc.hpp>
#include "jda/data.hpp"
#include "jda/cart.hpp"
#include "jda/common.hpp"
#include "jda/cascador.hpp"
using namespace cv;
using namespace std;
namespace jda {
/*! \breif draw the distribution of scores */
void draw_density_graph(vector<double>& pos_scores, vector<double>& neg_scores, const int n = 100, const int rows = 20)
{
JDA_Assert(n < 115, "number of bins should be less than 150");
JDA_Assert(rows < 100, "graph rows should be less than 100");
double s_max = max(pos_scores[0], neg_scores[0]);
int pos_size = pos_scores.size();
int neg_size = neg_scores.size();
double s_min = min(pos_scores[pos_size - 1], neg_scores[neg_size - 1]);
//printf("s_max: %f\n", s_max);
//printf("s_min: %f\n", s_min);
vector<int> pos_bin(n, 0);
vector<int> neg_bin(n, 0);
double delta = (s_max - s_min) / n + 1e-9;
double th = s_max - delta;
// calc bin
int bin_idx = 0;
for (int i = 0; i < pos_size; i++)
{
if (pos_scores[i] >= th)
pos_bin[bin_idx]++;
else
{
i--;
bin_idx++;
th -= delta;
}
}
th = s_max - delta;
bin_idx = 0;
for (int i = 0; i < neg_size; i++)
{
if (neg_scores[i] >= th)
neg_bin[bin_idx]++;
else
{
i--;
bin_idx++;
th -= delta;
}
}
// enlargre local detail
#define detail 1
#if detail
double max_bin_rate = 0;
double min_bin_rate = 1;
for (int i = 0; i < n; i++)
{
if (pos_bin[i] > 0)
{
double bin_rate = pos_bin[i] / double(pos_size);
if (bin_rate > max_bin_rate)
max_bin_rate = bin_rate;
if (bin_rate < min_bin_rate)
min_bin_rate = bin_rate;
}
if (neg_bin[i] > 0)
{
double bin_rate = neg_bin[i] / double(neg_size);
if (bin_rate > max_bin_rate)
max_bin_rate = bin_rate;
if (bin_rate < min_bin_rate)
min_bin_rate = bin_rate;
}
}
max_bin_rate += 1e-5;
min_bin_rate -= 1e-5;
double range = max_bin_rate - min_bin_rate + 1e-18;
#else
double max_bin_rate = 1 + 1e-5;
double min_bin_rate = 0 - 1e-5;
double range = max_bin_rate - min_bin_rate + 1e-18;
#endif
// draw graph
int graph[100][120] = { 0 };
for (int i = 0; i < n; i++)
{
//printf("pos_bin[%d]: %d\n", i, pos_bin[i]);
if (pos_bin[i]>0)
{
int density = int((pos_bin[i] / double(pos_size) - min_bin_rate) / range * rows);
graph[density][i] += 1;
}
if (neg_bin[i] > 0)
{
int density = int((neg_bin[i] / double(neg_size) - min_bin_rate) / range * rows);
graph[density][i] += 2;
}
}
// render graph
for (int c = 0; c < n + 8; c++)
printf("=");
printf("\n");
char var[5] = { ' ', '+', 'x', '*' };
for (int r = rows - 1; r >= 0; r--)
{
printf("%06.2lf%% ", (double(r + 1) / rows * range + min_bin_rate) * 100);
for (int c = 0; c < n; c++)
printf("%c", var[graph[r][c]]);
printf("\n");
}
for (int c = 0; c < n + 8; c++)
printf("=");
printf("\n");
}
BoostCart::BoostCart(int stage) {
const Config& c = Config::GetInstance();
this->stage = stage;
K = c.K;
carts.reserve(K);
for (int i = 0; i < K; i++) {
// distribute the landmarks
carts.push_back(Cart(stage, i%c.landmark_n));
}
const int landmark_n = c.landmark_n;
const int m = K*(1 << (c.tree_depth - 1)); // K * leafNume
w = Mat_<double>::zeros(2 * landmark_n, m);
}
BoostCart::~BoostCart() {
}
void BoostCart::Train(DataSet& pos, DataSet& neg) {
const Config& c = Config::GetInstance();
JoinCascador& joincascador = *c.joincascador;
// statistic parameters
const int pos_original_size = pos.size;
const int neg_original_size = int(pos_original_size * c.nps[stage]);
int neg_rejected = 0;
const int landmark_n = c.landmark_n;
RNG rng(getTickCount());
// Real Boost
const int start_of_cart = joincascador.current_cart_idx + 1;
for (int k = start_of_cart; k < K; k++) {
Cart& cart = carts[k];
// more neg if needed
neg.MoreNegSamples(pos.size, c.nps[stage]);
// print out data set status
pos.QSort(); neg.QSort();
LOG("Pos max score = %.4lf, min score = %.4lf", pos.scores[0], pos.scores[pos.size - 1]);
LOG("Neg max score = %.4lf, min score = %.4lf", neg.scores[0], neg.scores[neg.size - 1]);
// draw scores desity graph
draw_density_graph(pos.scores, neg.scores);
// update weights
DataSet::UpdateWeights(pos, neg);
LOG("Current Positive DataSet Size is %d", pos.size);
LOG("Current Negative DataSet Size is %d", neg.size);
// train cart
TIMER_BEGIN
LOG("Train %d th Cart", k + 1);
cart.Train(pos, neg);
LOG("Done with %d th Cart, costs %.4lf s", k + 1, TIMER_NOW);
TIMER_END
joincascador.current_cart_idx = k;
// update score
pos.UpdateScores(cart);
neg.UpdateScores(cart);
// select th for pre-defined recall
cart.th = pos.CalcThresholdByRate(1 - c.recall[stage]);
int pos_n = pos.size;
int neg_n = neg.size;
pos.Remove(cart.th);
neg.Remove(cart.th);
double pos_drop_rate = double(pos_n - pos.size) / double(pos_n)* 100.;
double neg_drop_rate = double(neg_n - neg.size) / double(neg_n)* 100.;
LOG("Pos drop rate = %.2lf%%, Neg drop rate = %.2lf%%", pos_drop_rate, neg_drop_rate);
neg_rejected += neg_n - neg.size;
LOG("Current Negative DataSet Reject Size is %d", neg_rejected);
// print cart info
cart.PrintSelf();
const int kk = k + 1;
if ((kk != K) && (kk%c.snapshot_iter == 0)) { // snapshot
c.joincascador->Snapshot();
}
}
// Global Regression with LBF
// generate lbf
const int pos_n = pos.size;
const int neg_n = neg.size;
LOG("Generate LBF of DataSet");
vector<Mat_<int> > pos_lbf(pos_n);
vector<Mat_<int> > neg_lbf(neg_n);
#pragma omp parallel for
for (int i = 0; i < pos_n; i++) {
pos_lbf[i] = GenLBF(pos.imgs[i], pos.current_shapes[i]);
}
#pragma omp parallel for
for (int i = 0; i < neg_n; i++) {
neg_lbf[i] = GenLBF(neg.imgs[i], neg.current_shapes[i]);
}
// regression
vector<int> pos_idx(pos.size);
for (int i = 0; i < pos.size; i++) pos_idx[i] = i;
Mat_<double> shape_residual = pos.CalcShapeResidual(pos_idx);
LOG("Start Global Regression");
GlobalRegression(pos_lbf, shape_residual);
// update shapes
#pragma omp parallel for
for (int i = 0; i < pos_n; i++) {
pos.current_shapes[i] += GenDeltaShape(pos_lbf[i]);
}
#pragma omp parallel for
for (int i = 0; i < neg_n; i++) {
neg.current_shapes[i] += GenDeltaShape(neg_lbf[i]);
}
// summary
LOG("====================");
LOG("| Summary |");
LOG("====================");
// regression error
double e = calcMeanError(pos.gt_shapes, pos.current_shapes);
LOG("Regression Mean Error = %.4lf", e);
// accept and reject rate
double accept_rate = 0.;
double reject_rate = 0.;
accept_rate = double(pos_n) / double(pos_original_size) * 100.;
reject_rate = double(neg_rejected) / double(neg_rejected + neg_original_size) * 100.;
LOG("Accept Rate = %.2lf%%, Reject Rate = %.2lf%%", accept_rate, reject_rate);
// Done
}
/*!
* \breif Fully Free Model from liblinear
*/
static inline void freeModel(struct model* model) {
free(model->w);
free(model->label);
free(model);
}
void BoostCart::GlobalRegression(const vector<Mat_<int> >& lbf, const Mat_<double>& shape_residual) {
Config& c = Config::GetInstance();
const int landmark_n = c.landmark_n;
const int n = lbf.size();
const int m = K; // true size of local binary feature
const int f = m*carts[0].leafNum; // full size of local binary feature
vector<int> idx;
// prepare linear regression X, Y
struct feature_node** X = (struct feature_node**)malloc(n*sizeof(struct feature_node*));
double** Y = (double**)malloc(2 * landmark_n*sizeof(double*));
for (int i = 0; i < n; i++) {
X[i] = (struct feature_node*)malloc((m + 1)*sizeof(struct feature_node));
for (int j = 0; j < m; j++) {
X[i][j].index = lbf[i](0, j) + 1; // index starts from 1
X[i][j].value = 1.;
}
X[i][m].index = -1;
X[i][m].value = -1.;
}
for (int i = 0; i < landmark_n; i++) {
Y[2 * i] = (double*)malloc(n*sizeof(double));
Y[2 * i + 1] = (double*)malloc(n*sizeof(double));
for (int j = 0; j < n; j++) {
Y[2 * i][j] = shape_residual(j, 2 * i);
Y[2 * i + 1][j] = shape_residual(j, 2 * i + 1);
}
}
// train every landmark
struct problem prob;
struct parameter param;
prob.l = n;
prob.n = f;
prob.x = X;
prob.bias = -1;
param.solver_type = L2R_L2LOSS_SVR_DUAL;
param.C = 1. / n;
param.p = 0;
param.eps = 0.0001;
#pragma omp parallel for
for (int i = 0; i < landmark_n; i++) {
struct problem prob_ = prob;
prob_.y = Y[2 * i];
check_parameter(&prob_, ¶m);
struct model *model = train(&prob_, ¶m);
for (int j = 0; j < f; j++) w(2 * i, j) = get_decfun_coef(model, j + 1, 0);
freeModel(model);
prob_.y = Y[2 * i + 1];
check_parameter(&prob_, ¶m);
model = train(&prob_, ¶m);
for (int j = 0; j < f; j++) w(2 * i + 1, j) = get_decfun_coef(model, j + 1, 0);
freeModel(model);
}
// free
for (int i = 0; i < n; i++) free(X[i]);
for (int i = 0; i < 2 * landmark_n; i++) free(Y[i]);
free(X);
free(Y);
}
Mat_<int> BoostCart::GenLBF(const Mat& img, const Mat_<double>& shape) const {
const Config& c = Config::GetInstance();
Mat_<int> lbf(1, K);
int* ptr = lbf.ptr<int>(0);
const int base = carts[0].leafNum;
int offset = 0;
Mat img_h, img_q;
cv::resize(img, img_h, Size(c.img_h_size, c.img_h_size));
cv::resize(img, img_q, Size(c.img_q_size, c.img_q_size));
for (int k = 0; k < K; k++) {
ptr[k] = offset + carts[k].Forward(img, img_h, img_q, shape);
offset += base;
}
return lbf;
}
Mat_<double> BoostCart::GenDeltaShape(const Mat_<int>& lbf) const {
const int landmark_n = w.rows / 2;
const int m = lbf.cols;
Mat_<double> delta_shape(1, 2 * landmark_n);
const double* w_ptr;
const int* lbf_ptr = lbf.ptr<int>(0);
double* ds_ptr = delta_shape.ptr<double>(0);
for (int i = 0; i < landmark_n; i++) {
w_ptr = w.ptr<double>(2 * i);
double y = 0;
for (int j = 0; j < m; j++) y += w_ptr[lbf_ptr[j]];
ds_ptr[2 * i] = y;
w_ptr = w.ptr<double>(2 * i + 1);
y = 0;
for (int j = 0; j < m; j++) y += w_ptr[lbf_ptr[j]];
ds_ptr[2 * i + 1] = y;
}
return delta_shape;
}
} // namespace jda
<commit_msg>adjust code style<commit_after>#include <liblinear/linear.h>
#include <opencv2/imgproc/imgproc.hpp>
#include "jda/data.hpp"
#include "jda/cart.hpp"
#include "jda/common.hpp"
#include "jda/cascador.hpp"
using namespace cv;
using namespace std;
namespace jda {
/*!
* \breif draw the distribution of scores
* \note scores should be in order
*/
static void draw_density_graph(vector<double>& pos_scores, vector<double>& neg_scores, \
const int n = 100, const int rows = 20) {
JDA_Assert(n < 115, "number of bins should be less than 150");
JDA_Assert(rows < 100, "graph rows should be less than 100");
double s_max = max(pos_scores[0], neg_scores[0]);
int pos_size = pos_scores.size();
int neg_size = neg_scores.size();
double s_min = min(pos_scores[pos_size - 1], neg_scores[neg_size - 1]);
vector<int> pos_bin(n, 0);
vector<int> neg_bin(n, 0);
double delta = (s_max - s_min) / n + 1e-9;
double th = s_max - delta;
// calc bin
int bin_idx = 0;
for (int i = 0; i < pos_size; i++) {
if (pos_scores[i] >= th) {
pos_bin[bin_idx]++;
}
else {
i--;
bin_idx++;
th -= delta;
}
}
th = s_max - delta;
bin_idx = 0;
for (int i = 0; i < neg_size; i++) {
if (neg_scores[i] >= th) {
neg_bin[bin_idx]++;
}
else {
i--;
bin_idx++;
th -= delta;
}
}
// enlargre local detail
double max_bin_rate = 0;
double min_bin_rate = 1;
for (int i = 0; i < n; i++) {
if (pos_bin[i] > 0) {
double bin_rate = pos_bin[i] / double(pos_size);
if (bin_rate > max_bin_rate) max_bin_rate = bin_rate;
if (bin_rate < min_bin_rate) min_bin_rate = bin_rate;
}
if (neg_bin[i] > 0) {
double bin_rate = neg_bin[i] / double(neg_size);
if (bin_rate > max_bin_rate) max_bin_rate = bin_rate;
if (bin_rate < min_bin_rate) min_bin_rate = bin_rate;
}
}
max_bin_rate += 1e-5;
min_bin_rate -= 1e-5;
double range = max_bin_rate - min_bin_rate + 1e-18;
// draw graph
int graph[100][120] = { 0 };
for (int i = 0; i < n; i++) {
if (pos_bin[i]>0) {
int density = int((pos_bin[i] / double(pos_size) - min_bin_rate) / range * rows);
graph[density][i] += 1;
}
if (neg_bin[i] > 0) {
int density = int((neg_bin[i] / double(neg_size) - min_bin_rate) / range * rows);
graph[density][i] += 2;
}
}
// render graph
for (int c = 0; c < n + 8; c++) {
printf("=");
}
printf("\n");
char var[5] = { ' ', '+', 'x', '*' };
for (int r = rows - 1; r >= 0; r--) {
printf("%06.2lf%% ", (double(r + 1) / rows * range + min_bin_rate) * 100);
for (int c = 0; c < n; c++) {
printf("%c", var[graph[r][c]]);
}
printf("\n");
}
for (int c = 0; c < n + 8; c++) {
printf("=");
}
printf("\n");
}
BoostCart::BoostCart(int stage) {
const Config& c = Config::GetInstance();
this->stage = stage;
K = c.K;
carts.reserve(K);
for (int i = 0; i < K; i++) {
// distribute the landmarks
carts.push_back(Cart(stage, i%c.landmark_n));
}
const int landmark_n = c.landmark_n;
const int m = K*(1 << (c.tree_depth - 1)); // K * leafNume
w = Mat_<double>::zeros(2 * landmark_n, m);
}
BoostCart::~BoostCart() {
}
void BoostCart::Train(DataSet& pos, DataSet& neg) {
const Config& c = Config::GetInstance();
JoinCascador& joincascador = *c.joincascador;
// statistic parameters
const int pos_original_size = pos.size;
const int neg_original_size = int(pos_original_size * c.nps[stage]);
int neg_rejected = 0;
const int landmark_n = c.landmark_n;
RNG rng(getTickCount());
// Real Boost
const int start_of_cart = joincascador.current_cart_idx + 1;
for (int k = start_of_cart; k < K; k++) {
Cart& cart = carts[k];
// more neg if needed
neg.MoreNegSamples(pos.size, c.nps[stage]);
// print out data set status
pos.QSort(); neg.QSort();
LOG("Pos max score = %.4lf, min score = %.4lf", pos.scores[0], pos.scores[pos.size - 1]);
LOG("Neg max score = %.4lf, min score = %.4lf", neg.scores[0], neg.scores[neg.size - 1]);
// draw scores desity graph
draw_density_graph(pos.scores, neg.scores);
// update weights
DataSet::UpdateWeights(pos, neg);
LOG("Current Positive DataSet Size is %d", pos.size);
LOG("Current Negative DataSet Size is %d", neg.size);
// train cart
TIMER_BEGIN
LOG("Train %d th Cart", k + 1);
cart.Train(pos, neg);
LOG("Done with %d th Cart, costs %.4lf s", k + 1, TIMER_NOW);
TIMER_END
joincascador.current_cart_idx = k;
// update score
pos.UpdateScores(cart);
neg.UpdateScores(cart);
// select th for pre-defined recall
cart.th = pos.CalcThresholdByRate(1 - c.recall[stage]);
int pos_n = pos.size;
int neg_n = neg.size;
pos.Remove(cart.th);
neg.Remove(cart.th);
double pos_drop_rate = double(pos_n - pos.size) / double(pos_n)* 100.;
double neg_drop_rate = double(neg_n - neg.size) / double(neg_n)* 100.;
LOG("Pos drop rate = %.2lf%%, Neg drop rate = %.2lf%%", pos_drop_rate, neg_drop_rate);
neg_rejected += neg_n - neg.size;
LOG("Current Negative DataSet Reject Size is %d", neg_rejected);
// print cart info
cart.PrintSelf();
const int kk = k + 1;
if ((kk != K) && (kk%c.snapshot_iter == 0)) { // snapshot
c.joincascador->Snapshot();
}
}
// Global Regression with LBF
// generate lbf
const int pos_n = pos.size;
const int neg_n = neg.size;
LOG("Generate LBF of DataSet");
vector<Mat_<int> > pos_lbf(pos_n);
vector<Mat_<int> > neg_lbf(neg_n);
#pragma omp parallel for
for (int i = 0; i < pos_n; i++) {
pos_lbf[i] = GenLBF(pos.imgs[i], pos.current_shapes[i]);
}
#pragma omp parallel for
for (int i = 0; i < neg_n; i++) {
neg_lbf[i] = GenLBF(neg.imgs[i], neg.current_shapes[i]);
}
// regression
vector<int> pos_idx(pos.size);
for (int i = 0; i < pos.size; i++) pos_idx[i] = i;
Mat_<double> shape_residual = pos.CalcShapeResidual(pos_idx);
LOG("Start Global Regression");
GlobalRegression(pos_lbf, shape_residual);
// update shapes
#pragma omp parallel for
for (int i = 0; i < pos_n; i++) {
pos.current_shapes[i] += GenDeltaShape(pos_lbf[i]);
}
#pragma omp parallel for
for (int i = 0; i < neg_n; i++) {
neg.current_shapes[i] += GenDeltaShape(neg_lbf[i]);
}
// summary
LOG("====================");
LOG("| Summary |");
LOG("====================");
// regression error
double e = calcMeanError(pos.gt_shapes, pos.current_shapes);
LOG("Regression Mean Error = %.4lf", e);
// accept and reject rate
double accept_rate = 0.;
double reject_rate = 0.;
accept_rate = double(pos_n) / double(pos_original_size) * 100.;
reject_rate = double(neg_rejected) / double(neg_rejected + neg_original_size) * 100.;
LOG("Accept Rate = %.2lf%%, Reject Rate = %.2lf%%", accept_rate, reject_rate);
// Done
}
/*!
* \breif Fully Free Model from liblinear
*/
static inline void freeModel(struct model* model) {
free(model->w);
free(model->label);
free(model);
}
void BoostCart::GlobalRegression(const vector<Mat_<int> >& lbf, const Mat_<double>& shape_residual) {
Config& c = Config::GetInstance();
const int landmark_n = c.landmark_n;
const int n = lbf.size();
const int m = K; // true size of local binary feature
const int f = m*carts[0].leafNum; // full size of local binary feature
vector<int> idx;
// prepare linear regression X, Y
struct feature_node** X = (struct feature_node**)malloc(n*sizeof(struct feature_node*));
double** Y = (double**)malloc(2 * landmark_n*sizeof(double*));
for (int i = 0; i < n; i++) {
X[i] = (struct feature_node*)malloc((m + 1)*sizeof(struct feature_node));
for (int j = 0; j < m; j++) {
X[i][j].index = lbf[i](0, j) + 1; // index starts from 1
X[i][j].value = 1.;
}
X[i][m].index = -1;
X[i][m].value = -1.;
}
for (int i = 0; i < landmark_n; i++) {
Y[2 * i] = (double*)malloc(n*sizeof(double));
Y[2 * i + 1] = (double*)malloc(n*sizeof(double));
for (int j = 0; j < n; j++) {
Y[2 * i][j] = shape_residual(j, 2 * i);
Y[2 * i + 1][j] = shape_residual(j, 2 * i + 1);
}
}
// train every landmark
struct problem prob;
struct parameter param;
prob.l = n;
prob.n = f;
prob.x = X;
prob.bias = -1;
param.solver_type = L2R_L2LOSS_SVR_DUAL;
param.C = 1. / n;
param.p = 0;
param.eps = 0.0001;
#pragma omp parallel for
for (int i = 0; i < landmark_n; i++) {
struct problem prob_ = prob;
prob_.y = Y[2 * i];
check_parameter(&prob_, ¶m);
struct model *model = train(&prob_, ¶m);
for (int j = 0; j < f; j++) w(2 * i, j) = get_decfun_coef(model, j + 1, 0);
freeModel(model);
prob_.y = Y[2 * i + 1];
check_parameter(&prob_, ¶m);
model = train(&prob_, ¶m);
for (int j = 0; j < f; j++) w(2 * i + 1, j) = get_decfun_coef(model, j + 1, 0);
freeModel(model);
}
// free
for (int i = 0; i < n; i++) free(X[i]);
for (int i = 0; i < 2 * landmark_n; i++) free(Y[i]);
free(X);
free(Y);
}
Mat_<int> BoostCart::GenLBF(const Mat& img, const Mat_<double>& shape) const {
const Config& c = Config::GetInstance();
Mat_<int> lbf(1, K);
int* ptr = lbf.ptr<int>(0);
const int base = carts[0].leafNum;
int offset = 0;
Mat img_h, img_q;
cv::resize(img, img_h, Size(c.img_h_size, c.img_h_size));
cv::resize(img, img_q, Size(c.img_q_size, c.img_q_size));
for (int k = 0; k < K; k++) {
ptr[k] = offset + carts[k].Forward(img, img_h, img_q, shape);
offset += base;
}
return lbf;
}
Mat_<double> BoostCart::GenDeltaShape(const Mat_<int>& lbf) const {
const int landmark_n = w.rows / 2;
const int m = lbf.cols;
Mat_<double> delta_shape(1, 2 * landmark_n);
const double* w_ptr;
const int* lbf_ptr = lbf.ptr<int>(0);
double* ds_ptr = delta_shape.ptr<double>(0);
for (int i = 0; i < landmark_n; i++) {
w_ptr = w.ptr<double>(2 * i);
double y = 0;
for (int j = 0; j < m; j++) y += w_ptr[lbf_ptr[j]];
ds_ptr[2 * i] = y;
w_ptr = w.ptr<double>(2 * i + 1);
y = 0;
for (int j = 0; j < m; j++) y += w_ptr[lbf_ptr[j]];
ds_ptr[2 * i + 1] = y;
}
return delta_shape;
}
} // namespace jda
<|endoftext|> |
<commit_before>#include <csignal>
#include <QCoreApplication>
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQuickItem>
#include <QtQml>
#include <QSettings>
#include <QDir>
#include <QTextStream>
#include <QCommandLineParser>
#include "global.h"
#include "treemodel.h"
#include "settingsmodel.h"
#include "debug.h"
#include "processmonitor.h"
static const QString LOG_FILE = "afisync.log";
struct CleanExit
{
CleanExit()
{
signal(SIGINT, &CleanExit::exitQt);
signal(SIGTERM, &CleanExit::exitQt);
}
static void exitQt(int sig)
{
Q_UNUSED(sig);
QCoreApplication::exit(0);
}
};
static QObject* getTreeModel(QQmlEngine* engine, QJSEngine* scriptEngine)
{
DBG;
Q_UNUSED(scriptEngine)
Global::model = new TreeModel(engine);
return Global::model;
}
static QObject* getSettingsModel(QQmlEngine* engine, QJSEngine* scriptEngine)
{
Q_UNUSED(scriptEngine)
return new SettingsModel(engine);
}
static QObject* getProcessMonitor(QQmlEngine* engine, QJSEngine* scriptEngine)
{
Q_UNUSED(scriptEngine)
return new ProcessMonitor(engine);
}
void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
Q_UNUSED(type)
Q_UNUSED(context)
*Global::logStream << msg << "\n";
}
int gui(int argc, char* argv[])
{
qmlRegisterSingletonType<TreeModel>("org.AFISync", 0, 1, "TreeModel", getTreeModel);
qmlRegisterSingletonType<SettingsModel>("org.AFISync", 0, 1, "SettingsModel", getSettingsModel);
qmlRegisterSingletonType<ProcessMonitor>("org.AFISync", 0, 1, "ProcessMonitor", getProcessMonitor);
DBG << "QML Singletons registered";
QApplication app(argc, argv);
DBG << "QGuiApplication created";
QQmlApplicationEngine engine;
//DBG << 3.2;
engine.load(QUrl(QStringLiteral("qrc:/SplashScreen.qml")));
DBG << "QML Engine loaded";
int rVal = app.exec();
DBG << "END";
return rVal;
}
int cli(int argc, char* argv[], QCommandLineParser& parser)
{
//Linux ctrl+c compatability
CleanExit cleanExit;
Q_UNUSED(cleanExit);
QCoreApplication app(argc, argv);
QStringList args;
for (int i = 0; i < argc; ++i)
{
DBG << argv[i];
args.append(argv[i]);
}
parser.process(args);
DBG << parser.errorText();
QString username, password, directory;
unsigned port;
directory = parser.value("mirror");
port = parser.value("port").toInt();
QFileInfo dir(directory);
QString modDownloadPath = dir.absoluteFilePath();
if (!dir.isDir() || !dir.isWritable())
{
qDebug() << "Invalid path:" << modDownloadPath;
QCoreApplication::exit(2);
}
DBG << "Setting mod download path:" << modDownloadPath;
SettingsModel::setModDownloadPath(modDownloadPath);
SettingsModel::setPort(QString::number(port));
Global::guiless = true;
TreeModel* model = new TreeModel(port, &app);
DBG << "model created";
model->enableRepositories();
return app.exec();
}
void createLogFile()
{
QFile* file = new QFile(LOG_FILE);
file->open(QIODevice::WriteOnly | QIODevice::Append);
Global::logStream = new QTextStream(file);
}
int main(int argc, char* argv[])
{
QCoreApplication::setOrganizationName("AFISync");
QCoreApplication::setOrganizationDomain("armafinland.fi");
QCoreApplication::setApplicationName("AFISync");
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, Constants::SETTINGS_PATH);
QSettings::setDefaultFormat(QSettings::IniFormat);
QCommandLineParser parser;
parser.addHelpOption();
parser.addVersionOption();
parser.addOptions({
{"mirror", "Mirror all files into <directory>. Current value: " + SettingsModel::modDownloadPath()
, "directory", SettingsModel::modDownloadPath()},
{"port", "External Port. Current value: " + SettingsModel::port()
, "port", SettingsModel::port()},
});
#ifndef QT_DEBUG
createLogFile();
qInstallMessageHandler(messageHandler);
#endif
DBG << "\nAFISync" << Constants::VERSION_STRING << "started";
if (argc > 1)
{
return cli(argc, argv, parser);
}
return gui(argc, argv);
}
<commit_msg>Delta patching cmd interface.<commit_after>#include <csignal>
#include <QCoreApplication>
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQuickItem>
#include <QtQml>
#include <QSettings>
#include <QDir>
#include <QTextStream>
#include <QCommandLineParser>
#include "apis/libtorrent/deltapatcher.h"
#include "global.h"
#include "treemodel.h"
#include "settingsmodel.h"
#include "debug.h"
#include "processmonitor.h"
static const QString LOG_FILE = "afisync.log";
static const QStringList DELTA_ARGS = {"old-path", "new-path", "output-path"};
struct CleanExit
{
CleanExit()
{
signal(SIGINT, &CleanExit::exitQt);
signal(SIGTERM, &CleanExit::exitQt);
}
static void exitQt(int sig)
{
Q_UNUSED(sig);
QCoreApplication::exit(0);
}
};
static QObject* getTreeModel(QQmlEngine* engine, QJSEngine* scriptEngine)
{
DBG;
Q_UNUSED(scriptEngine)
Global::model = new TreeModel(engine);
return Global::model;
}
static QObject* getSettingsModel(QQmlEngine* engine, QJSEngine* scriptEngine)
{
Q_UNUSED(scriptEngine)
return new SettingsModel(engine);
}
static QObject* getProcessMonitor(QQmlEngine* engine, QJSEngine* scriptEngine)
{
Q_UNUSED(scriptEngine)
return new ProcessMonitor(engine);
}
void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
Q_UNUSED(type)
Q_UNUSED(context)
*Global::logStream << msg << "\n";
}
int gui(int argc, char* argv[])
{
qmlRegisterSingletonType<TreeModel>("org.AFISync", 0, 1, "TreeModel", getTreeModel);
qmlRegisterSingletonType<SettingsModel>("org.AFISync", 0, 1, "SettingsModel", getSettingsModel);
qmlRegisterSingletonType<ProcessMonitor>("org.AFISync", 0, 1, "ProcessMonitor", getProcessMonitor);
DBG << "QML Singletons registered";
QApplication app(argc, argv);
DBG << "QGuiApplication created";
QQmlApplicationEngine engine;
//DBG << 3.2;
engine.load(QUrl(QStringLiteral("qrc:/SplashScreen.qml")));
DBG << "QML Engine loaded";
int rVal = app.exec();
DBG << "END";
return rVal;
}
int cli(int argc, char* argv[], QCommandLineParser& parser)
{
//Linux ctrl+c compatability
CleanExit cleanExit;
Q_UNUSED(cleanExit);
QCoreApplication app(argc, argv);
QStringList args;
for (int i = 0; i < argc; ++i)
{
DBG << argv[i];
args.append(argv[i]);
}
parser.process(args);
DBG << parser.errorText();
//Delta patching
QSet<QString> missingArgs = DELTA_ARGS.toSet() - parser.optionNames().toSet();
if (missingArgs.size() < DELTA_ARGS.size())
{
if (missingArgs.size() != 0)
{
qDebug() << "ERROR: Missing arguments:" << missingArgs;
return 2;
}
QString oldPath = parser.value(DELTA_ARGS.at(0));
QString newPath = parser.value(DELTA_ARGS.at(1));
QString patchesPath = parser.value(DELTA_ARGS.at(2));
DeltaPatcher dp(patchesPath);
dp.delta(oldPath, newPath);
return 0;
}
DBG << "FAIL" << missingArgs.size() << missingArgs;
QString username, password, directory;
unsigned port;
directory = parser.value("mirror");
port = parser.value("port").toInt();
QFileInfo dir(directory);
QString modDownloadPath = dir.absoluteFilePath();
if (!dir.isDir() || !dir.isWritable())
{
qDebug() << "Invalid path:" << modDownloadPath;
QCoreApplication::exit(2);
}
DBG << "Setting mod download path:" << modDownloadPath;
SettingsModel::setModDownloadPath(modDownloadPath);
SettingsModel::setPort(QString::number(port));
Global::guiless = true;
TreeModel* model = new TreeModel(port, &app);
DBG << "model created";
model->enableRepositories();
return app.exec();
}
void createLogFile()
{
QFile* file = new QFile(LOG_FILE);
file->open(QIODevice::WriteOnly | QIODevice::Append);
Global::logStream = new QTextStream(file);
}
int main(int argc, char* argv[])
{
QCoreApplication::setOrganizationName("AFISync");
QCoreApplication::setOrganizationDomain("armafinland.fi");
QCoreApplication::setApplicationName("AFISync");
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, Constants::SETTINGS_PATH);
QSettings::setDefaultFormat(QSettings::IniFormat);
QCommandLineParser parser;
parser.addHelpOption();
parser.addVersionOption();
parser.addOptions({
{"mirror", "Mirror all files into <directory>. Current value: " + SettingsModel::modDownloadPath()
, "directory", SettingsModel::modDownloadPath()},
{"port", "External Port. Current value: " + SettingsModel::port()
, "port", SettingsModel::port()},
{DELTA_ARGS.at(0), "Delta patch generation: Defines path to old version", DELTA_ARGS.at(0)},
{DELTA_ARGS.at(1), "Delta patch generation: Defines path to new version", DELTA_ARGS.at(1)},
{DELTA_ARGS.at(2), "Delta patch generation: Defines path to patches directory", DELTA_ARGS.at(2)},
});
#ifndef QT_DEBUG
createLogFile();
qInstallMessageHandler(messageHandler);
#endif
DBG << "\nAFISync" << Constants::VERSION_STRING << "started";
if (argc > 1)
{
return cli(argc, argv, parser);
}
return gui(argc, argv);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2017, Ubiquity Robotics
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the FreeBSD Project.
*
*/
#include <ros/ros.h>
#include <tf/transform_datatypes.h>
#include <tf2/LinearMath/Transform.h>
#include <tf2_ros/buffer.h>
#include <tf2_ros/transform_listener.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Path.h>
#include <list>
#include <string>
class MoveBasic {
private:
ros::Subscriber goalSub;
ros::Publisher cmdPub;
ros::Publisher pathPub;
double angularVelocity;
double angularTolerance;
double linearVelocity;
double linearTolerance;
tf2_ros::Buffer tfBuffer;
tf2_ros::TransformListener listener;
tf2::Transform goalOdom;
bool haveGoal;
void goalCallback(const geometry_msgs::PoseStamped::ConstPtr &msg);
void sendCmd(double angular, double linear);
bool getTransform(const std::string& from, const std::string& to,
tf2::Transform& tf);
bool handleRotation();
bool handleLinear();
public:
MoveBasic(ros::NodeHandle &nh);
void run();
bool moveLinear(double requestedDistance);
bool rotateTo(double requestedYaw);
bool rotateRel(double yaw);
};
// Radians to degrees
static double rad2deg(double rad)
{
return rad * 180.0 / M_PI;
}
// Adjust angle to be between -PI and PI
static void normalizeAngle(double& angle)
{
if (angle < -M_PI) {
angle += 2 * M_PI;
}
if (angle > M_PI) {
angle -= 2 * M_PI;
}
}
// retreive the 3 DOF we are interested in from a Transform
static void getPose(const tf2::Transform& tf, double& x, double& y, double& yaw)
{
tf2::Vector3 trans = tf.getOrigin();
x = trans.x();
y = trans.y();
double roll, pitch;
tf.getBasis().getRPY(roll, pitch, yaw);
}
// Constructor
MoveBasic::MoveBasic(ros::NodeHandle &nh): tfBuffer(ros::Duration(30.0)),
listener(tfBuffer), haveGoal(false)
{
nh.param<double>("angular_velocity", angularVelocity, 0.3);
nh.param<double>("angular_tolerance", angularTolerance, 0.01);
nh.param<double>("linear_velocity", linearVelocity, 0.4);
nh.param<double>("linear_tolerance", linearTolerance, 0.01);
cmdPub = ros::Publisher(nh.advertise<geometry_msgs::Twist>("/cmd_vel", 1));
pathPub = ros::Publisher(nh.advertise<nav_msgs::Path>("/plan", 1));
goalSub = nh.subscribe("/move_base_simple/goal", 1,
&MoveBasic::goalCallback, this);
ROS_INFO("Move Basic ready");
}
// Lookup the specified transform, returns true on success
bool MoveBasic::getTransform(const std::string& from, const std::string& to,
tf2::Transform& tf)
{
try {
geometry_msgs::TransformStamped tfs =
tfBuffer.lookupTransform(to, from, ros::Time(0));
tf2::fromMsg(tfs.transform, tf);
return true;
}
catch (tf2::TransformException &ex) {
ROS_WARN("%s", ex.what());
return false;
}
}
// Called when a simple goal message is received
void MoveBasic::goalCallback(const geometry_msgs::PoseStamped::ConstPtr &msg)
{
tf2::Transform goal;
tf2::fromMsg(msg->pose, goal);
std::string frameId = msg->header.frame_id;
double x, y, yaw;
getPose(goal, x, y, yaw);
ROS_INFO("Received goal %f %f %f", x, y, rad2deg(yaw));
tf2::Transform tfMapOdom;
if (!getTransform(frameId, "odom", tfMapOdom)) {
ROS_WARN("Cannot determine robot pose");
return;
}
goalOdom = tfMapOdom * goal;
getPose(goalOdom, x, y, yaw);
ROS_INFO("Goal in odom %f %f %f", x, y, rad2deg(yaw));
haveGoal = true;
nav_msgs::Path path;
geometry_msgs::PoseStamped p0, p1;
path.header.frame_id = "odom";
p0.pose.position.x = x;
p0.pose.position.y = y;
path.poses.push_back(p0);
tf2::Transform poseOdom;
if (!getTransform("base_link", "odom", poseOdom)) {
ROS_WARN("Cannot determine robot pose for rotation");
return;
}
getPose(poseOdom, x, y, yaw);
p1.pose.position.x = x;
p1.pose.position.y = y;
path.poses.push_back(p1);
pathPub.publish(path);
}
// Send a motion command
void MoveBasic::sendCmd(double angular, double linear)
{
geometry_msgs::Twist msg;
msg.angular.z = angular;
msg.linear.x = linear;
cmdPub.publish(msg);
}
// Main loop
void MoveBasic::run()
{
ros::Rate r(20);
while (ros::ok()) {
ros::spinOnce();
r.sleep();
if (haveGoal) {
haveGoal = false;
if (!handleRotation()) {
continue;
}
if (!handleLinear()) {
continue;
}
double x, y, yaw;
getPose(goalOdom, x, y, yaw);
rotateTo(yaw);
}
}
}
// Do angular part of goal
bool MoveBasic::handleRotation()
{
tf2::Transform poseOdom;
if (!getTransform("base_link", "odom", poseOdom)) {
ROS_WARN("Cannot determine robot pose for rotation");
return false;
}
tf2::Vector3 linear = goalOdom.getOrigin() - poseOdom.getOrigin();
double requestedYaw = atan2(linear.y(), linear.x());
return rotateTo(requestedYaw);
}
// Rotate relative to current orientation
bool MoveBasic::rotateRel(double yaw)
{
tf2::Transform poseOdom;
if (!getTransform("base_link", "odom", poseOdom)) {
ROS_WARN("Cannot determine robot pose for rotation");
return false;
}
double x, y, currentYaw;
getPose(poseOdom, x, y, currentYaw);
double requestedYaw = currentYaw + yaw;
normalizeAngle(requestedYaw);
return rotateTo(requestedYaw);
}
// Rotate to specified orientation (in radians)
bool MoveBasic::rotateTo(double requestedYaw)
{
bool done = false;
ros::Rate r(50);
while (!done && ros::ok()) {
ros::spinOnce();
r.sleep();
double x, y, currentYaw;
tf2::Transform poseOdom;
if (!getTransform("base_link", "odom", poseOdom)) {
ROS_WARN("Cannot determine robot pose for rotation");
return false;
}
getPose(poseOdom, x, y, currentYaw);
double demand = requestedYaw - currentYaw;
normalizeAngle(demand);
double velocity = 0;
if (demand < 0) {
velocity = -angularVelocity;
}
else {
velocity = angularVelocity;
}
if (haveGoal) { // new goal received
ROS_INFO("Stopping rotation due to new goal");
done = true;
velocity = 0;
}
// ROS_INFO("Demand %f %f %f", rad2deg(demand), demand, velocity);
if (std::abs(demand) < angularTolerance) {
velocity = 0;
done = true;
ROS_INFO("Done rotation, error %f radians %f degrees", demand, rad2deg(demand));
}
sendCmd(velocity, 0);
}
return done;
}
// Do linear part of goal
bool MoveBasic::handleLinear()
{
bool done = false;
tf2::Transform poseOdomInitial;
if (!getTransform("base_link", "odom", poseOdomInitial)) {
ROS_WARN("Cannot determine robot pose for linrar");
return false;
}
tf2::Vector3 linear = goalOdom.getOrigin() - poseOdomInitial.getOrigin();
double requestedDistance = linear.length();;
ROS_INFO("Requested distance %f", requestedDistance);
return moveLinear(requestedDistance);
}
// Move foreward specified distance
bool MoveBasic::moveLinear(double requestedDistance)
{
bool done = false;
ros::Rate r(50);
tf2::Transform poseOdomInitial;
if (!getTransform("base_link", "odom", poseOdomInitial)) {
ROS_WARN("Cannot determine robot pose for linrar");
return false;
}
while (!done && ros::ok()) {
ros::spinOnce();
r.sleep();
tf2::Transform poseOdom;
if (!getTransform("base_link", "odom", poseOdom)) {
ROS_WARN("Cannot determine robot pose for linear");
continue;
}
tf2::Vector3 travelled = poseOdomInitial.getOrigin() - poseOdom.getOrigin();
double distTravelled = travelled.length();;
double demand = requestedDistance - distTravelled;
double velocity = linearVelocity;
if (haveGoal) { // new goal received
ROS_INFO("Stopping rotation due to new goal");
done = true;
velocity = 0;
}
// ROS_INFO("Demand %f %f", requestedDist-distTravelled, velocity);
if (distTravelled > requestedDistance - linearTolerance) {
velocity = 0;
done = true;
ROS_INFO("Done linear, error %f meters", demand);
}
sendCmd(0, velocity);
}
return done;
}
int main(int argc, char ** argv) {
ros::init(argc, argv, "move_basic");
ros::NodeHandle nh("~");
MoveBasic node(nh);
node.run();
return 0;
}
<commit_msg>Add ramping, fixes #4<commit_after>/*
* Copyright (c) 2017, Ubiquity Robotics
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the FreeBSD Project.
*
*/
#include <ros/ros.h>
#include <tf/transform_datatypes.h>
#include <tf2/LinearMath/Transform.h>
#include <tf2_ros/buffer.h>
#include <tf2_ros/transform_listener.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Path.h>
#include <list>
#include <string>
class MoveBasic {
private:
ros::Subscriber goalSub;
ros::Publisher cmdPub;
ros::Publisher pathPub;
double maxAngularVelocity;
double minAngularVelocity;
double angularAcceleration;
double angularTolerance;
double minLinearVelocity;
double maxLinearVelocity;
double linearAcceleration;
double linearTolerance;
tf2_ros::Buffer tfBuffer;
tf2_ros::TransformListener listener;
tf2::Transform goalOdom;
bool haveGoal;
void goalCallback(const geometry_msgs::PoseStamped::ConstPtr &msg);
void sendCmd(double angular, double linear);
bool getTransform(const std::string& from, const std::string& to,
tf2::Transform& tf);
bool handleRotation();
bool handleLinear();
public:
MoveBasic(ros::NodeHandle &nh);
void run();
bool moveLinear(double requestedDistance);
bool rotateAbs(double requestedYaw);
bool rotateRel(double yaw);
};
// Radians to degrees
static double rad2deg(double rad)
{
return rad * 180.0 / M_PI;
}
// Adjust angle to be between -PI and PI
static void normalizeAngle(double& angle)
{
if (angle < -M_PI) {
angle += 2 * M_PI;
}
if (angle > M_PI) {
angle -= 2 * M_PI;
}
}
// retreive the 3 DOF we are interested in from a Transform
static void getPose(const tf2::Transform& tf, double& x, double& y, double& yaw)
{
tf2::Vector3 trans = tf.getOrigin();
x = trans.x();
y = trans.y();
double roll, pitch;
tf.getBasis().getRPY(roll, pitch, yaw);
}
// Constructor
MoveBasic::MoveBasic(ros::NodeHandle &nh): tfBuffer(ros::Duration(30.0)),
listener(tfBuffer), haveGoal(false)
{
nh.param<double>("min_angular_velocity", minAngularVelocity, 0.1);
nh.param<double>("max_angular_velocity", maxAngularVelocity, 1.0);
nh.param<double>("angular_acceleration", angularAcceleration, 0.3);
nh.param<double>("angular_tolerance", angularTolerance, 0.01);
nh.param<double>("min_linear_velocity", minLinearVelocity, 0.1);
nh.param<double>("max_linear_velocity", maxLinearVelocity, 0.5);
nh.param<double>("linear_acceleration", linearAcceleration, 0.5);
nh.param<double>("linear_tolerance", linearTolerance, 0.01);
cmdPub = ros::Publisher(nh.advertise<geometry_msgs::Twist>("/cmd_vel", 1));
pathPub = ros::Publisher(nh.advertise<nav_msgs::Path>("/plan", 1));
goalSub = nh.subscribe("/move_base_simple/goal", 1,
&MoveBasic::goalCallback, this);
ROS_INFO("Move Basic ready");
}
// Lookup the specified transform, returns true on success
bool MoveBasic::getTransform(const std::string& from, const std::string& to,
tf2::Transform& tf)
{
try {
geometry_msgs::TransformStamped tfs =
tfBuffer.lookupTransform(to, from, ros::Time(0));
tf2::fromMsg(tfs.transform, tf);
return true;
}
catch (tf2::TransformException &ex) {
ROS_WARN("%s", ex.what());
return false;
}
}
// Called when a simple goal message is received
void MoveBasic::goalCallback(const geometry_msgs::PoseStamped::ConstPtr &msg)
{
tf2::Transform goal;
tf2::fromMsg(msg->pose, goal);
std::string frameId = msg->header.frame_id;
double x, y, yaw;
getPose(goal, x, y, yaw);
ROS_INFO("Received goal %f %f %f", x, y, rad2deg(yaw));
tf2::Transform tfMapOdom;
if (!getTransform(frameId, "odom", tfMapOdom)) {
ROS_WARN("Cannot determine robot pose");
return;
}
goalOdom = tfMapOdom * goal;
getPose(goalOdom, x, y, yaw);
ROS_INFO("Goal in odom %f %f %f", x, y, rad2deg(yaw));
haveGoal = true;
nav_msgs::Path path;
geometry_msgs::PoseStamped p0, p1;
path.header.frame_id = "odom";
p0.pose.position.x = x;
p0.pose.position.y = y;
path.poses.push_back(p0);
tf2::Transform poseOdom;
if (!getTransform("base_link", "odom", poseOdom)) {
ROS_WARN("Cannot determine robot pose for rotation");
return;
}
getPose(poseOdom, x, y, yaw);
p1.pose.position.x = x;
p1.pose.position.y = y;
path.poses.push_back(p1);
pathPub.publish(path);
}
// Send a motion command
void MoveBasic::sendCmd(double angular, double linear)
{
geometry_msgs::Twist msg;
msg.angular.z = angular;
msg.linear.x = linear;
cmdPub.publish(msg);
}
// Main loop
void MoveBasic::run()
{
ros::Rate r(20);
while (ros::ok()) {
ros::spinOnce();
r.sleep();
if (haveGoal) {
haveGoal = false;
if (!handleRotation()) {
continue;
}
if (!handleLinear()) {
continue;
}
double x, y, yaw;
getPose(goalOdom, x, y, yaw);
rotateAbs(yaw);
}
}
}
// Do angular part of goal
bool MoveBasic::handleRotation()
{
tf2::Transform poseOdom;
if (!getTransform("base_link", "odom", poseOdom)) {
ROS_WARN("Cannot determine robot pose for rotation");
return false;
}
tf2::Vector3 linear = goalOdom.getOrigin() - poseOdom.getOrigin();
double requestedYaw = atan2(linear.y(), linear.x());
return rotateAbs(requestedYaw);
}
// Rotate relative to current orientation
bool MoveBasic::rotateRel(double yaw)
{
tf2::Transform poseOdom;
if (!getTransform("base_link", "odom", poseOdom)) {
ROS_WARN("Cannot determine robot pose for rotation");
return false;
}
double x, y, currentYaw;
getPose(poseOdom, x, y, currentYaw);
double requestedYaw = currentYaw + yaw;
normalizeAngle(requestedYaw);
return rotateAbs(requestedYaw);
}
// Rotate to specified orientation (in radians)
bool MoveBasic::rotateAbs(double requestedYaw)
{
bool done = false;
ros::Rate r(50);
while (!done && ros::ok()) {
ros::spinOnce();
r.sleep();
double x, y, currentYaw;
tf2::Transform poseOdom;
if (!getTransform("base_link", "odom", poseOdom)) {
ROS_WARN("Cannot determine robot pose for rotation");
return false;
}
getPose(poseOdom, x, y, currentYaw);
double angleRemaining = requestedYaw - currentYaw;
normalizeAngle(angleRemaining);
double speed = std::max(minAngularVelocity,
std::min(maxAngularVelocity,
std::sqrt(2.0 * angularAcceleration * std::abs(angleRemaining))));
double velocity = 0;
if (angleRemaining < 0) {
velocity = -speed;
}
else {
velocity = speed;
}
if (haveGoal) { // new goal received
ROS_INFO("Stopping rotation due to new goal");
done = true;
velocity = 0;
}
//ROS_INFO("%f %f %f", rad2deg(angleRemaining), angleRemaining, velocity);
if (std::abs(angleRemaining) < angularTolerance) {
velocity = 0;
done = true;
ROS_INFO("Done rotation, error %f radians %f degrees", angleRemaining, rad2deg(angleRemaining));
}
sendCmd(velocity, 0);
}
return done;
}
// Do linear part of goal
bool MoveBasic::handleLinear()
{
bool done = false;
tf2::Transform poseOdomInitial;
if (!getTransform("base_link", "odom", poseOdomInitial)) {
ROS_WARN("Cannot determine robot pose for linrar");
return false;
}
tf2::Vector3 linear = goalOdom.getOrigin() - poseOdomInitial.getOrigin();
double requestedDistance = linear.length();;
ROS_INFO("Requested distance %f", requestedDistance);
return moveLinear(requestedDistance);
}
// Move foreward specified distance
bool MoveBasic::moveLinear(double requestedDistance)
{
bool done = false;
ros::Rate r(50);
tf2::Transform poseOdomInitial;
if (!getTransform("base_link", "odom", poseOdomInitial)) {
ROS_WARN("Cannot determine robot pose for linrar");
return false;
}
while (!done && ros::ok()) {
ros::spinOnce();
r.sleep();
tf2::Transform poseOdom;
if (!getTransform("base_link", "odom", poseOdom)) {
ROS_WARN("Cannot determine robot pose for linear");
continue;
}
tf2::Vector3 travelled = poseOdomInitial.getOrigin() - poseOdom.getOrigin();
double distTravelled = travelled.length();;
double distRemaining = requestedDistance - distTravelled;
double velocity = std::max(minLinearVelocity,
std::min(maxLinearVelocity, std::min(
std::sqrt(2.0 * linearAcceleration * std::abs(distTravelled)),
std::sqrt(2.0 * linearAcceleration * std::abs(distRemaining)))));
if (haveGoal) { // new goal received
ROS_INFO("Stopping rotation due to new goal");
done = true;
velocity = 0;
}
//ROS_INFO("%f %f %f", distTravelled, distRemaining, velocity);
if (distTravelled > requestedDistance - linearTolerance) {
velocity = 0;
done = true;
ROS_INFO("Done linear, error %f meters", distRemaining);
}
sendCmd(0, velocity);
}
return done;
}
int main(int argc, char ** argv) {
ros::init(argc, argv, "move_basic");
ros::NodeHandle nh("~");
MoveBasic node(nh);
node.run();
return 0;
}
<|endoftext|> |
<commit_before>///
/// @file P2_mpi.cpp
/// @brief 2nd partial sieve function.
/// P2(x, y) counts the numbers <= x that have exactly 2 prime
/// factors each exceeding the a-th prime.
///
/// Copyright (C) 2016 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <aligned_vector.hpp>
#include <BitSieve.hpp>
#include <generate.hpp>
#include <int128.hpp>
#include <min_max.hpp>
#include <mpi_reduce_sum.hpp>
#include <pmath.hpp>
#include <print.hpp>
#include <Wheel.hpp>
#include <stdint.h>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primecount;
namespace {
/// Calculate the segments per thread.
/// The idea is to gradually increase the segments per thread (based
/// on elapsed time) in order to keep all CPU cores busy.
///
int64_t balanceLoad(int64_t segments_per_thread, double start_time)
{
double seconds = get_wtime() - start_time;
if (seconds < 30)
segments_per_thread *= 2;
else if (segments_per_thread >= 4)
segments_per_thread -= segments_per_thread / 4;
return segments_per_thread;
}
/// Cross-off the multiples inside [low, high[
/// of the primes <= sqrt(high - 1).
///
void cross_off(BitSieve& sieve,
vector<int32_t> primes,
Wheel& wheel,
int64_t c,
int64_t low,
int64_t high)
{
int64_t pi_sqrt_high = pi_bsearch(primes, isqrt(high - 1));
for (int64_t i = c + 1; i <= pi_sqrt_high; i++)
{
int64_t prime = primes[i];
int64_t m = wheel[i].next_multiple;
int64_t wheel_index = wheel[i].wheel_index;
// cross-off the multiples of prime inside [low, high[
for (; m < high; m += prime * Wheel::next_multiple_factor(&wheel_index))
sieve.unset(m - low);
wheel[i].set(m, wheel_index);
}
}
template <typename T>
T P2_OpenMP_thread(T x,
int64_t y,
int64_t segment_size,
int64_t segments_per_thread,
int64_t thread_num,
int64_t low,
int64_t limit,
int64_t& pix,
int64_t& pix_count,
vector<int32_t>& primes)
{
pix = 0;
pix_count = 0;
low += thread_num * segments_per_thread * segment_size;
limit = min(low + segments_per_thread * segment_size, limit);
int64_t size = pi_bsearch(primes, isqrt(limit)) + 1;
int64_t start = (int64_t) max(x / limit + 1, y);
int64_t stop = (int64_t) min(x / low, isqrt(x));
T P2_thread = 0;
// P2_thread = \sum_{i = pi[start]}^{pi[stop]} pi(x / primes[i]) - pi(low - 1)
// We use a reverse prime iterator to calculate P2_thread
primesieve::iterator pi(stop + 1, start);
int64_t prime = pi.previous_prime();
bool sieve_primes = true;
Wheel wheel(primes, size, low, sieve_primes);
BitSieve sieve(segment_size);
// segmented sieve of Eratosthenes
for (; low < limit; low += segment_size)
{
// current segment = interval [low, high[
int64_t high = min(low + segment_size, limit);
int64_t x_div_prime = 0;
int64_t j = 0;
int64_t c = 6;
// pre-sieve the multiples of the first c primes
sieve.pre_sieve(c, low, sieve_primes);
// cross-off the multiples of the primes <= sqrt(high - 1)
cross_off(sieve, primes, wheel, c, low, high);
while (prime >= start &&
(x_div_prime = (int64_t) (x / prime)) < high)
{
int64_t next_count = x_div_prime - low;
pix += sieve.count(j, next_count);
j = next_count + 1;
pix_count++;
P2_thread += pix;
prime = pi.previous_prime();
}
pix += sieve.count(j, (high - 1) - low);
}
return P2_thread;
}
/// P2_mpi_master(x, y) counts the numbers <= x that have exactly 2
/// prime factors each exceeding the a-th prime, a = pi(y).
/// Space complexity: O((x / y)^(1/2)).
///
template <typename T>
T P2_mpi_master(T x, int64_t y, int threads)
{
#if __cplusplus >= 201103L
static_assert(prt::is_signed<T>::value,
"P2(T x, ...): T must be signed integer type");
#endif
if (x < 4)
return 0;
T a = pi_legendre(y, threads);
T b = pi_legendre((int64_t) isqrt(x), threads);
if (a >= b)
return 0;
int64_t low = 2;
int64_t limit = (int64_t)(x / max(y, 1));
int64_t sqrt_limit = isqrt(limit);
int64_t segment_size = max(sqrt_limit, 1 << 12);
int64_t segments_per_thread = 64;
threads = validate_threads(threads, limit);
vector<int32_t> primes = generate_primes(sqrt_limit);
aligned_vector<int64_t> pix(threads);
aligned_vector<int64_t> pix_counts(threads);
int proc_id = mpi_proc_id();
int procs = mpi_num_procs();
int64_t interval = limit - low;
int64_t interval_per_proc = ceil_div(interval, procs);
low += interval_per_proc * proc_id;
limit = min(low + interval_per_proc, limit);
// \sum_{i=a+1}^{b} pi(x / primes[i]) - (i - 1)
T p2 = 0;
// \sum_{i=a+1}^{b} -(i - 1)
if (proc_id == mpi_master_proc_id())
p2 = (a - 2) * (a + 1) / 2 - (b - 2) * (b + 1) / 2;
// temporarily disable printing for pi()
bool is_print = print_status();
set_print_status(false);
T pix_total = pi(low - 1, threads);
set_print_status(is_print);
// \sum_{i=a+1}^{b} pi(x / primes[i])
while (low < limit)
{
int64_t segments = ceil_div(limit - low, segment_size);
threads = in_between(1, threads, segments);
segments_per_thread = in_between(1, segments_per_thread, ceil_div(segments, threads));
double time = get_wtime();
#pragma omp parallel for \
num_threads(threads) reduction(+: p2)
for (int i = 0; i < threads; i++)
p2 += P2_OpenMP_thread(x, y, segment_size, segments_per_thread,
i, low, limit, pix[i], pix_counts[i], primes);
low += segments_per_thread * threads * segment_size;
segments_per_thread = balanceLoad(segments_per_thread, time);
// Add missing sum contributions in order
for (int i = 0; i < threads; i++)
{
p2 += pix_total * pix_counts[i];
pix_total += pix[i];
}
if (print_status())
{
double percent = get_percent((double) low, (double) limit);
cout << "\rStatus: " << fixed << setprecision(get_status_precision(x))
<< percent << '%' << flush;
}
}
p2 = mpi_reduce_sum(p2);
return p2;
}
} // namespace
namespace primecount {
int64_t P2_mpi(int64_t x, int64_t y, int threads)
{
print("");
print("=== P2_mpi(x, y) ===");
print("Computation of the 2nd partial sieve function");
print(x, y, threads);
double time = get_wtime();
int64_t p2 = P2_mpi_master(x, y, threads);
print("P2", p2, time);
return p2;
}
#ifdef HAVE_INT128_T
int128_t P2_mpi(int128_t x, int64_t y, int threads)
{
print("");
print("=== P2_mpi(x, y) ===");
print("Computation of the 2nd partial sieve function");
print(x, y, threads);
double time = get_wtime();
int128_t p2 = P2_mpi_master(x, y, threads);
print("P2", p2, time);
return p2;
}
#endif
} // namespace primecount
<commit_msg>Refactoring<commit_after>///
/// @file P2_mpi.cpp
/// @brief 2nd partial sieve function.
/// P2(x, y) counts the numbers <= x that have exactly 2 prime
/// factors each exceeding the a-th prime.
///
/// Copyright (C) 2016 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <aligned_vector.hpp>
#include <BitSieve.hpp>
#include <generate.hpp>
#include <int128.hpp>
#include <min_max.hpp>
#include <mpi_reduce_sum.hpp>
#include <pmath.hpp>
#include <print.hpp>
#include <Wheel.hpp>
#include <stdint.h>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primecount;
namespace {
/// Calculate the segments per thread.
/// The idea is to gradually increase the segments per thread (based
/// on elapsed time) in order to keep all CPU cores busy.
///
int64_t balanceLoad(int64_t segments_per_thread, double start_time)
{
double seconds = get_wtime() - start_time;
if (seconds < 30)
segments_per_thread *= 2;
else if (segments_per_thread >= 4)
segments_per_thread -= segments_per_thread / 4;
return segments_per_thread;
}
/// Cross-off the multiples inside [low, high[
/// of the primes <= sqrt(high - 1).
///
void cross_off(BitSieve& sieve,
vector<int32_t> primes,
Wheel& wheel,
int64_t c,
int64_t low,
int64_t high)
{
int64_t pi_sqrt_high = pi_bsearch(primes, isqrt(high - 1));
for (int64_t i = c + 1; i <= pi_sqrt_high; i++)
{
int64_t prime = primes[i];
int64_t m = wheel[i].next_multiple;
int64_t wheel_index = wheel[i].wheel_index;
// cross-off the multiples of prime inside [low, high[
for (; m < high; m += prime * Wheel::next_multiple_factor(&wheel_index))
sieve.unset(m - low);
wheel[i].set(m, wheel_index);
}
}
template <typename T>
T P2_OpenMP_thread(T x,
int64_t y,
int64_t segment_size,
int64_t segments_per_thread,
int64_t thread_num,
int64_t low,
int64_t limit,
int64_t& pix,
int64_t& pix_count,
vector<int32_t>& primes)
{
pix = 0;
pix_count = 0;
low += thread_num * segments_per_thread * segment_size;
limit = min(low + segments_per_thread * segment_size, limit);
int64_t size = pi_bsearch(primes, isqrt(limit)) + 1;
int64_t start = (int64_t) max(x / limit + 1, y);
int64_t stop = (int64_t) min(x / low, isqrt(x));
T P2_thread = 0;
// P2_thread = \sum_{i = pi[start]}^{pi[stop]} pi(x / primes[i]) - pi(low - 1)
// We use a reverse prime iterator to calculate P2_thread
primesieve::iterator pi(stop + 1, start);
int64_t prime = pi.previous_prime();
bool sieve_primes = true;
Wheel wheel(primes, size, low, sieve_primes);
BitSieve sieve(segment_size);
// segmented sieve of Eratosthenes
for (; low < limit; low += segment_size)
{
// current segment = interval [low, high[
int64_t high = min(low + segment_size, limit);
int64_t x_div_prime = 0;
int64_t j = 0;
int64_t c = 6;
// pre-sieve the multiples of the first c primes
sieve.pre_sieve(c, low, sieve_primes);
// cross-off the multiples of the primes <= sqrt(high - 1)
cross_off(sieve, primes, wheel, c, low, high);
while (prime >= start &&
(x_div_prime = (int64_t) (x / prime)) < high)
{
int64_t next_count = x_div_prime - low;
pix += sieve.count(j, next_count);
j = next_count + 1;
pix_count++;
P2_thread += pix;
prime = pi.previous_prime();
}
pix += sieve.count(j, (high - 1) - low);
}
return P2_thread;
}
/// P2_mpi_master(x, y) counts the numbers <= x that have exactly 2
/// prime factors each exceeding the a-th prime, a = pi(y).
/// Space complexity: O((x / y)^(1/2)).
///
template <typename T>
T P2_mpi_master(T x, int64_t y, int threads)
{
#if __cplusplus >= 201103L
static_assert(prt::is_signed<T>::value,
"P2(T x, ...): T must be signed integer type");
#endif
if (x < 4)
return 0;
T a = pi_legendre(y, threads);
T b = pi_legendre((int64_t) isqrt(x), threads);
if (a >= b)
return 0;
int64_t low = 2;
int64_t limit = (int64_t)(x / max(y, 1));
int64_t sqrt_limit = isqrt(limit);
int64_t segment_size = max(sqrt_limit, 1 << 12);
int64_t segments_per_thread = 64;
threads = validate_threads(threads, limit);
vector<int32_t> primes = generate_primes(sqrt_limit);
aligned_vector<int64_t> pix(threads);
aligned_vector<int64_t> pix_counts(threads);
int proc_id = mpi_proc_id();
int procs = mpi_num_procs();
int64_t interval = limit - low;
int64_t interval_per_proc = ceil_div(interval, procs);
low += interval_per_proc * proc_id;
limit = min(low + interval_per_proc, limit);
// \sum_{i=a+1}^{b} pi(x / primes[i]) - (i - 1)
T p2 = 0;
// \sum_{i=a+1}^{b} -(i - 1)
if (is_mpi_master_proc())
p2 = (a - 2) * (a + 1) / 2 - (b - 2) * (b + 1) / 2;
// temporarily disable printing for pi()
bool is_print = print_status();
set_print_status(false);
T pix_total = pi(low - 1, threads);
set_print_status(is_print);
// \sum_{i=a+1}^{b} pi(x / primes[i])
while (low < limit)
{
int64_t segments = ceil_div(limit - low, segment_size);
threads = in_between(1, threads, segments);
segments_per_thread = in_between(1, segments_per_thread, ceil_div(segments, threads));
double time = get_wtime();
#pragma omp parallel for \
num_threads(threads) reduction(+: p2)
for (int i = 0; i < threads; i++)
p2 += P2_OpenMP_thread(x, y, segment_size, segments_per_thread,
i, low, limit, pix[i], pix_counts[i], primes);
low += segments_per_thread * threads * segment_size;
segments_per_thread = balanceLoad(segments_per_thread, time);
// Add missing sum contributions in order
for (int i = 0; i < threads; i++)
{
p2 += pix_total * pix_counts[i];
pix_total += pix[i];
}
if (print_status())
{
double percent = get_percent((double) low, (double) limit);
cout << "\rStatus: " << fixed << setprecision(get_status_precision(x))
<< percent << '%' << flush;
}
}
p2 = mpi_reduce_sum(p2);
return p2;
}
} // namespace
namespace primecount {
int64_t P2_mpi(int64_t x, int64_t y, int threads)
{
print("");
print("=== P2_mpi(x, y) ===");
print("Computation of the 2nd partial sieve function");
print(x, y, threads);
double time = get_wtime();
int64_t p2 = P2_mpi_master(x, y, threads);
print("P2", p2, time);
return p2;
}
#ifdef HAVE_INT128_T
int128_t P2_mpi(int128_t x, int64_t y, int threads)
{
print("");
print("=== P2_mpi(x, y) ===");
print("Computation of the 2nd partial sieve function");
print(x, y, threads);
double time = get_wtime();
int128_t p2 = P2_mpi_master(x, y, threads);
print("P2", p2, time);
return p2;
}
#endif
} // namespace primecount
<|endoftext|> |
<commit_before>#pragma once
#include <net/socket.h>
#include <assert.h>
#if defined WIN32
# include <Mstcpip.h>
#else
# include <fcntl.h>
# include <netinet/tcp.h>
# include <signal.h>
#endif
namespace net { namespace socket {
NET_INLINE void initialize()
{
static bool initialized = false;
if (!initialized) {
initialized = true;
#if defined WIN32
WSADATA wd;
int rc = WSAStartup(MAKEWORD(2, 2), &wd);
assert(rc >= 0);
#else
struct sigaction sa;
sa.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &sa, 0);
#endif
}
}
NET_INLINE int error_no_()
{
#if defined WIN32
return ::WSAGetLastError();
#else
return errno;
#endif
}
#if defined WIN32
NET_INLINE int wsa_error_to_errno(int errcode)
{
switch (errcode) {
// 10009 - File handle is not valid.
case WSAEBADF:
return EBADF;
// 10013 - Permission denied.
case WSAEACCES:
return EACCES;
// 10014 - Bad address.
case WSAEFAULT:
return EFAULT;
// 10022 - Invalid argument.
case WSAEINVAL:
return EINVAL;
// 10024 - Too many open files.
case WSAEMFILE:
return EMFILE;
// 10035 - A non-blocking socket operation could not be completed immediately.
case WSAEWOULDBLOCK:
return EWOULDBLOCK;
// 10036 - Operation now in progress.
case WSAEINPROGRESS:
return EAGAIN;
// 10040 - Message too long.
case WSAEMSGSIZE:
return EMSGSIZE;
// 10043 - Protocol not supported.
case WSAEPROTONOSUPPORT:
return EPROTONOSUPPORT;
// 10047 - Address family not supported by protocol family.
case WSAEAFNOSUPPORT:
return EAFNOSUPPORT;
// 10048 - Address already in use.
case WSAEADDRINUSE:
return EADDRINUSE;
// 10049 - Cannot assign requested address.
case WSAEADDRNOTAVAIL:
return EADDRNOTAVAIL;
// 10050 - Network is down.
case WSAENETDOWN:
return ENETDOWN;
// 10051 - Network is unreachable.
case WSAENETUNREACH:
return ENETUNREACH;
// 10052 - Network dropped connection on reset.
case WSAENETRESET:
return ENETRESET;
// 10053 - Software caused connection abort.
case WSAECONNABORTED:
return ECONNABORTED;
// 10054 - Connection reset by peer.
case WSAECONNRESET:
return ECONNRESET;
// 10055 - No buffer space available.
case WSAENOBUFS:
return ENOBUFS;
// 10057 - Socket is not connected.
case WSAENOTCONN:
return ENOTCONN;
// 10060 - Connection timed out.
case WSAETIMEDOUT:
return ETIMEDOUT;
// 10061 - Connection refused.
case WSAECONNREFUSED:
return ECONNREFUSED;
// 10065 - No route to host.
case WSAEHOSTUNREACH:
return EHOSTUNREACH;
default:
net_assert(false);
}
// Not reachable
return 0;
}
#endif
NET_INLINE int error_no()
{
#if defined WIN32
return wsa_error_to_errno(error_no_());
#else
return error_no_();
#endif
}
NET_INLINE fd_t open(int domain, int type, int protocol)
{
return ::socket(domain, type, protocol);
}
NET_INLINE void close(fd_t s)
{
assert(s != retired_fd);
#if defined WIN32
int rc = closesocket(s);
#else
int rc = ::close(s);
#endif
net_assert_success(rc);
}
NET_INLINE void shutdown(fd_t s)
{
assert(s != retired_fd);
#if defined WIN32
int rc = ::shutdown(s, SD_BOTH);
#else
int rc = ::shutdown(s, SHUT_RDWR);
#endif
net_assert_success(rc);
}
NET_INLINE void shutdown_read(fd_t s)
{
assert(s != retired_fd);
#if defined WIN32
int rc = ::shutdown(s, SD_RECEIVE);
#else
int rc = ::shutdown(s, SHUT_RD);
#endif
net_assert_success(rc);
}
NET_INLINE void shutdown_write(fd_t s)
{
assert(s != retired_fd);
#if defined WIN32
int rc = ::shutdown(s, SD_SEND);
#else
int rc = ::shutdown(s, SHUT_WR);
#endif
net_assert_success(rc);
}
NET_INLINE void nonblocking(fd_t s)
{
#if defined WIN32
unsigned long nonblock = 1;
int rc = ioctlsocket(s, FIONBIO, &nonblock);
net_assert_success(rc);
#else
int flags = fcntl(s, F_GETFL, 0);
if (flags == -1)
flags = 0;
int rc = fcntl(s, F_SETFL, flags | O_NONBLOCK);
net_assert(rc != -1);
#endif
}
NET_INLINE void keepalive(fd_t s, int keepalive, int keepalive_cnt, int keepalive_idle, int keepalive_intvl)
{
#if defined WIN32
if (keepalive != -1)
{
tcp_keepalive keepaliveopts;
keepaliveopts.onoff = keepalive;
keepaliveopts.keepalivetime = keepalive_idle != -1 ? keepalive_idle * 1000 : 7200000;
keepaliveopts.keepaliveinterval = keepalive_intvl != -1 ? keepalive_intvl * 1000 : 1000;
DWORD num_bytes_returned;
int rc = WSAIoctl(s, SIO_KEEPALIVE_VALS, &keepaliveopts, sizeof(keepaliveopts), NULL, 0, &num_bytes_returned, NULL, NULL);
net_assert_success(rc);
}
#else
if (keepalive != -1)
{
int rc = setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (char*) &keepalive, sizeof (int));
net_assert(rc == 0);
if (keepalive_cnt != -1)
{
int rc = setsockopt(s, IPPROTO_TCP, TCP_KEEPCNT, &keepalive_cnt, sizeof (int));
net_assert_success(rc);
}
if (keepalive_idle != -1)
{
int rc = setsockopt(s, IPPROTO_TCP, TCP_KEEPIDLE, &keepalive_idle, sizeof (int));
net_assert_success(rc);
}
if (keepalive_intvl != -1)
{
int rc = setsockopt(s, IPPROTO_TCP, TCP_KEEPINTVL, &keepalive_intvl, sizeof (int));
net_assert_success(rc);
}
}
#endif
}
NET_INLINE void udp_connect_reset(fd_t s)
{
#if defined WIN32
DWORD byte_retruned = 0;
bool new_be = false;
WSAIoctl(s, SIO_UDP_CONNRESET, &new_be, sizeof(new_be), NULL, 0, &byte_retruned, NULL, NULL);
#endif
}
NET_INLINE void send_buffer(fd_t s, int bufsize)
{
const int rc = setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char*) &bufsize, sizeof bufsize);
net_assert_success(rc);
}
NET_INLINE void recv_buffer(fd_t s, int bufsize)
{
const int rc = setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char*) &bufsize, sizeof bufsize);
net_assert_success(rc);
}
NET_INLINE void reuse(fd_t s)
{
int flag = 1;
#if defined WIN32
const int rc = setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char*) &flag, sizeof flag);
#else
const int rc = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*) &flag, sizeof flag);
#endif
net_assert_success(rc);
}
NET_INLINE bool connect_error(fd_t s)
{
int err = 0;
#if defined WIN32
int len = sizeof(err);
#else
socklen_t len = sizeof(err);
#endif
int rc = getsockopt(s, SOL_SOCKET, SO_ERROR, (char*) &err, &len);
#if defined WIN32
assert(rc == 0);
if (err != 0)
return false;
#else
if (rc == -1)
err = error_no_();
if (err != 0)
return false;
#endif
return true;
}
NET_INLINE int connect(fd_t s, const endpoint& ep)
{
int rc = ::connect(s, ep.addr(), (int)ep.addrlen());
if (rc == 0)
return 0;
const int error_code = error_no_();
#if defined WIN32
if (error_code == WSAEINPROGRESS || error_code == WSAEWOULDBLOCK)
return -2;
#else
if (error_code == EINTR || error_code == EINPROGRESS)
return -2;
#endif
return -1;
}
NET_INLINE int bind(fd_t s, const endpoint& ep)
{
return ::bind(s, ep.addr(), (int)ep.addrlen());
}
NET_INLINE int listen(fd_t s, const endpoint& ep, int backlog)
{
if (::bind(s, ep.addr(), (int)ep.addrlen()) == -1)
{
return -1;
}
if (::listen(s, backlog) == -1)
{
return -2;
}
return 0;
}
NET_INLINE int accept(fd_t s, fd_t& fd, endpoint& ep)
{
struct sockaddr_storage ss;
memset(&ss, 0, sizeof (ss));
#if defined WIN32
int ss_len = sizeof (ss);
#else
socklen_t ss_len = sizeof (ss);
#endif
fd = ::accept(s, (struct sockaddr *) &ss, &ss_len);
if (fd == retired_fd)
{
#if defined WIN32
return -1;
#else
const int error_code = error_no_();
if (error_code != EAGAIN && error_code != ECONNABORTED && error_code != EPROTO && error_code != EINTR)
{
return -1;
}
else
{
return -2;
}
#endif
}
#if defined WIN32
assert(ss_len > 0);
#endif
assert((size_t)ss_len >= ep.addrlen());
memcpy(ep.addr(), &ss, ep.addrlen());
return 0;
}
}}
<commit_msg>析构时有可能失败,暂且先屏蔽了断言<commit_after>#pragma once
#include <net/socket.h>
#include <assert.h>
#if defined WIN32
# include <Mstcpip.h>
#else
# include <fcntl.h>
# include <netinet/tcp.h>
# include <signal.h>
#endif
namespace net { namespace socket {
NET_INLINE void initialize()
{
static bool initialized = false;
if (!initialized) {
initialized = true;
#if defined WIN32
WSADATA wd;
int rc = WSAStartup(MAKEWORD(2, 2), &wd);
assert(rc >= 0);
#else
struct sigaction sa;
sa.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &sa, 0);
#endif
}
}
NET_INLINE int error_no_()
{
#if defined WIN32
return ::WSAGetLastError();
#else
return errno;
#endif
}
#if defined WIN32
NET_INLINE int wsa_error_to_errno(int errcode)
{
switch (errcode) {
// 10009 - File handle is not valid.
case WSAEBADF:
return EBADF;
// 10013 - Permission denied.
case WSAEACCES:
return EACCES;
// 10014 - Bad address.
case WSAEFAULT:
return EFAULT;
// 10022 - Invalid argument.
case WSAEINVAL:
return EINVAL;
// 10024 - Too many open files.
case WSAEMFILE:
return EMFILE;
// 10035 - A non-blocking socket operation could not be completed immediately.
case WSAEWOULDBLOCK:
return EWOULDBLOCK;
// 10036 - Operation now in progress.
case WSAEINPROGRESS:
return EAGAIN;
// 10040 - Message too long.
case WSAEMSGSIZE:
return EMSGSIZE;
// 10043 - Protocol not supported.
case WSAEPROTONOSUPPORT:
return EPROTONOSUPPORT;
// 10047 - Address family not supported by protocol family.
case WSAEAFNOSUPPORT:
return EAFNOSUPPORT;
// 10048 - Address already in use.
case WSAEADDRINUSE:
return EADDRINUSE;
// 10049 - Cannot assign requested address.
case WSAEADDRNOTAVAIL:
return EADDRNOTAVAIL;
// 10050 - Network is down.
case WSAENETDOWN:
return ENETDOWN;
// 10051 - Network is unreachable.
case WSAENETUNREACH:
return ENETUNREACH;
// 10052 - Network dropped connection on reset.
case WSAENETRESET:
return ENETRESET;
// 10053 - Software caused connection abort.
case WSAECONNABORTED:
return ECONNABORTED;
// 10054 - Connection reset by peer.
case WSAECONNRESET:
return ECONNRESET;
// 10055 - No buffer space available.
case WSAENOBUFS:
return ENOBUFS;
// 10057 - Socket is not connected.
case WSAENOTCONN:
return ENOTCONN;
// 10060 - Connection timed out.
case WSAETIMEDOUT:
return ETIMEDOUT;
// 10061 - Connection refused.
case WSAECONNREFUSED:
return ECONNREFUSED;
// 10065 - No route to host.
case WSAEHOSTUNREACH:
return EHOSTUNREACH;
default:
net_assert(false);
}
// Not reachable
return 0;
}
#endif
NET_INLINE int error_no()
{
#if defined WIN32
return wsa_error_to_errno(error_no_());
#else
return error_no_();
#endif
}
NET_INLINE fd_t open(int domain, int type, int protocol)
{
return ::socket(domain, type, protocol);
}
NET_INLINE void close(fd_t s)
{
assert(s != retired_fd);
#if defined WIN32
int rc = closesocket(s);
#else
int rc = ::close(s);
#endif
//net_assert_success(rc);
}
NET_INLINE void shutdown(fd_t s)
{
assert(s != retired_fd);
#if defined WIN32
int rc = ::shutdown(s, SD_BOTH);
#else
int rc = ::shutdown(s, SHUT_RDWR);
#endif
net_assert_success(rc);
}
NET_INLINE void shutdown_read(fd_t s)
{
assert(s != retired_fd);
#if defined WIN32
int rc = ::shutdown(s, SD_RECEIVE);
#else
int rc = ::shutdown(s, SHUT_RD);
#endif
net_assert_success(rc);
}
NET_INLINE void shutdown_write(fd_t s)
{
assert(s != retired_fd);
#if defined WIN32
int rc = ::shutdown(s, SD_SEND);
#else
int rc = ::shutdown(s, SHUT_WR);
#endif
net_assert_success(rc);
}
NET_INLINE void nonblocking(fd_t s)
{
#if defined WIN32
unsigned long nonblock = 1;
int rc = ioctlsocket(s, FIONBIO, &nonblock);
net_assert_success(rc);
#else
int flags = fcntl(s, F_GETFL, 0);
if (flags == -1)
flags = 0;
int rc = fcntl(s, F_SETFL, flags | O_NONBLOCK);
net_assert(rc != -1);
#endif
}
NET_INLINE void keepalive(fd_t s, int keepalive, int keepalive_cnt, int keepalive_idle, int keepalive_intvl)
{
#if defined WIN32
if (keepalive != -1)
{
tcp_keepalive keepaliveopts;
keepaliveopts.onoff = keepalive;
keepaliveopts.keepalivetime = keepalive_idle != -1 ? keepalive_idle * 1000 : 7200000;
keepaliveopts.keepaliveinterval = keepalive_intvl != -1 ? keepalive_intvl * 1000 : 1000;
DWORD num_bytes_returned;
int rc = WSAIoctl(s, SIO_KEEPALIVE_VALS, &keepaliveopts, sizeof(keepaliveopts), NULL, 0, &num_bytes_returned, NULL, NULL);
net_assert_success(rc);
}
#else
if (keepalive != -1)
{
int rc = setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (char*) &keepalive, sizeof (int));
net_assert(rc == 0);
if (keepalive_cnt != -1)
{
int rc = setsockopt(s, IPPROTO_TCP, TCP_KEEPCNT, &keepalive_cnt, sizeof (int));
net_assert_success(rc);
}
if (keepalive_idle != -1)
{
int rc = setsockopt(s, IPPROTO_TCP, TCP_KEEPIDLE, &keepalive_idle, sizeof (int));
net_assert_success(rc);
}
if (keepalive_intvl != -1)
{
int rc = setsockopt(s, IPPROTO_TCP, TCP_KEEPINTVL, &keepalive_intvl, sizeof (int));
net_assert_success(rc);
}
}
#endif
}
NET_INLINE void udp_connect_reset(fd_t s)
{
#if defined WIN32
DWORD byte_retruned = 0;
bool new_be = false;
WSAIoctl(s, SIO_UDP_CONNRESET, &new_be, sizeof(new_be), NULL, 0, &byte_retruned, NULL, NULL);
#endif
}
NET_INLINE void send_buffer(fd_t s, int bufsize)
{
const int rc = setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char*) &bufsize, sizeof bufsize);
net_assert_success(rc);
}
NET_INLINE void recv_buffer(fd_t s, int bufsize)
{
const int rc = setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char*) &bufsize, sizeof bufsize);
net_assert_success(rc);
}
NET_INLINE void reuse(fd_t s)
{
int flag = 1;
#if defined WIN32
const int rc = setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char*) &flag, sizeof flag);
#else
const int rc = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*) &flag, sizeof flag);
#endif
net_assert_success(rc);
}
NET_INLINE bool connect_error(fd_t s)
{
int err = 0;
#if defined WIN32
int len = sizeof(err);
#else
socklen_t len = sizeof(err);
#endif
int rc = getsockopt(s, SOL_SOCKET, SO_ERROR, (char*) &err, &len);
#if defined WIN32
assert(rc == 0);
if (err != 0)
return false;
#else
if (rc == -1)
err = error_no_();
if (err != 0)
return false;
#endif
return true;
}
NET_INLINE int connect(fd_t s, const endpoint& ep)
{
int rc = ::connect(s, ep.addr(), (int)ep.addrlen());
if (rc == 0)
return 0;
const int error_code = error_no_();
#if defined WIN32
if (error_code == WSAEINPROGRESS || error_code == WSAEWOULDBLOCK)
return -2;
#else
if (error_code == EINTR || error_code == EINPROGRESS)
return -2;
#endif
return -1;
}
NET_INLINE int bind(fd_t s, const endpoint& ep)
{
return ::bind(s, ep.addr(), (int)ep.addrlen());
}
NET_INLINE int listen(fd_t s, const endpoint& ep, int backlog)
{
if (::bind(s, ep.addr(), (int)ep.addrlen()) == -1)
{
return -1;
}
if (::listen(s, backlog) == -1)
{
return -2;
}
return 0;
}
NET_INLINE int accept(fd_t s, fd_t& fd, endpoint& ep)
{
struct sockaddr_storage ss;
memset(&ss, 0, sizeof (ss));
#if defined WIN32
int ss_len = sizeof (ss);
#else
socklen_t ss_len = sizeof (ss);
#endif
fd = ::accept(s, (struct sockaddr *) &ss, &ss_len);
if (fd == retired_fd)
{
#if defined WIN32
return -1;
#else
const int error_code = error_no_();
if (error_code != EAGAIN && error_code != ECONNABORTED && error_code != EPROTO && error_code != EINTR)
{
return -1;
}
else
{
return -2;
}
#endif
}
#if defined WIN32
assert(ss_len > 0);
#endif
assert((size_t)ss_len >= ep.addrlen());
memcpy(ep.addr(), &ss, ep.addrlen());
return 0;
}
}}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "unzip.h"
#include "MachineInstaller.h"
#include "resource.h"
#include <sddl.h>
bool findPackageFromEmbeddedZip(wchar_t* buf, DWORD cbSize)
{
bool ret = false;
CResource zipResource;
if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) {
return false;
}
DWORD dwSize = zipResource.GetSize();
if (dwSize < 0x100) {
return false;
}
BYTE* pData = (BYTE*)zipResource.Lock();
HZIP zipFile = OpenZip(pData, dwSize, NULL);
ZRESULT zr;
int index = 0;
do {
ZIPENTRY zentry;
zr = GetZipItem(zipFile, index, &zentry);
if (zr != ZR_OK && zr != ZR_MORE) {
break;
}
if (wcsstr(zentry.name, L"nupkg")) {
ZeroMemory(buf, cbSize);
int idx = wcscspn(zentry.name, L"-");
memcpy(buf, zentry.name, sizeof(wchar_t) * idx);
ret = true;
break;
}
index++;
} while (zr == ZR_MORE || zr == ZR_OK);
CloseZip(zipFile);
zipResource.Release();
return ret;
}
int MachineInstaller::PerformMachineInstallSetup()
{
wchar_t packageName[512];
if (!findPackageFromEmbeddedZip(packageName, sizeof(packageName))) {
MessageBox(NULL, L"Corrupt installer", L"Cannot find package name for installer, is it created correctly?", MB_OK);
return ERROR_INVALID_PARAMETER;
}
wchar_t machineInstallFolder[MAX_PATH];
SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, machineInstallFolder);
wcscat(machineInstallFolder, L"\\SquirrelMachineInstalls");
// NB: This is the DACL for Program Files
PSECURITY_DESCRIPTOR descriptor;
ConvertStringSecurityDescriptorToSecurityDescriptor(
L"D:PAI(A;;FA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)(A;CIIO;GA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)(A;;0x1301bf;;;SY)(A;OICIIO;GA;;;SY)(A;;0x1301bf;;;BA)(A;OICIIO;GA;;;BA)(A;;0x1200a9;;;BU)(A;OICIIO;GXGR;;;BU)(A;OICIIO;GA;;;CO)(A;;0x1200a9;;;AC)(A;OICIIO;GXGR;;;AC)",
SDDL_REVISION_1,
&descriptor, NULL);
SECURITY_ATTRIBUTES attrs;
attrs.nLength = sizeof(SECURITY_ATTRIBUTES);
attrs.bInheritHandle = false;
attrs.lpSecurityDescriptor = descriptor;
if (!CreateDirectory(machineInstallFolder, &attrs) && GetLastError() != ERROR_ALREADY_EXISTS) {
LocalFree(descriptor);
return GetLastError();
}
LocalFree(descriptor);
wcscat(machineInstallFolder, L"\\");
wcscat(machineInstallFolder, packageName);
wcscat(machineInstallFolder, L".exe");
wchar_t ourFile[MAX_PATH];
HMODULE hMod = GetModuleHandle(NULL);
GetModuleFileName(hMod, ourFile, _countof(ourFile));
if (!CopyFile(ourFile, machineInstallFolder, false)) {
return GetLastError();
}
HKEY runKey;
DWORD dontcare;
if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL, 0, KEY_ALL_ACCESS, NULL, &runKey, &dontcare) != ERROR_SUCCESS) {
return GetLastError();
}
wcscat_s(machineInstallFolder, L" --checkInstall");
if (RegSetValueEx(runKey, packageName, 0, REG_SZ, (BYTE*)machineInstallFolder, (wcsnlen(machineInstallFolder, sizeof(machineInstallFolder)) + 1) * sizeof(wchar_t)) != ERROR_SUCCESS) {
return GetLastError();
}
RegCloseKey(runKey);
return 0;
}
bool MachineInstaller::ShouldSilentInstall()
{
// Figure out the package name from our own EXE name
wchar_t ourFile[MAX_PATH];
HMODULE hMod = GetModuleHandle(NULL);
GetModuleFileName(hMod, ourFile, _countof(ourFile));
CString fullPath = CString(ourFile);
CString pkgName = CString(ourFile + fullPath.ReverseFind(L'\\'));
pkgName.Replace(L".exe", L"");
wchar_t installFolder[MAX_PATH];
// C:\Users\Username\AppData\Local\$pkgName\packages
SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder);
wcscat(installFolder, L"\\");
wcscat(installFolder, pkgName);
wcscat(installFolder, L"\\");
wcscat(installFolder, L"packages");
if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) {
return false;
}
// C:\Users\Username\AppData\Local\$pkgName\.dead (was machine-installed but user uninstalled)
SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder);
wcscat(installFolder, L"\\");
wcscat(installFolder, pkgName);
wcscat(installFolder, L"\\");
wcscat(installFolder, L".dead");
if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) {
return false;
}
// C:\ProgramData\$pkgName\$username\packages
wchar_t username[512];
DWORD unamesize = _countof(username);
SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder);
GetUserName(username, &unamesize);
wcscat(installFolder, L"\\");
wcscat(installFolder, pkgName);
wcscat(installFolder, L"\\");
wcscat(installFolder, username);
wcscat(installFolder, L"\\");
wcscat(installFolder, L"packages");
if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) {
return false;
}
// C:\ProgramData\$pkgName\$username\.dead
SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder);
wcscat(installFolder, L"\\");
wcscat(installFolder, pkgName);
wcscat(installFolder, L"\\");
wcscat(installFolder, username);
wcscat(installFolder, L"\\");
wcscat(installFolder, L".dead");
if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) {
return false;
}
// None of these exist, we should install
return true;
}
<commit_msg>Update ACL to work with Windows 7. AC SID only valid on Windows 8+<commit_after>#include "stdafx.h"
#include "unzip.h"
#include "MachineInstaller.h"
#include "resource.h"
#include <sddl.h>
bool findPackageFromEmbeddedZip(wchar_t* buf, DWORD cbSize)
{
bool ret = false;
CResource zipResource;
if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) {
return false;
}
DWORD dwSize = zipResource.GetSize();
if (dwSize < 0x100) {
return false;
}
BYTE* pData = (BYTE*)zipResource.Lock();
HZIP zipFile = OpenZip(pData, dwSize, NULL);
ZRESULT zr;
int index = 0;
do {
ZIPENTRY zentry;
zr = GetZipItem(zipFile, index, &zentry);
if (zr != ZR_OK && zr != ZR_MORE) {
break;
}
if (wcsstr(zentry.name, L"nupkg")) {
ZeroMemory(buf, cbSize);
int idx = wcscspn(zentry.name, L"-");
memcpy(buf, zentry.name, sizeof(wchar_t) * idx);
ret = true;
break;
}
index++;
} while (zr == ZR_MORE || zr == ZR_OK);
CloseZip(zipFile);
zipResource.Release();
return ret;
}
int MachineInstaller::PerformMachineInstallSetup()
{
wchar_t packageName[512];
if (!findPackageFromEmbeddedZip(packageName, sizeof(packageName))) {
MessageBox(NULL, L"Corrupt installer", L"Cannot find package name for installer, is it created correctly?", MB_OK);
return ERROR_INVALID_PARAMETER;
}
wchar_t machineInstallFolder[MAX_PATH];
SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, machineInstallFolder);
wcscat(machineInstallFolder, L"\\SquirrelMachineInstalls");
// NB: This is the DACL for Program Files
wchar_t sddl[512] = L"D:PAI(A;;FA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)(A;CIIO;GA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)(A;;0x1301bf;;;SY)(A;OICIIO;GA;;;SY)(A;;0x1301bf;;;BA)(A;OICIIO;GA;;;BA)(A;;0x1200a9;;;BU)(A;OICIIO;GXGR;;;BU)(A;OICIIO;GA;;;CO)";
if (IsWindows8OrGreater())
{
// Add ALL APPLICATION PACKAGES account (Only available on Windows 8 and greater)
wcscat(sddl, L"(A;;0x1200a9;;;AC)(A;OICIIO;GXGR;;;AC)");
}
PSECURITY_DESCRIPTOR descriptor;
ConvertStringSecurityDescriptorToSecurityDescriptor(
sddl,
SDDL_REVISION_1,
&descriptor, NULL);
SECURITY_ATTRIBUTES attrs;
attrs.nLength = sizeof(SECURITY_ATTRIBUTES);
attrs.bInheritHandle = false;
attrs.lpSecurityDescriptor = descriptor;
if (!CreateDirectory(machineInstallFolder, &attrs) && GetLastError() != ERROR_ALREADY_EXISTS) {
LocalFree(descriptor);
return GetLastError();
}
LocalFree(descriptor);
wcscat(machineInstallFolder, L"\\");
wcscat(machineInstallFolder, packageName);
wcscat(machineInstallFolder, L".exe");
wchar_t ourFile[MAX_PATH];
HMODULE hMod = GetModuleHandle(NULL);
GetModuleFileName(hMod, ourFile, _countof(ourFile));
if (!CopyFile(ourFile, machineInstallFolder, false)) {
return GetLastError();
}
HKEY runKey;
DWORD dontcare;
if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL, 0, KEY_ALL_ACCESS, NULL, &runKey, &dontcare) != ERROR_SUCCESS) {
return GetLastError();
}
wcscat_s(machineInstallFolder, L" --checkInstall");
if (RegSetValueEx(runKey, packageName, 0, REG_SZ, (BYTE*)machineInstallFolder, (wcsnlen(machineInstallFolder, sizeof(machineInstallFolder)) + 1) * sizeof(wchar_t)) != ERROR_SUCCESS) {
return GetLastError();
}
RegCloseKey(runKey);
return 0;
}
bool MachineInstaller::ShouldSilentInstall()
{
// Figure out the package name from our own EXE name
wchar_t ourFile[MAX_PATH];
HMODULE hMod = GetModuleHandle(NULL);
GetModuleFileName(hMod, ourFile, _countof(ourFile));
CString fullPath = CString(ourFile);
CString pkgName = CString(ourFile + fullPath.ReverseFind(L'\\'));
pkgName.Replace(L".exe", L"");
wchar_t installFolder[MAX_PATH];
// C:\Users\Username\AppData\Local\$pkgName\packages
SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder);
wcscat(installFolder, L"\\");
wcscat(installFolder, pkgName);
wcscat(installFolder, L"\\");
wcscat(installFolder, L"packages");
if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) {
return false;
}
// C:\Users\Username\AppData\Local\$pkgName\.dead (was machine-installed but user uninstalled)
SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder);
wcscat(installFolder, L"\\");
wcscat(installFolder, pkgName);
wcscat(installFolder, L"\\");
wcscat(installFolder, L".dead");
if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) {
return false;
}
// C:\ProgramData\$pkgName\$username\packages
wchar_t username[512];
DWORD unamesize = _countof(username);
SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder);
GetUserName(username, &unamesize);
wcscat(installFolder, L"\\");
wcscat(installFolder, pkgName);
wcscat(installFolder, L"\\");
wcscat(installFolder, username);
wcscat(installFolder, L"\\");
wcscat(installFolder, L"packages");
if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) {
return false;
}
// C:\ProgramData\$pkgName\$username\.dead
SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder);
wcscat(installFolder, L"\\");
wcscat(installFolder, pkgName);
wcscat(installFolder, L"\\");
wcscat(installFolder, username);
wcscat(installFolder, L"\\");
wcscat(installFolder, L".dead");
if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) {
return false;
}
// None of these exist, we should install
return true;
}
<|endoftext|> |
<commit_before>#include <map>
#include "object_nonattack.h"
#include "util/bitmap.h"
#include "util/funcs.h"
#include "globals.h"
#include "animation.h"
#include "util/tokenreader.h"
#include "util/token.h"
#include <math.h>
#include "cat.h"
using namespace std;
Cat::Cat( const string & filename ) throw( LoadException ):
ObjectNonAttack( 0, 0 ),
state( IDLE1 ){
setMaxHealth( 1 );
setHealth( 1 );
TokenReader tr( filename );
try{
Token * head;
head = tr.readToken();
if ( *head != "cat" ){
throw new LoadException( "File does not begin with 'Cat'" );
}
while ( head->hasTokens() ){
Token * next = head->readToken();
if ( *next == "animation" ){
Animation * animation = new Animation( next, 0 );
animations[ animation->getName() ] = animation;
}
}
if ( animations.size() == 0 ){
throw new LoadException( "No animation given" );
}
} catch( const TokenException & ex ){
cerr<< "Could not read "<<filename<<" : "<<ex.getReason()<<endl;
throw LoadException( "Could not open file" );
}
current_animation = animations[ "idle1" ];
meow = Sound( Util::getDataPath() + "/misc/cat/meow.wav" );
}
Cat::Cat( const Cat & cat ):
ObjectNonAttack( cat ),
state( IDLE1 ){
setMaxHealth( cat.getMaxHealth() );
setHealth( cat.getHealth() );
/*
animation = new Animation( *Cat.animation, 0 );
animation->reset();
*/
for ( map< string, Animation * >::const_iterator it = cat.animations.begin(); it != cat.animations.end(); it++ ){
// animations.push_back( new Animation( **it, 0 ) );
animations[ it->first ] = new Animation( *(it->second), 0 );
}
current_animation = animations[ "idle1" ];
meow = cat.meow;
}
const int Cat::getRX() const {
if ( current_animation ){
if ( getFacing() == FACING_LEFT ){
return Object::getRX() - current_animation->getOffsetX();
} else {
return Object::getRX() + current_animation->getOffsetX();
}
}
return Object::getRX();
}
void Cat::act( vector< Object * > * others, World * world, vector< Object * > * add ){
switch ( state ){
case WALK : {
moveX( -0.8 );
if ( Util::rnd( 5 ) == 0 ){
moveZ( -0.2 );
}
if ( Util::rnd( 5 ) == 0 ){
moveZ( 0.2 );
}
break;
}
case RUN : {
moveX( -2.2 );
if ( Util::rnd( 5 ) == 0 ){
moveZ( -0.2 );
}
if ( Util::rnd( 5 ) == 0 ){
moveZ( 0.2 );
}
break;
}
default : {
break;
}
}
if ( current_animation->Act() ){
switch ( state ){
case IDLE1 :
case IDLE2 : {
switch ( Util::rnd( 5 ) ){
case 0 : {
state = IDLE1;
current_animation = animations[ "idle1" ];
break;
}
case 1 : {
state = IDLE2;
current_animation = animations[ "idle2" ];
break;
}
case 2 :
case 3 :
case 4 : {
state = YAWN;
current_animation = animations[ "yawn" ];
if ( Util::rnd( 2 ) == 0 ){
setFacing( getOppositeFacing() );
}
break;
}
default : {
break;
}
}
break;
}
case YAWN : {
switch ( Util::rnd( 6 ) ){
case 0 :
case 1 : {
state = SIT;
current_animation = animations[ "sit" ];
break;
}
case 2 :
case 3 :
case 4 :
case 5 : {
state = WALK;
current_animation = animations[ "walk" ];
break;
}
}
break;
}
case WALK : {
switch ( Util::rnd( 12 ) ){
case 0 : {
state = SIT;
current_animation = animations[ "sit" ];
break;
}
case 1 :
case 2 :
case 3 : {
state = TURN;
current_animation = animations[ "turn" ];
break;
}
case 4 :
case 5 : {
state = RUN;
current_animation = animations[ "run" ];
}
default : {
}
}
break;
}
case SIT : {
switch ( Util::rnd( 2 ) ){
case 0 : {
state = IDLE1;
current_animation = animations[ "idle1" ];
break;
}
case 1 : {
state = IDLE2;
current_animation = animations[ "idle2" ];
break;
}
}
break;
}
case TURN : {
setFacing( getOppositeFacing() );
state = WALK;
current_animation = animations[ "walk" ];
break;
}
case RUN : {
switch ( Util::rnd( 4 ) ){
case 0 : {
state = WALK;
current_animation = animations[ "walk" ];
break;
}
default : {
}
}
break;
}
}
current_animation->reset();
}
}
void Cat::draw( Bitmap * work, int rel_x ){
if ( getFacing() == Object::FACING_RIGHT ){
current_animation->Draw( getRX() - rel_x, getRY(), work );
} else {
current_animation->DrawFlipped( getRX() - rel_x, getRY(), work );
}
if ( Util::rnd( 2000 ) == 0 ){
meow.play( (int)(255 - fabs(getRX() - rel_x) / 50), 128 + (getRX() - rel_x) / 50 );
}
}
bool Cat::isCollidable( Object * obj ){
return false;
}
bool Cat::isGettable(){
return false;
}
const int Cat::getWidth() const {
return 0;
}
const int Cat::getHeight() const {
return 0;
}
Object * Cat::copy(){
return new Cat( *this );
}
Cat::~Cat(){
for ( map< string, Animation * >::iterator it = animations.begin(); it != animations.end(); it++ ){
delete it->second;
}
}
<commit_msg>dont use new for exceptions<commit_after>#include <map>
#include "object_nonattack.h"
#include "util/bitmap.h"
#include "util/funcs.h"
#include "globals.h"
#include "animation.h"
#include "util/tokenreader.h"
#include "util/token.h"
#include <math.h>
#include "cat.h"
using namespace std;
Cat::Cat( const string & filename ) throw( LoadException ):
ObjectNonAttack( 0, 0 ),
state( IDLE1 ){
setMaxHealth( 1 );
setHealth( 1 );
TokenReader tr( filename );
try{
Token * head;
head = tr.readToken();
if ( *head != "cat" ){
throw LoadException( "File does not begin with 'Cat'" );
}
while ( head->hasTokens() ){
Token * next = head->readToken();
if ( *next == "animation" ){
Animation * animation = new Animation( next, 0 );
animations[ animation->getName() ] = animation;
}
}
if ( animations.size() == 0 ){
throw LoadException( "No animation given" );
}
} catch( const TokenException & ex ){
cerr<< "Could not read "<<filename<<" : "<<ex.getReason()<<endl;
throw LoadException( "Could not open file" );
}
current_animation = animations[ "idle1" ];
meow = Sound( Util::getDataPath() + "/misc/cat/meow.wav" );
}
Cat::Cat( const Cat & cat ):
ObjectNonAttack( cat ),
state( IDLE1 ){
setMaxHealth( cat.getMaxHealth() );
setHealth( cat.getHealth() );
/*
animation = new Animation( *Cat.animation, 0 );
animation->reset();
*/
for ( map< string, Animation * >::const_iterator it = cat.animations.begin(); it != cat.animations.end(); it++ ){
// animations.push_back( new Animation( **it, 0 ) );
animations[ it->first ] = new Animation( *(it->second), 0 );
}
current_animation = animations[ "idle1" ];
meow = cat.meow;
}
const int Cat::getRX() const {
if ( current_animation ){
if ( getFacing() == FACING_LEFT ){
return Object::getRX() - current_animation->getOffsetX();
} else {
return Object::getRX() + current_animation->getOffsetX();
}
}
return Object::getRX();
}
void Cat::act( vector< Object * > * others, World * world, vector< Object * > * add ){
switch ( state ){
case WALK : {
moveX( -0.8 );
if ( Util::rnd( 5 ) == 0 ){
moveZ( -0.2 );
}
if ( Util::rnd( 5 ) == 0 ){
moveZ( 0.2 );
}
break;
}
case RUN : {
moveX( -2.2 );
if ( Util::rnd( 5 ) == 0 ){
moveZ( -0.2 );
}
if ( Util::rnd( 5 ) == 0 ){
moveZ( 0.2 );
}
break;
}
default : {
break;
}
}
if ( current_animation->Act() ){
switch ( state ){
case IDLE1 :
case IDLE2 : {
switch ( Util::rnd( 5 ) ){
case 0 : {
state = IDLE1;
current_animation = animations[ "idle1" ];
break;
}
case 1 : {
state = IDLE2;
current_animation = animations[ "idle2" ];
break;
}
case 2 :
case 3 :
case 4 : {
state = YAWN;
current_animation = animations[ "yawn" ];
if ( Util::rnd( 2 ) == 0 ){
setFacing( getOppositeFacing() );
}
break;
}
default : {
break;
}
}
break;
}
case YAWN : {
switch ( Util::rnd( 6 ) ){
case 0 :
case 1 : {
state = SIT;
current_animation = animations[ "sit" ];
break;
}
case 2 :
case 3 :
case 4 :
case 5 : {
state = WALK;
current_animation = animations[ "walk" ];
break;
}
}
break;
}
case WALK : {
switch ( Util::rnd( 12 ) ){
case 0 : {
state = SIT;
current_animation = animations[ "sit" ];
break;
}
case 1 :
case 2 :
case 3 : {
state = TURN;
current_animation = animations[ "turn" ];
break;
}
case 4 :
case 5 : {
state = RUN;
current_animation = animations[ "run" ];
}
default : {
}
}
break;
}
case SIT : {
switch ( Util::rnd( 2 ) ){
case 0 : {
state = IDLE1;
current_animation = animations[ "idle1" ];
break;
}
case 1 : {
state = IDLE2;
current_animation = animations[ "idle2" ];
break;
}
}
break;
}
case TURN : {
setFacing( getOppositeFacing() );
state = WALK;
current_animation = animations[ "walk" ];
break;
}
case RUN : {
switch ( Util::rnd( 4 ) ){
case 0 : {
state = WALK;
current_animation = animations[ "walk" ];
break;
}
default : {
}
}
break;
}
}
current_animation->reset();
}
}
void Cat::draw( Bitmap * work, int rel_x ){
if ( getFacing() == Object::FACING_RIGHT ){
current_animation->Draw( getRX() - rel_x, getRY(), work );
} else {
current_animation->DrawFlipped( getRX() - rel_x, getRY(), work );
}
if ( Util::rnd( 2000 ) == 0 ){
meow.play( (int)(255 - fabs(getRX() - rel_x) / 50), 128 + (getRX() - rel_x) / 50 );
}
}
bool Cat::isCollidable( Object * obj ){
return false;
}
bool Cat::isGettable(){
return false;
}
const int Cat::getWidth() const {
return 0;
}
const int Cat::getHeight() const {
return 0;
}
Object * Cat::copy(){
return new Cat( *this );
}
Cat::~Cat(){
for ( map< string, Animation * >::iterator it = animations.begin(); it != animations.end(); it++ ){
delete it->second;
}
}
<|endoftext|> |
<commit_before><commit_msg>cleanup<commit_after><|endoftext|> |
<commit_before><commit_msg>Clean up function declarations<commit_after><|endoftext|> |
<commit_before>/** \copyright
* Copyright (c) 2013, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
* \file If.hxx
*
* Asynchronous NMRAnet interface.
*
* @author Balazs Racz
* @date 3 Dec 2013
*/
#ifndef _OPENLCB_IF_HXX_
#define _OPENLCB_IF_HXX_
/// @todo(balazs.racz) remove this dep
#include <string>
#include "openlcb/Node.hxx"
#include "openlcb/Defs.hxx"
#include "executor/Dispatcher.hxx"
#include "executor/Service.hxx"
#include "executor/Executor.hxx"
#include "utils/Buffer.hxx"
#include "utils/Queue.hxx"
#include "utils/Map.hxx"
namespace openlcb
{
class Node;
/// Container that carries the data bytes in an NMRAnet message.
typedef string Payload;
/** Convenience function to render a 48-bit NMRAnet node ID into a new buffer.
*
* @param id is the 48-bit ID to render.
* @returns a new buffer (from the main pool) with 6 bytes of used space, a
* big-endian representation of the node ID.
*/
extern string node_id_to_buffer(NodeID id);
/** Convenience function to render a 48-bit NMRAnet node ID into an existing
* buffer.
*
* @param id is the 48-bit ID to render.
* @param data is the memory space to write the rendered ID into. There must be
* at least 6 bytes available at this address.
*/
extern void node_id_to_data(NodeID id, void* data);
/** Converts a 6-byte-long buffer to a node ID.
*
* @param buf is a buffer that has to have exactly 6 bytes used, filled with a
* big-endian node id.
* @returns the node id (in host endian).
*/
extern NodeID buffer_to_node_id(const string& buf);
/** Converts 6 bytes of big-endian data to a node ID.
*
* @param d is a pointer to at least 6 valid bytes.
* @returns the node ID represented by the first 6 bytes of d.
*/
extern NodeID data_to_node_id(const void* d);
/** Converts an Event ID to a Payload suitable to be sent as an event report. */
extern Payload eventid_to_buffer(uint64_t eventid);
/** Takes 8 bytes (big-endian) from *data, and returns the event id they
* represent. */
inline uint64_t data_to_eventid(const void* data) {
uint64_t ret = 0;
memcpy(&ret, data, 8);
return be64toh(ret);
}
/** Formats a payload for response of error response messages such as OPtioanl
* Interaction Rejected or Terminate Due To Error. */
extern string error_to_buffer(uint16_t error_code, uint16_t mti);
/** Formats a payload for response of error response messages such as Datagram
* Rejected. */
extern string error_to_buffer(uint16_t error_code);
/** Writes an error code into a payload object at a given pointer. */
extern void error_to_data(uint16_t error_code, void* data);
/** Appends an error to the end of an existing buffer. */
extern void append_error_to_buffer(uint16_t error_code, Payload* p);
/** Parses the payload of an Optional Interaction Rejected or Terminate Due To
* Error message.
* @param payload is the contents of the incoming addressed message.
* @param error_code will hold the 2-byte error code, or ERROR_PERMANENT if not
* specified
* @param mti will hold the MTI value, or 0 if not specified
* @param error_message will hold all remaining bytes that came with the error
* message.
*/
extern void buffer_to_error(const Payload& payload, uint16_t* error_code, uint16_t* mti, string* error_message);
/** A global class / variable for empty or not-yet-initialized payloads. */
extern string EMPTY_PAYLOAD;
/// @return the high 4 bytes of a node ID. @param id is the node ID.
inline unsigned node_high(NodeID id) {
return id >> 32;
}
/// @return the low 4 bytes of a node ID. @param id is the node ID.
inline unsigned node_low(NodeID id) {
return id & 0xffffffffU;
}
/// Helper function to send an event report to the bus. Performs
/// synchronous (dynamic) memory allocation so use it sparingly and when
/// there is sufficient amount of RAM available.
/// @param event_id is the event to send off.
extern void send_event(Node* src_node, uint64_t event_id);
/** This class is used in the dispatching of incoming or outgoing NMRAnet
* messages to the message handlers at the protocol-agnostic level (i.e. not
* CAN or TCP-specific).
*
* TODO(balazs.racz) There shall be one instance of this class that will be
* sent to all handlers that expressed interest in that MTI. When all those
* handlers are done, the instance should be freed. Currently the instance is
* copied by the dispatcher separately for each handler. */
struct GenMessage
{
GenMessage()
: src({0, 0}), dst({0, 0}), flagsSrc(0), flagsDst(0) {}
void reset(Defs::MTI mti, NodeID src, NodeHandle dst, const string &payload)
{
this->mti = mti;
this->src = {src, 0};
this->dst = dst;
this->payload = payload;
this->dstNode = nullptr;
this->flagsSrc = 0;
this->flagsDst = 0;
}
void reset(Defs::MTI mti, NodeID src, const string &payload)
{
this->mti = mti;
this->src = {src, 0};
this->dst = {0, 0};
this->payload = payload;
this->dstNode = nullptr;
this->flagsSrc = 0;
this->flagsDst = 0;
}
/// OpenLCB MTI of the incoming message.
Defs::MTI mti;
/// Source node.
NodeHandle src;
/// Destination node.
NodeHandle dst;
/// If the destination node is local, this value is non-NULL.
Node *dstNode;
/// Data content in the message body. Owned by the dispatcher.
/// @todo(balazs.racz) figure out a better container.
string payload;
unsigned flagsSrc : 4;
unsigned flagsDst : 4;
unsigned get_flags_src() {
return flagsSrc;
}
unsigned get_flags_dst() {
return flagsDst;
}
void set_flag_src(unsigned flags) {
flagsSrc |= flags;
}
void clear_flag_src(unsigned flags) {
flagsSrc &= ~flags;
}
/** Returns true if src flags has all the specified flags set. */
bool has_flag_src(unsigned flags) {
return ((flagsSrc & flags) == flags);
}
void set_flag_dst(unsigned flags) {
flagsDst |= flags;
}
void clear_flag_dst(unsigned flags) {
flagsDst &= ~flags;
}
/** Returns true if src flags has all the specified flags set. */
bool has_flag_dst(unsigned flags) {
return ((flagsDst & flags) == flags);
}
typedef uint32_t id_type;
id_type id() const
{
return static_cast<uint32_t>(mti);
}
/** Returns the NMRAnet-defined priority band, in the range of 0..3. */
unsigned priority()
{
return (mti & Defs::MTI_PRIORITY_MASK) >> Defs::MTI_PRIORITY_SHIFT;
}
enum DstFlags {
/** Specifies that the stack should wait for the local loopback
* processing before invoking the done notifiable. */
WAIT_FOR_LOCAL_LOOPBACK = 1,
/** Signals to the stack that we need to set the continuation bits in
* the outgoing message to indicate that this is not the first frame of
* a message. */
DSTFLAG_NOT_FIRST_MESSAGE = 2,
/** Signals to the stack that we need to set the continuation bits in
* the outgoing message to indicate that this is not the last frame of
* a message. */
DSTFLAG_NOT_LAST_MESSAGE = 4,
// 8: free
};
enum SrcFlags {
// 1, 2, 4, 8: free
};
};
/// Interface class for all handlers that can be registered in the dispatcher
/// to receive incoming NMRAnet messages.
typedef FlowInterface<Buffer<GenMessage>> MessageHandler;
/// Abstract class representing an OpenLCB Interface. All interaction between
/// the local software stack and the physical bus has to go through this
/// class. The API that's not specific to the wire protocol appears here. The
/// implementations of this class would be specific to the wire protocol
/// (e.g. IfCan for CAN, and a not-yet-implemented class for TCP).
class If : public Service
{
public:
/** Constructs an NMRAnet interface.
* @param executor is the thread that will be used for all processing on
* this interface.
* @param local_nodes_count is the maximum number of virtual nodes that
* this interface will support. */
If(ExecutorBase *executor, int local_nodes_count);
/** Destructor */
virtual ~If()
{
}
/** @return Flow to send global messages to the NMRAnet bus. */
MessageHandler *global_message_write_flow()
{
HASSERT(globalWriteFlow_);
return globalWriteFlow_;
}
/** @return Flow to send addressed messages to the NMRAnet bus. */
MessageHandler *addressed_message_write_flow()
{
HASSERT(addressedWriteFlow_);
return addressedWriteFlow_;
}
/** Type of the dispatcher of incoming NMRAnet messages. */
typedef DispatchFlow<Buffer<GenMessage>, 4> MessageDispatchFlow;
/** @return Dispatcher of incoming NMRAnet messages. */
MessageDispatchFlow *dispatcher()
{
return &dispatcher_;
}
/** Transfers ownership of a module to the interface. It will be brought
* down in the destructor. The destruction order is guaranteed such that
* all supporting structures are still available when the flow is destryed,
* but incoming messages can not come in anymore.
*
* @todo(balazs.racz) revise whether this needs to be virtual. */
virtual void add_owned_flow(Executable *e) = 0;
/** Registers a new local node on this interface. This function must be
* called from the interface's executor.
*
* @param node is the node to register.
*/
void add_local_node(Node *node)
{
NodeID id = node->node_id();
HASSERT(localNodes_.find(id) == localNodes_.end());
localNodes_[id] = node;
}
/** Removes a local node from this interface. This function must be called
* from the interface's executor.
*
* @param node is the node to delete. The node will not be freed, just
* removed from the data structures.
*/
virtual void delete_local_node(Node *node) = 0;
/*
{
HASSERT(0);
auto it = localNodes_.find(node->node_id());
HASSERT(it != localNodes_.end());
localNodes_.erase(it);
}*/
/** Looks up a node ID in the local nodes' registry. This function must be
* called from the interface's executor.
*
* @param id is the 48-bit NMRAnet node ID to look up.
* @returns the node pointer or NULL if the node is not registered.
*/
Node *lookup_local_node(NodeID id)
{
auto it = localNodes_.find(id);
if (it == localNodes_.end())
{
return nullptr;
}
return it->second;
}
/**
* @returns the first node (by nodeID order) that is registered in this
* interface as a local node, or nullptr if this interface has no local
* nodes.
*/
Node* first_local_node() {
auto it = localNodes_.begin();
if (it == localNodes_.end()) return nullptr;
return it->second;
}
/**
* Iterator helper on the local nodes map.
*
* @param previous is the node ID of a valid local node.
*
* @returns the node pointer of the next local node (in node ID order) or
* null if this was the last node or an invalid argument (not the node ID
* of a local node).
*/
Node* next_local_node(NodeID previous) {
auto it = localNodes_.find(previous);
if (it == localNodes_.end())
{
return nullptr;
}
++it;
if (it == localNodes_.end())
{
return nullptr;
}
return it->second;
}
/** @returns true if the two node handles match as far as we can tell
* without doing any network traffic. */
virtual bool matching_node(NodeHandle expected,
NodeHandle actual) = 0;
protected:
void remove_local_node_from_map(Node *node) {
auto it = localNodes_.find(node->node_id());
HASSERT(it != localNodes_.end());
localNodes_.erase(it);
}
/// Allocator containing the global write flows.
MessageHandler *globalWriteFlow_;
/// Allocator containing the addressed write flows.
MessageHandler *addressedWriteFlow_;
private:
/// Flow responsible for routing incoming messages to handlers.
MessageDispatchFlow dispatcher_;
typedef Map<NodeID, Node *> VNodeMap;
/// Local virtual nodes registered on this interface.
VNodeMap localNodes_;
friend class VerifyNodeIdHandler;
DISALLOW_COPY_AND_ASSIGN(If);
};
/// Message handlers that are implemented as state flows should derive from
/// this class.
typedef StateFlow<Buffer<GenMessage>, QList<4>> MessageStateFlowBase;
/** Base class for incoming message handler flows. */
class IncomingMessageStateFlow
: public MessageStateFlowBase
{
public:
IncomingMessageStateFlow(If *iface)
: MessageStateFlowBase(iface)
{
}
If *iface()
{
return static_cast<If *>(service());
}
/// Returns the NMRAnet message we received.
GenMessage *nmsg()
{
return message()->data();
}
};
} // namespace openlcb
#endif // _OPENLCB_IF_HXX_
<commit_msg>Improves the performance of datagram initialization by avoiding a copy of the payload.<commit_after>/** \copyright
* Copyright (c) 2013, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
* \file If.hxx
*
* Asynchronous NMRAnet interface.
*
* @author Balazs Racz
* @date 3 Dec 2013
*/
#ifndef _OPENLCB_IF_HXX_
#define _OPENLCB_IF_HXX_
/// @todo(balazs.racz) remove this dep
#include <string>
#include "openlcb/Node.hxx"
#include "openlcb/Defs.hxx"
#include "executor/Dispatcher.hxx"
#include "executor/Service.hxx"
#include "executor/Executor.hxx"
#include "utils/Buffer.hxx"
#include "utils/Queue.hxx"
#include "utils/Map.hxx"
namespace openlcb
{
class Node;
/// Container that carries the data bytes in an NMRAnet message.
typedef string Payload;
/** Convenience function to render a 48-bit NMRAnet node ID into a new buffer.
*
* @param id is the 48-bit ID to render.
* @returns a new buffer (from the main pool) with 6 bytes of used space, a
* big-endian representation of the node ID.
*/
extern string node_id_to_buffer(NodeID id);
/** Convenience function to render a 48-bit NMRAnet node ID into an existing
* buffer.
*
* @param id is the 48-bit ID to render.
* @param data is the memory space to write the rendered ID into. There must be
* at least 6 bytes available at this address.
*/
extern void node_id_to_data(NodeID id, void* data);
/** Converts a 6-byte-long buffer to a node ID.
*
* @param buf is a buffer that has to have exactly 6 bytes used, filled with a
* big-endian node id.
* @returns the node id (in host endian).
*/
extern NodeID buffer_to_node_id(const string& buf);
/** Converts 6 bytes of big-endian data to a node ID.
*
* @param d is a pointer to at least 6 valid bytes.
* @returns the node ID represented by the first 6 bytes of d.
*/
extern NodeID data_to_node_id(const void* d);
/** Converts an Event ID to a Payload suitable to be sent as an event report. */
extern Payload eventid_to_buffer(uint64_t eventid);
/** Takes 8 bytes (big-endian) from *data, and returns the event id they
* represent. */
inline uint64_t data_to_eventid(const void* data) {
uint64_t ret = 0;
memcpy(&ret, data, 8);
return be64toh(ret);
}
/** Formats a payload for response of error response messages such as OPtioanl
* Interaction Rejected or Terminate Due To Error. */
extern string error_to_buffer(uint16_t error_code, uint16_t mti);
/** Formats a payload for response of error response messages such as Datagram
* Rejected. */
extern string error_to_buffer(uint16_t error_code);
/** Writes an error code into a payload object at a given pointer. */
extern void error_to_data(uint16_t error_code, void* data);
/** Appends an error to the end of an existing buffer. */
extern void append_error_to_buffer(uint16_t error_code, Payload* p);
/** Parses the payload of an Optional Interaction Rejected or Terminate Due To
* Error message.
* @param payload is the contents of the incoming addressed message.
* @param error_code will hold the 2-byte error code, or ERROR_PERMANENT if not
* specified
* @param mti will hold the MTI value, or 0 if not specified
* @param error_message will hold all remaining bytes that came with the error
* message.
*/
extern void buffer_to_error(const Payload& payload, uint16_t* error_code, uint16_t* mti, string* error_message);
/** A global class / variable for empty or not-yet-initialized payloads. */
extern string EMPTY_PAYLOAD;
/// @return the high 4 bytes of a node ID. @param id is the node ID.
inline unsigned node_high(NodeID id) {
return id >> 32;
}
/// @return the low 4 bytes of a node ID. @param id is the node ID.
inline unsigned node_low(NodeID id) {
return id & 0xffffffffU;
}
/// Helper function to send an event report to the bus. Performs
/// synchronous (dynamic) memory allocation so use it sparingly and when
/// there is sufficient amount of RAM available.
/// @param event_id is the event to send off.
extern void send_event(Node* src_node, uint64_t event_id);
/** This class is used in the dispatching of incoming or outgoing NMRAnet
* messages to the message handlers at the protocol-agnostic level (i.e. not
* CAN or TCP-specific).
*
* TODO(balazs.racz) There shall be one instance of this class that will be
* sent to all handlers that expressed interest in that MTI. When all those
* handlers are done, the instance should be freed. Currently the instance is
* copied by the dispatcher separately for each handler. */
struct GenMessage
{
GenMessage()
: src({0, 0}), dst({0, 0}), flagsSrc(0), flagsDst(0) {}
void reset(Defs::MTI mti, NodeID src, NodeHandle dst, string payload)
{
this->mti = mti;
this->src = {src, 0};
this->dst = dst;
this->payload = std::move(payload);
this->dstNode = nullptr;
this->flagsSrc = 0;
this->flagsDst = 0;
}
void reset(Defs::MTI mti, NodeID src, string payload)
{
this->mti = mti;
this->src = {src, 0};
this->dst = {0, 0};
this->payload = std::move(payload);
this->dstNode = nullptr;
this->flagsSrc = 0;
this->flagsDst = 0;
}
/// OpenLCB MTI of the incoming message.
Defs::MTI mti;
/// Source node.
NodeHandle src;
/// Destination node.
NodeHandle dst;
/// If the destination node is local, this value is non-NULL.
Node *dstNode;
/// Data content in the message body. Owned by the dispatcher.
/// @todo(balazs.racz) figure out a better container.
string payload;
unsigned flagsSrc : 4;
unsigned flagsDst : 4;
unsigned get_flags_src() {
return flagsSrc;
}
unsigned get_flags_dst() {
return flagsDst;
}
void set_flag_src(unsigned flags) {
flagsSrc |= flags;
}
void clear_flag_src(unsigned flags) {
flagsSrc &= ~flags;
}
/** Returns true if src flags has all the specified flags set. */
bool has_flag_src(unsigned flags) {
return ((flagsSrc & flags) == flags);
}
void set_flag_dst(unsigned flags) {
flagsDst |= flags;
}
void clear_flag_dst(unsigned flags) {
flagsDst &= ~flags;
}
/** Returns true if src flags has all the specified flags set. */
bool has_flag_dst(unsigned flags) {
return ((flagsDst & flags) == flags);
}
typedef uint32_t id_type;
id_type id() const
{
return static_cast<uint32_t>(mti);
}
/** Returns the NMRAnet-defined priority band, in the range of 0..3. */
unsigned priority()
{
return (mti & Defs::MTI_PRIORITY_MASK) >> Defs::MTI_PRIORITY_SHIFT;
}
enum DstFlags {
/** Specifies that the stack should wait for the local loopback
* processing before invoking the done notifiable. */
WAIT_FOR_LOCAL_LOOPBACK = 1,
/** Signals to the stack that we need to set the continuation bits in
* the outgoing message to indicate that this is not the first frame of
* a message. */
DSTFLAG_NOT_FIRST_MESSAGE = 2,
/** Signals to the stack that we need to set the continuation bits in
* the outgoing message to indicate that this is not the last frame of
* a message. */
DSTFLAG_NOT_LAST_MESSAGE = 4,
// 8: free
};
enum SrcFlags {
// 1, 2, 4, 8: free
};
};
/// Interface class for all handlers that can be registered in the dispatcher
/// to receive incoming NMRAnet messages.
typedef FlowInterface<Buffer<GenMessage>> MessageHandler;
/// Abstract class representing an OpenLCB Interface. All interaction between
/// the local software stack and the physical bus has to go through this
/// class. The API that's not specific to the wire protocol appears here. The
/// implementations of this class would be specific to the wire protocol
/// (e.g. IfCan for CAN, and a not-yet-implemented class for TCP).
class If : public Service
{
public:
/** Constructs an NMRAnet interface.
* @param executor is the thread that will be used for all processing on
* this interface.
* @param local_nodes_count is the maximum number of virtual nodes that
* this interface will support. */
If(ExecutorBase *executor, int local_nodes_count);
/** Destructor */
virtual ~If()
{
}
/** @return Flow to send global messages to the NMRAnet bus. */
MessageHandler *global_message_write_flow()
{
HASSERT(globalWriteFlow_);
return globalWriteFlow_;
}
/** @return Flow to send addressed messages to the NMRAnet bus. */
MessageHandler *addressed_message_write_flow()
{
HASSERT(addressedWriteFlow_);
return addressedWriteFlow_;
}
/** Type of the dispatcher of incoming NMRAnet messages. */
typedef DispatchFlow<Buffer<GenMessage>, 4> MessageDispatchFlow;
/** @return Dispatcher of incoming NMRAnet messages. */
MessageDispatchFlow *dispatcher()
{
return &dispatcher_;
}
/** Transfers ownership of a module to the interface. It will be brought
* down in the destructor. The destruction order is guaranteed such that
* all supporting structures are still available when the flow is destryed,
* but incoming messages can not come in anymore.
*
* @todo(balazs.racz) revise whether this needs to be virtual. */
virtual void add_owned_flow(Executable *e) = 0;
/** Registers a new local node on this interface. This function must be
* called from the interface's executor.
*
* @param node is the node to register.
*/
void add_local_node(Node *node)
{
NodeID id = node->node_id();
HASSERT(localNodes_.find(id) == localNodes_.end());
localNodes_[id] = node;
}
/** Removes a local node from this interface. This function must be called
* from the interface's executor.
*
* @param node is the node to delete. The node will not be freed, just
* removed from the data structures.
*/
virtual void delete_local_node(Node *node) = 0;
/*
{
HASSERT(0);
auto it = localNodes_.find(node->node_id());
HASSERT(it != localNodes_.end());
localNodes_.erase(it);
}*/
/** Looks up a node ID in the local nodes' registry. This function must be
* called from the interface's executor.
*
* @param id is the 48-bit NMRAnet node ID to look up.
* @returns the node pointer or NULL if the node is not registered.
*/
Node *lookup_local_node(NodeID id)
{
auto it = localNodes_.find(id);
if (it == localNodes_.end())
{
return nullptr;
}
return it->second;
}
/**
* @returns the first node (by nodeID order) that is registered in this
* interface as a local node, or nullptr if this interface has no local
* nodes.
*/
Node* first_local_node() {
auto it = localNodes_.begin();
if (it == localNodes_.end()) return nullptr;
return it->second;
}
/**
* Iterator helper on the local nodes map.
*
* @param previous is the node ID of a valid local node.
*
* @returns the node pointer of the next local node (in node ID order) or
* null if this was the last node or an invalid argument (not the node ID
* of a local node).
*/
Node* next_local_node(NodeID previous) {
auto it = localNodes_.find(previous);
if (it == localNodes_.end())
{
return nullptr;
}
++it;
if (it == localNodes_.end())
{
return nullptr;
}
return it->second;
}
/** @returns true if the two node handles match as far as we can tell
* without doing any network traffic. */
virtual bool matching_node(NodeHandle expected,
NodeHandle actual) = 0;
protected:
void remove_local_node_from_map(Node *node) {
auto it = localNodes_.find(node->node_id());
HASSERT(it != localNodes_.end());
localNodes_.erase(it);
}
/// Allocator containing the global write flows.
MessageHandler *globalWriteFlow_;
/// Allocator containing the addressed write flows.
MessageHandler *addressedWriteFlow_;
private:
/// Flow responsible for routing incoming messages to handlers.
MessageDispatchFlow dispatcher_;
typedef Map<NodeID, Node *> VNodeMap;
/// Local virtual nodes registered on this interface.
VNodeMap localNodes_;
friend class VerifyNodeIdHandler;
DISALLOW_COPY_AND_ASSIGN(If);
};
/// Message handlers that are implemented as state flows should derive from
/// this class.
typedef StateFlow<Buffer<GenMessage>, QList<4>> MessageStateFlowBase;
/** Base class for incoming message handler flows. */
class IncomingMessageStateFlow
: public MessageStateFlowBase
{
public:
IncomingMessageStateFlow(If *iface)
: MessageStateFlowBase(iface)
{
}
If *iface()
{
return static_cast<If *>(service());
}
/// Returns the NMRAnet message we received.
GenMessage *nmsg()
{
return message()->data();
}
};
} // namespace openlcb
#endif // _OPENLCB_IF_HXX_
<|endoftext|> |
<commit_before>#include <disir/cli/command.h>
#include <disir/cli/cli.h>
#include <iostream>
using namespace disir;
Command::Command (std::string name)
: m_name (name)
{
}
void
Command::setup_parser (args::ArgumentParser& parser)
{
parser.helpParams.progindent = 0;
parser.helpParams.progtailindent = 2;
parser.helpParams.descriptionindent = 2;
parser.helpParams.flagindent = 2;
parser.helpParams.eachgroupindent = 0;
parser.helpParams.helpindent = 28;
parser.helpParams.showTerminator = false;
}
int
Command::list_configs (std::set<std::string>& list)
{
enum disir_status status;
struct disir_entry *config_entries;
struct disir_entry *next;
struct disir_entry *current;
status = disir_config_entries (m_cli->disir(), m_cli->group_id().c_str(), &config_entries);
if (status != DISIR_STATUS_OK)
{
std::cerr << "error querying available configs: "
<< disir_error (m_cli->disir()) << std::endl;
return (-1);
}
current = config_entries;
while (current != NULL)
{
next = current->next;
list.insert (std::string(current->de_entry_name));
disir_entry_finished (¤t);
current = next;
}
return (0);
}
int
Command::setup_group (std::string id)
{
int code;
std::list<std::string> groups;
m_cli->list_groups (groups);
if (std::find (groups.begin(), groups.end(), id) == groups.end())
{
// invalid entry
std::cerr << "error: invalid group selected - " << id << std::endl;
std::cerr << "Select one of the following:" << std::endl;
for (auto& g : groups)
{
std::cerr << " " << g << std::endl;
}
code = 1;
}
else
{
m_cli->group_id (id);
m_cli->verbose() << "Setting user-provided group id to: "
<< m_cli->group_id() << std::endl;
code = 0;
}
return (code);
}
void
Command::print_verify (enum disir_status status, const char *entry,
struct disir_config *config,
struct disir_mold *mold)
{
struct disir_collection *collection = NULL;
struct disir_context *context = NULL;
char *resolved_name = NULL;
if (status == DISIR_STATUS_OK)
{
std::cout << " OK: " << entry << std::endl;
}
else if (status == DISIR_STATUS_INVALID_CONTEXT)
{
std::cout << " INVALID: " << entry << std::endl;
if (config)
status = disir_config_valid (config, &collection);
else if (mold)
status = disir_mold_valid (mold, &collection);
if (collection)
{
do
{
status = dc_collection_next (collection, &context);
if (status == DISIR_STATUS_EXHAUSTED)
break;
if (status != DISIR_STATUS_OK)
{
std::cerr << "failed to retrieve collection item: "
<< disir_status_string (status) << std::endl;
break;
}
status = dc_resolve_root_name (context, &resolved_name);
const char *name;
if (status != DISIR_STATUS_OK)
{
name = "UNRESOLVED";
}
else
{
name = resolved_name;
}
if (dc_context_error (context))
{
std::cout << " " << name << ": "
<< dc_context_error (context) << std::endl;
}
else if (dc_context_type (context) == DISIR_CONTEXT_KEYVAL)
{
std::cout << " " << name << ": "
<< "(entry missing error)" << std::endl;
}
if (resolved_name != NULL)
{
free (resolved_name);
}
dc_putcontext (&context);
} while (1);
if (context)
{
dc_putcontext (&context);
}
if (collection)
{
dc_collection_finished (&collection);
}
}
}
else
{
std::cout << " ERROR: " << entry << std::endl;
std::cout << " " << disir_status_string (status) << std::endl;
if (disir_error (m_cli->disir()) != NULL)
{
std::cout << " " << disir_error (m_cli->disir()) << std::endl;
}
else
{
std::cout << " (no error registered)" << std::endl;
}
}
}
<commit_msg>fix cli: removed unneccesary status assignment<commit_after>#include <disir/cli/command.h>
#include <disir/cli/cli.h>
#include <iostream>
using namespace disir;
Command::Command (std::string name)
: m_name (name)
{
}
void
Command::setup_parser (args::ArgumentParser& parser)
{
parser.helpParams.progindent = 0;
parser.helpParams.progtailindent = 2;
parser.helpParams.descriptionindent = 2;
parser.helpParams.flagindent = 2;
parser.helpParams.eachgroupindent = 0;
parser.helpParams.helpindent = 28;
parser.helpParams.showTerminator = false;
}
int
Command::list_configs (std::set<std::string>& list)
{
enum disir_status status;
struct disir_entry *config_entries;
struct disir_entry *next;
struct disir_entry *current;
status = disir_config_entries (m_cli->disir(), m_cli->group_id().c_str(), &config_entries);
if (status != DISIR_STATUS_OK)
{
std::cerr << "error querying available configs: "
<< disir_error (m_cli->disir()) << std::endl;
return (-1);
}
current = config_entries;
while (current != NULL)
{
next = current->next;
list.insert (std::string(current->de_entry_name));
disir_entry_finished (¤t);
current = next;
}
return (0);
}
int
Command::setup_group (std::string id)
{
int code;
std::list<std::string> groups;
m_cli->list_groups (groups);
if (std::find (groups.begin(), groups.end(), id) == groups.end())
{
// invalid entry
std::cerr << "error: invalid group selected - " << id << std::endl;
std::cerr << "Select one of the following:" << std::endl;
for (auto& g : groups)
{
std::cerr << " " << g << std::endl;
}
code = 1;
}
else
{
m_cli->group_id (id);
m_cli->verbose() << "Setting user-provided group id to: "
<< m_cli->group_id() << std::endl;
code = 0;
}
return (code);
}
void
Command::print_verify (enum disir_status status, const char *entry,
struct disir_config *config,
struct disir_mold *mold)
{
struct disir_collection *collection = NULL;
struct disir_context *context = NULL;
char *resolved_name = NULL;
if (status == DISIR_STATUS_OK)
{
std::cout << " OK: " << entry << std::endl;
}
else if (status == DISIR_STATUS_INVALID_CONTEXT)
{
std::cout << " INVALID: " << entry << std::endl;
if (config)
disir_config_valid (config, &collection);
else if (mold)
disir_mold_valid (mold, &collection);
if (collection)
{
do
{
status = dc_collection_next (collection, &context);
if (status == DISIR_STATUS_EXHAUSTED)
break;
if (status != DISIR_STATUS_OK)
{
std::cerr << "failed to retrieve collection item: "
<< disir_status_string (status) << std::endl;
break;
}
status = dc_resolve_root_name (context, &resolved_name);
const char *name;
if (status != DISIR_STATUS_OK)
{
name = "UNRESOLVED";
}
else
{
name = resolved_name;
}
if (dc_context_error (context))
{
std::cout << " " << name << ": "
<< dc_context_error (context) << std::endl;
}
else if (dc_context_type (context) == DISIR_CONTEXT_KEYVAL)
{
std::cout << " " << name << ": "
<< "(entry missing error)" << std::endl;
}
if (resolved_name != NULL)
{
free (resolved_name);
}
dc_putcontext (&context);
} while (1);
if (context)
{
dc_putcontext (&context);
}
if (collection)
{
dc_collection_finished (&collection);
}
}
}
else
{
std::cout << " ERROR: " << entry << std::endl;
std::cout << " " << disir_status_string (status) << std::endl;
if (disir_error (m_cli->disir()) != NULL)
{
std::cout << " " << disir_error (m_cli->disir()) << std::endl;
}
else
{
std::cout << " (no error registered)" << std::endl;
}
}
}
<|endoftext|> |
<commit_before>/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2004-2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "avmplus.h"
#ifdef AVMPLUS_MIR
#include "../codegen/CodegenMIR.h"
#endif
#ifdef FEATURE_NANOJIT
#include "../codegen/CodegenLIR.h"
#endif
#ifdef PERFM
#include "../vprof/vprof.h"
#endif /* PERFM */
namespace avmplus
{
using namespace MMgc;
MethodInfo::MethodInfo()
: AbstractFunction()
{
#ifdef DEBUGGER
this->local_count = 0;
this->max_scopes = 0;
this->localNames = 0;
this->firstSourceLine = 0;
this->lastSourceLine = 0;
this->offsetInAbc = 0;
#endif
this->impl32 = verifyEnter;
}
void MethodInfo::setInterpImpl() {
if (returnTraits() == core()->traits.number_itraits)
implN = avmplus::interpN;
else
impl32 = avmplus::interp32;
}
Atom MethodInfo::verifyEnter(MethodEnv* env, int argc, uint32 *ap)
{
MethodInfo* f = (MethodInfo*) env->method;
f->verify(env->vtable->toplevel);
#if 0 // This is handled near the top of interp() for the moment, see comments there
#ifdef AVMPLUS_WORD_CODE
{
int n;
if ((int32)(n = f->word_code.cache_size) > 0) {
AvmAssert(env->lookup_cache == NULL);
env->lookup_cache = (MethodEnv::LookupCache*)env->core()->GetGC()->Alloc(sizeof(MethodEnv::LookupCache)*n, GC::kContainsPointers|GC::kZero);
}
}
#endif
#endif // 0
#ifdef AVMPLUS_VERIFYALL
f->flags |= VERIFIED;
f->core()->processVerifyQueue(env->toplevel());
#endif
AvmAssert(f->impl32 != MethodInfo::verifyEnter);
env->impl32 = f->impl32;
return f->impl32(env, argc, ap);
}
void MethodInfo::verify(Toplevel* toplevel)
{
AvmAssert(declaringTraits->linked);
resolveSignature(toplevel);
#ifdef DEBUGGER
CallStackNode callStackNode(NULL, this, NULL, NULL, 0, NULL, NULL);
#endif /* DEBUGGER */
if (!body_pos)
{
// no body was supplied in abc
toplevel->throwVerifyError(kNotImplementedError, toplevel->core()->toErrorString(this));
}
#if defined AVMPLUS_MIR || defined FEATURE_NANOJIT
Verifier verifier(this, toplevel);
AvmCore* core = this->core();
if ((core->IsMIREnabled()) && !isFlagSet(AbstractFunction::SUGGEST_INTERP))
{
PERFM_NTPROF("verify & IR gen");
#if defined AVMPLUS_MIR
CodegenMIR jit(this);
#elif defined FEATURE_NANOJIT
CodegenLIR jit(this);
#endif
TRY(core, kCatchAction_Rethrow)
{
verifier.verify(&jit); // pass 2 - data flow
PERFM_TPROF_END();
if (!jit.overflow)
jit.emitMD(); // pass 3 - generate code
// the MD buffer can overflow so we need to re-iterate
// over the whole thing, since we aren't yet robust enough
// to just rebuild the MD code.
// mark it as interpreted and try to limp along
if (jit.overflow)
setInterpImpl();
}
CATCH (Exception *exception)
{
#ifdef AVMPLUS_MIR
jit.clearMIRBuffers();
#endif
// re-throw exception
core->throwException(exception);
}
END_CATCH
END_TRY
}
else
{
verifier.verify(NULL); // pass2 dataflow
setInterpImpl();
}
#else
Verifier verifier(this, toplevel);
verifier.verify();
#endif
#ifdef DEBUGGER
callStackNode.exit();
#endif /* DEBUGGER */
}
#ifdef DEBUGGER
// reg names
Stringp MethodInfo::getLocalName(int index) const { return getRegName(index+param_count); }
Stringp MethodInfo::getArgName(int index) const { return getRegName(index); }
Stringp MethodInfo::getRegName(int slot) const
{
AvmAssert(slot >= 0 && slot < local_count);
Stringp name;
if (localNames)
name = localNames[slot];
else
name = core()->kundefined;
return name;
}
void MethodInfo::setRegName(int slot, Stringp name)
{
//AvmAssert(slot >= 0 && slot < local_count);
// @todo fix me. This is a patch for bug #112405
if (slot >= local_count)
return;
if (!localNames)
initLocalNames();
AvmCore* core = this->core();
// [mmorearty 5/3/05] temporary workaround for bug 123237: if the register
// already has a name, don't assign a new one
if (getRegName(slot) != core->kundefined)
return;
//localNames[slot] = core->internString(name);
WBRC(core->GetGC(), localNames, &localNames[slot], core->internString(name));
}
void MethodInfo::initLocalNames()
{
AvmCore* core = this->core();
localNames = (Stringp*) core->GetGC()->Calloc(local_count, sizeof(Stringp), GC::kZero|GC::kContainsPointers);
for(int i=0; i<local_count; i++)
{
//localNames[i] = core->kundefined;
WBRC(core->GetGC(), localNames, &localNames[i], uintptr(Stringp(core->kundefined)));
}
}
/**
* convert ap[start]...ap[start+count-1] entries from their native types into
* Atoms. The result is placed into out[to]...out[to+count-1].
*
* The traitArr is used to determine the type of conversion that should take place.
* traitArr[start]...traitArr[start+count-1] are used.
*
* If the method is interpreted then we just copy the Atom, no conversion is needed.
*/
void MethodInfo::boxLocals(void* src, int srcPos, Traits** traitArr, Atom* dest, int destPos, int length)
{
int size = srcPos+length;
int at = destPos;
// if we are running jit then the types are native and we
// need to box em.
if (isFlagSet(TURBO))
{
// each entry is a pointer into the function's stack frame
void **in = (void**)src; // WARNING this must match with MIR generator
// now probe each type and do the atom conversion.
AvmCore* core = this->core();
for (int i=srcPos; i<size; i++)
{
Traits* t = traitArr[i];
void *p = in[i];
if (t == NUMBER_TYPE)
{
dest[at] = core->doubleToAtom( *((double*)p) );
}
else if (t == INT_TYPE)
{
dest[at] = core->intToAtom( *((int*)p) );
}
else if (t == UINT_TYPE)
{
dest[at] = core->uintToAtom( *((uint32*)p) );
}
else if (t == BOOLEAN_TYPE)
{
dest[at] = *((int*)p) ? trueAtom : falseAtom;
}
else if (!t || t == OBJECT_TYPE || t == VOID_TYPE)
{
dest[at] = *((Atom*)p);
}
else
{
// it's a pointer type, either null or some specific atom tag.
void* ptr = *((void**)p); // unknown pointer
if (t == STRING_TYPE)
{
dest[at] = ((Stringp)ptr)->atom();
}
else if (t == NAMESPACE_TYPE)
{
dest[at] = ((Namespace*)ptr)->atom();
}
else
{
dest[at] = ((ScriptObject*)ptr)->atom();
}
}
at++;
}
}
else
{
// no MIR then we know they are Atoms and we just copy them
Atom* in = (Atom*)src;
for(int i=srcPos; i<size; i++)
dest[at++] = in[i];
}
}
/**
* convert in[0]...in[count-1] entries from Atoms to native types placing them
* in ap[start]...out[start+count-1].
*
* The traitArr is used to determine the type of conversion that should take place.
* traitArr[start]...traitArr[start+count-1] are used.
*
* If the method is interpreted then we just copy the Atom, no conversion is needed.
*/
void MethodInfo::unboxLocals(Atom* src, int srcPos, Traits** traitArr, void* dest, int destPos, int length)
{
#ifdef AVMPLUS_64BIT
AvmDebugMsg (true, "are these ops right for 64-bit? alignment of int/uint/bool?\n");
#endif
int size = destPos+length;
int at = srcPos;
// If the method has been jit'd then we need to box em, otherwise just
// copy them
if (isFlagSet(TURBO))
{
// we allocated double sized entry for each local src CodegenMIR
void** out = (void**)dest; // WARNING this must match with MIR generator
// now probe each type and conversion.
AvmCore* core = this->core();
for (int i=destPos; i<size; i++)
{
Traits* t = traitArr[i];
void *p = out[i];
if (t == NUMBER_TYPE)
{
*((double*)p) = AvmCore::number_d(src[at++]);
}
else if (t == INT_TYPE)
{
*((int*)p) = AvmCore::integer_i(src[at++]);
}
else if (t == UINT_TYPE)
{
*((uint32*)p) = AvmCore::integer_u(src[at++]);
}
else if (t == BOOLEAN_TYPE)
{
*((int*)p) = (int)(src[at++]>>3);
}
else if (!t || t == OBJECT_TYPE || t == VOID_TYPE)
{
*((Atom*)p) = src[at++];
}
else
{
// ScriptObject, String, Namespace, or Null
*((sintptr*)p) = (src[at++] & ~7);
}
}
}
else
{
// no MIR then we know they are Atoms and we just copy them
Atom* out = (Atom*)dest;
for(int i=destPos; i<size; i++)
out[i] = src[at++];
}
}
uint32 MethodInfo::size() const
{
uint32 size = AbstractFunction::size();
size += (sizeof(MethodInfo) - sizeof(AbstractFunction));
size += codeSize;
return size;
}
#endif //DEBUGGER
}
<commit_msg>add missing setInterpImpl<commit_after>/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2004-2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "avmplus.h"
#ifdef AVMPLUS_MIR
#include "../codegen/CodegenMIR.h"
#endif
#ifdef FEATURE_NANOJIT
#include "../codegen/CodegenLIR.h"
#endif
#ifdef PERFM
#include "../vprof/vprof.h"
#endif /* PERFM */
namespace avmplus
{
using namespace MMgc;
MethodInfo::MethodInfo()
: AbstractFunction()
{
#ifdef DEBUGGER
this->local_count = 0;
this->max_scopes = 0;
this->localNames = 0;
this->firstSourceLine = 0;
this->lastSourceLine = 0;
this->offsetInAbc = 0;
#endif
this->impl32 = verifyEnter;
}
void MethodInfo::setInterpImpl() {
if (returnTraits() == core()->traits.number_itraits)
implN = avmplus::interpN;
else
impl32 = avmplus::interp32;
}
Atom MethodInfo::verifyEnter(MethodEnv* env, int argc, uint32 *ap)
{
MethodInfo* f = (MethodInfo*) env->method;
f->verify(env->vtable->toplevel);
#if 0 // This is handled near the top of interp() for the moment, see comments there
#ifdef AVMPLUS_WORD_CODE
{
int n;
if ((int32)(n = f->word_code.cache_size) > 0) {
AvmAssert(env->lookup_cache == NULL);
env->lookup_cache = (MethodEnv::LookupCache*)env->core()->GetGC()->Alloc(sizeof(MethodEnv::LookupCache)*n, GC::kContainsPointers|GC::kZero);
}
}
#endif
#endif // 0
#ifdef AVMPLUS_VERIFYALL
f->flags |= VERIFIED;
f->core()->processVerifyQueue(env->toplevel());
#endif
AvmAssert(f->impl32 != MethodInfo::verifyEnter);
env->impl32 = f->impl32;
return f->impl32(env, argc, ap);
}
void MethodInfo::verify(Toplevel* toplevel)
{
AvmAssert(declaringTraits->linked);
resolveSignature(toplevel);
#ifdef DEBUGGER
CallStackNode callStackNode(NULL, this, NULL, NULL, 0, NULL, NULL);
#endif /* DEBUGGER */
if (!body_pos)
{
// no body was supplied in abc
toplevel->throwVerifyError(kNotImplementedError, toplevel->core()->toErrorString(this));
}
#if defined AVMPLUS_MIR || defined FEATURE_NANOJIT
Verifier verifier(this, toplevel);
AvmCore* core = this->core();
if ((core->IsMIREnabled()) && !isFlagSet(AbstractFunction::SUGGEST_INTERP))
{
PERFM_NTPROF("verify & IR gen");
#if defined AVMPLUS_MIR
CodegenMIR jit(this);
#elif defined FEATURE_NANOJIT
CodegenLIR jit(this);
#endif
TRY(core, kCatchAction_Rethrow)
{
verifier.verify(&jit); // pass 2 - data flow
PERFM_TPROF_END();
if (!jit.overflow)
jit.emitMD(); // pass 3 - generate code
// the MD buffer can overflow so we need to re-iterate
// over the whole thing, since we aren't yet robust enough
// to just rebuild the MD code.
// mark it as interpreted and try to limp along
if (jit.overflow)
setInterpImpl();
}
CATCH (Exception *exception)
{
#ifdef AVMPLUS_MIR
jit.clearMIRBuffers();
#endif
// re-throw exception
core->throwException(exception);
}
END_CATCH
END_TRY
}
else
{
verifier.verify(NULL); // pass2 dataflow
setInterpImpl();
}
#else
Verifier verifier(this, toplevel);
verifier.verify();
setInterpImpl();
#endif
#ifdef DEBUGGER
callStackNode.exit();
#endif /* DEBUGGER */
}
#ifdef DEBUGGER
// reg names
Stringp MethodInfo::getLocalName(int index) const { return getRegName(index+param_count); }
Stringp MethodInfo::getArgName(int index) const { return getRegName(index); }
Stringp MethodInfo::getRegName(int slot) const
{
AvmAssert(slot >= 0 && slot < local_count);
Stringp name;
if (localNames)
name = localNames[slot];
else
name = core()->kundefined;
return name;
}
void MethodInfo::setRegName(int slot, Stringp name)
{
//AvmAssert(slot >= 0 && slot < local_count);
// @todo fix me. This is a patch for bug #112405
if (slot >= local_count)
return;
if (!localNames)
initLocalNames();
AvmCore* core = this->core();
// [mmorearty 5/3/05] temporary workaround for bug 123237: if the register
// already has a name, don't assign a new one
if (getRegName(slot) != core->kundefined)
return;
//localNames[slot] = core->internString(name);
WBRC(core->GetGC(), localNames, &localNames[slot], core->internString(name));
}
void MethodInfo::initLocalNames()
{
AvmCore* core = this->core();
localNames = (Stringp*) core->GetGC()->Calloc(local_count, sizeof(Stringp), GC::kZero|GC::kContainsPointers);
for(int i=0; i<local_count; i++)
{
//localNames[i] = core->kundefined;
WBRC(core->GetGC(), localNames, &localNames[i], uintptr(Stringp(core->kundefined)));
}
}
/**
* convert ap[start]...ap[start+count-1] entries from their native types into
* Atoms. The result is placed into out[to]...out[to+count-1].
*
* The traitArr is used to determine the type of conversion that should take place.
* traitArr[start]...traitArr[start+count-1] are used.
*
* If the method is interpreted then we just copy the Atom, no conversion is needed.
*/
void MethodInfo::boxLocals(void* src, int srcPos, Traits** traitArr, Atom* dest, int destPos, int length)
{
int size = srcPos+length;
int at = destPos;
// if we are running jit then the types are native and we
// need to box em.
if (isFlagSet(TURBO))
{
// each entry is a pointer into the function's stack frame
void **in = (void**)src; // WARNING this must match with MIR generator
// now probe each type and do the atom conversion.
AvmCore* core = this->core();
for (int i=srcPos; i<size; i++)
{
Traits* t = traitArr[i];
void *p = in[i];
if (t == NUMBER_TYPE)
{
dest[at] = core->doubleToAtom( *((double*)p) );
}
else if (t == INT_TYPE)
{
dest[at] = core->intToAtom( *((int*)p) );
}
else if (t == UINT_TYPE)
{
dest[at] = core->uintToAtom( *((uint32*)p) );
}
else if (t == BOOLEAN_TYPE)
{
dest[at] = *((int*)p) ? trueAtom : falseAtom;
}
else if (!t || t == OBJECT_TYPE || t == VOID_TYPE)
{
dest[at] = *((Atom*)p);
}
else
{
// it's a pointer type, either null or some specific atom tag.
void* ptr = *((void**)p); // unknown pointer
if (t == STRING_TYPE)
{
dest[at] = ((Stringp)ptr)->atom();
}
else if (t == NAMESPACE_TYPE)
{
dest[at] = ((Namespace*)ptr)->atom();
}
else
{
dest[at] = ((ScriptObject*)ptr)->atom();
}
}
at++;
}
}
else
{
// no MIR then we know they are Atoms and we just copy them
Atom* in = (Atom*)src;
for(int i=srcPos; i<size; i++)
dest[at++] = in[i];
}
}
/**
* convert in[0]...in[count-1] entries from Atoms to native types placing them
* in ap[start]...out[start+count-1].
*
* The traitArr is used to determine the type of conversion that should take place.
* traitArr[start]...traitArr[start+count-1] are used.
*
* If the method is interpreted then we just copy the Atom, no conversion is needed.
*/
void MethodInfo::unboxLocals(Atom* src, int srcPos, Traits** traitArr, void* dest, int destPos, int length)
{
#ifdef AVMPLUS_64BIT
AvmDebugMsg (true, "are these ops right for 64-bit? alignment of int/uint/bool?\n");
#endif
int size = destPos+length;
int at = srcPos;
// If the method has been jit'd then we need to box em, otherwise just
// copy them
if (isFlagSet(TURBO))
{
// we allocated double sized entry for each local src CodegenMIR
void** out = (void**)dest; // WARNING this must match with MIR generator
// now probe each type and conversion.
AvmCore* core = this->core();
for (int i=destPos; i<size; i++)
{
Traits* t = traitArr[i];
void *p = out[i];
if (t == NUMBER_TYPE)
{
*((double*)p) = AvmCore::number_d(src[at++]);
}
else if (t == INT_TYPE)
{
*((int*)p) = AvmCore::integer_i(src[at++]);
}
else if (t == UINT_TYPE)
{
*((uint32*)p) = AvmCore::integer_u(src[at++]);
}
else if (t == BOOLEAN_TYPE)
{
*((int*)p) = (int)(src[at++]>>3);
}
else if (!t || t == OBJECT_TYPE || t == VOID_TYPE)
{
*((Atom*)p) = src[at++];
}
else
{
// ScriptObject, String, Namespace, or Null
*((sintptr*)p) = (src[at++] & ~7);
}
}
}
else
{
// no MIR then we know they are Atoms and we just copy them
Atom* out = (Atom*)dest;
for(int i=destPos; i<size; i++)
out[i] = src[at++];
}
}
uint32 MethodInfo::size() const
{
uint32 size = AbstractFunction::size();
size += (sizeof(MethodInfo) - sizeof(AbstractFunction));
size += codeSize;
return size;
}
#endif //DEBUGGER
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <factory_motion_segmenter.h>
#include <unordered_map>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <config_loader.h>
#include <rgbd_loader.h>
#include <common/constants.h>
using namespace std;
typedef std::unordered_map<int, std::string> classMap;
void mergeMask(cv::Mat &img, cv::Mat mask)
{
img.convertTo(img, CV_8UC1);
cv::cvtColor(img, img, cv::COLOR_BGR2GRAY);
bitwise_and(img, mask, img);
}
int main(int argc, char **argv)
{
if (argc != 2)
{
cout << "usage: ./test_motion_image_segmentation <yml_config_filepath>" << endl;
return 1;
}
// load parameters
ConfigLoader param_loader(argv[1]);
bool is_video;
param_loader.checkAndGetBool("is_video", is_video);
bool resize_src;
param_loader.checkAndGetBool("resize_src", resize_src);
string src_path;
param_loader.checkAndGetString("src_path", src_path);
// create image segmentor
auto segmenter = FactoryMotionSegmenter::create<DNNMotionSegmenter>(Constants::mask_rcnn_model_path,
Constants::mask_rcnn_pbtxt_path, classMap({{0, "person"}, {2, "car"}}));
segmenter->setThreshold(0.3);
if (is_video)
{
cv::VideoCapture cap(src_path);
if (!cap.isOpened())
{
cerr << "invalid video file " << src_path << endl;
exit(-1);
}
cv::Mat frame;
while (cap.isOpened())
{
cv::Mat mask;
cap >> frame;
if (resize_src)
{
cv::resize(frame, frame, cv::Size(320, 240));
}
// segment the image
segmenter->segment(frame, mask);
cv::imshow("original img", frame);
cv::imshow("mask", mask);
mergeMask(frame, mask);
cv::imshow("masked img", frame);
char k = cv::waitKey(1);
if (k == 27)
{
break;
}
}
return 0;
}
else
{
param_loader.checkAndGetString("src_path", src_path);
cv::Mat in_img = cv::imread(src_path);
if (resize_src)
{
cv::resize(in_img, in_img, cv::Size(300, 300));
}
if (in_img.empty())
{
cerr << "invalid img file " << src_path << endl;
exit(-1);
}
cv::Mat mask;
// segment the image
segmenter->segment(in_img, mask);
cv::imshow("original img", in_img);
cv::imshow("mask", mask);
mergeMask(in_img, mask);
cv::imshow("masked img", in_img);
cv::waitKey(1);
}
return 0;
}<commit_msg>Delete file dynamic_image_dnn_segmentation.cpp<commit_after><|endoftext|> |
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2005 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <osg/Switch>
#include <osg/BoundingBox>
#include <osg/Transform>
#include <osg/Notify>
#include <algorithm>
using namespace osg;
Switch::Switch():
_newChildDefaultValue(true)
{
}
Switch::Switch(const Switch& sw,const CopyOp& copyop):
Group(sw,copyop),
_newChildDefaultValue(sw._newChildDefaultValue),
_values(sw._values)
{
}
void Switch::traverse(NodeVisitor& nv)
{
if (nv.getTraversalMode()==NodeVisitor::TRAVERSE_ACTIVE_CHILDREN)
{
for(unsigned int pos=0;pos<_children.size();++pos)
{
if (_values[pos]) _children[pos]->accept(nv);
}
}
else
{
Group::traverse(nv);
}
}
bool Switch::addChild( Node *child )
{
if (Group::addChild(child))
{
if (_children.size()>_values.size())
{
_values.resize(_children.size(),_newChildDefaultValue);
}
// note, we don't override any pre-existing _values[childPosition] setting
// like in addChild(child,value) below.
return true;
}
return false;
}
bool Switch::addChild( Node *child, bool value )
{
unsigned int childPosition = _children.size();
if (Group::addChild(child))
{
if (_children.size()>_values.size())
{
_values.resize(_children.size(),_newChildDefaultValue);
}
_values[childPosition]=value;
return true;
}
return false;
}
bool Switch::insertChild( unsigned int index, Node *child )
{
return insertChild(index,child,_newChildDefaultValue);
}
bool Switch::insertChild( unsigned int index, Node *child, bool value )
{
if (Group::insertChild(index,child))
{
if (index>=_values.size())
{
_values.push_back(value);
}
else
{
_values.insert(_values.begin()+index, value);
}
return true;
}
return false;
}
bool Switch::removeChild( Node *child )
{
removeChild( getChildIndex(child) );
}
bool Switch::removeChild(unsigned int pos,unsigned int numChildrenToRemove)
{
if (pos>=_values.size() || numChildrenToRemove==0) return false;
unsigned int endOfRemoveRange = pos+numChildrenToRemove;
if (endOfRemoveRange>_values.size())
{
notify(DEBUG_INFO)<<"Warning: Switch::removeChild(i,numChildrenToRemove) has been passed an excessive number"<<std::endl;
notify(DEBUG_INFO)<<" of chilren to remove, trimming just to end of value list."<<std::endl;
endOfRemoveRange=_values.size();
}
_values.erase(_values.begin()+pos,_values.begin()+endOfRemoveRange);
return Group::removeChild(pos, numChildrenToRemove);
}
void Switch::setValue(unsigned int pos,bool value)
{
if (pos>=_values.size()) _values.resize(pos+1,_newChildDefaultValue);
_values[pos]=value;
dirtyBound();
}
void Switch::setChildValue(const Node* child,bool value)
{
// find the child's position.
unsigned int pos=getChildIndex(child);
if (pos==_children.size()) return;
_values[pos]=value;
dirtyBound();
}
bool Switch::getValue(unsigned int pos) const
{
if (pos>=_values.size()) return false;
return _values[pos];
}
bool Switch::getChildValue(const Node* child) const
{
// find the child's position.
unsigned int pos=getChildIndex(child);
if (pos==_children.size()) return false;
return _values[pos];
}
bool Switch::setAllChildrenOff()
{
_newChildDefaultValue = false;
for(ValueList::iterator itr=_values.begin();
itr!=_values.end();
++itr)
{
*itr = false;
}
dirtyBound();
return true;
}
bool Switch::setAllChildrenOn()
{
_newChildDefaultValue = true;
for(ValueList::iterator itr=_values.begin();
itr!=_values.end();
++itr)
{
*itr = true;
}
dirtyBound();
return true;
}
bool Switch::setSingleChildOn(unsigned int pos)
{
for(ValueList::iterator itr=_values.begin();
itr!=_values.end();
++itr)
{
*itr = false;
}
setValue(pos,true);
return true;
}
BoundingSphere Switch::computeBound() const
{
BoundingSphere bsphere;
if (_children.empty())
{
return bsphere;
}
// note, special handling of the case when a child is an Transform,
// such that only Transforms which are relative to their parents coordinates frame (i.e this group)
// are handled, Transform relative to and absolute reference frame are ignored.
BoundingBox bb;
bb.init();
NodeList::const_iterator itr;
for(itr=_children.begin();
itr!=_children.end();
++itr)
{
const osg::Transform* transform = (*itr)->asTransform();
if (!transform || transform->getReferenceFrame()==osg::Transform::RELATIVE_RF)
{
if( getChildValue((*itr).get()) == true )
bb.expandBy((*itr)->getBound());
}
}
if (!bb.valid())
{
return bsphere;
}
bsphere._center = bb.center();
bsphere._radius = 0.0f;
for(itr=_children.begin();
itr!=_children.end();
++itr)
{
const osg::Transform* transform = (*itr)->asTransform();
if (!transform || transform->getReferenceFrame()==osg::Transform::RELATIVE_RF)
{
if( getChildValue((*itr).get()) == true )
bsphere.expandRadiusBy((*itr)->getBound());
}
}
return bsphere;
}
<commit_msg>From Farshid Lashkari, compile fix<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2005 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <osg/Switch>
#include <osg/BoundingBox>
#include <osg/Transform>
#include <osg/Notify>
#include <algorithm>
using namespace osg;
Switch::Switch():
_newChildDefaultValue(true)
{
}
Switch::Switch(const Switch& sw,const CopyOp& copyop):
Group(sw,copyop),
_newChildDefaultValue(sw._newChildDefaultValue),
_values(sw._values)
{
}
void Switch::traverse(NodeVisitor& nv)
{
if (nv.getTraversalMode()==NodeVisitor::TRAVERSE_ACTIVE_CHILDREN)
{
for(unsigned int pos=0;pos<_children.size();++pos)
{
if (_values[pos]) _children[pos]->accept(nv);
}
}
else
{
Group::traverse(nv);
}
}
bool Switch::addChild( Node *child )
{
if (Group::addChild(child))
{
if (_children.size()>_values.size())
{
_values.resize(_children.size(),_newChildDefaultValue);
}
// note, we don't override any pre-existing _values[childPosition] setting
// like in addChild(child,value) below.
return true;
}
return false;
}
bool Switch::addChild( Node *child, bool value )
{
unsigned int childPosition = _children.size();
if (Group::addChild(child))
{
if (_children.size()>_values.size())
{
_values.resize(_children.size(),_newChildDefaultValue);
}
_values[childPosition]=value;
return true;
}
return false;
}
bool Switch::insertChild( unsigned int index, Node *child )
{
return insertChild(index,child,_newChildDefaultValue);
}
bool Switch::insertChild( unsigned int index, Node *child, bool value )
{
if (Group::insertChild(index,child))
{
if (index>=_values.size())
{
_values.push_back(value);
}
else
{
_values.insert(_values.begin()+index, value);
}
return true;
}
return false;
}
bool Switch::removeChild( Node *child )
{
return removeChild( getChildIndex(child) );
}
bool Switch::removeChild(unsigned int pos,unsigned int numChildrenToRemove)
{
if (pos>=_values.size() || numChildrenToRemove==0) return false;
unsigned int endOfRemoveRange = pos+numChildrenToRemove;
if (endOfRemoveRange>_values.size())
{
notify(DEBUG_INFO)<<"Warning: Switch::removeChild(i,numChildrenToRemove) has been passed an excessive number"<<std::endl;
notify(DEBUG_INFO)<<" of chilren to remove, trimming just to end of value list."<<std::endl;
endOfRemoveRange=_values.size();
}
_values.erase(_values.begin()+pos,_values.begin()+endOfRemoveRange);
return Group::removeChild(pos, numChildrenToRemove);
}
void Switch::setValue(unsigned int pos,bool value)
{
if (pos>=_values.size()) _values.resize(pos+1,_newChildDefaultValue);
_values[pos]=value;
dirtyBound();
}
void Switch::setChildValue(const Node* child,bool value)
{
// find the child's position.
unsigned int pos=getChildIndex(child);
if (pos==_children.size()) return;
_values[pos]=value;
dirtyBound();
}
bool Switch::getValue(unsigned int pos) const
{
if (pos>=_values.size()) return false;
return _values[pos];
}
bool Switch::getChildValue(const Node* child) const
{
// find the child's position.
unsigned int pos=getChildIndex(child);
if (pos==_children.size()) return false;
return _values[pos];
}
bool Switch::setAllChildrenOff()
{
_newChildDefaultValue = false;
for(ValueList::iterator itr=_values.begin();
itr!=_values.end();
++itr)
{
*itr = false;
}
dirtyBound();
return true;
}
bool Switch::setAllChildrenOn()
{
_newChildDefaultValue = true;
for(ValueList::iterator itr=_values.begin();
itr!=_values.end();
++itr)
{
*itr = true;
}
dirtyBound();
return true;
}
bool Switch::setSingleChildOn(unsigned int pos)
{
for(ValueList::iterator itr=_values.begin();
itr!=_values.end();
++itr)
{
*itr = false;
}
setValue(pos,true);
return true;
}
BoundingSphere Switch::computeBound() const
{
BoundingSphere bsphere;
if (_children.empty())
{
return bsphere;
}
// note, special handling of the case when a child is an Transform,
// such that only Transforms which are relative to their parents coordinates frame (i.e this group)
// are handled, Transform relative to and absolute reference frame are ignored.
BoundingBox bb;
bb.init();
NodeList::const_iterator itr;
for(itr=_children.begin();
itr!=_children.end();
++itr)
{
const osg::Transform* transform = (*itr)->asTransform();
if (!transform || transform->getReferenceFrame()==osg::Transform::RELATIVE_RF)
{
if( getChildValue((*itr).get()) == true )
bb.expandBy((*itr)->getBound());
}
}
if (!bb.valid())
{
return bsphere;
}
bsphere._center = bb.center();
bsphere._radius = 0.0f;
for(itr=_children.begin();
itr!=_children.end();
++itr)
{
const osg::Transform* transform = (*itr)->asTransform();
if (!transform || transform->getReferenceFrame()==osg::Transform::RELATIVE_RF)
{
if( getChildValue((*itr).get()) == true )
bsphere.expandRadiusBy((*itr)->getBound());
}
}
return bsphere;
}
<|endoftext|> |
<commit_before>#ifndef UTENSOR_MLP_TEST
#define UTENSOR_MLP_TEST
#include "tensor.hpp"
#include "ArrayOps.hpp"
#include "MathOps.hpp"
#include "MatrixOps.hpp"
class mlpTest : public Test {
public:
TensorIdxImporter t_import;
void runQuantization() {
testStart("runQuantization");
timer_start();
//reshape
//input
Tensor* mnist_input = t_import.float_import("/fs/testData/mlpTest/runQuantization/in/import-Placeholder_0.idx");
Tensor* reshape_dim = t_import.int_import("/fs/testData/mlpTest/runQuantization/in/import-MatMul_eightbit_reshape_dims_0.idx");
//output
Tensor* reshape_out = nullptr;
reshape<float>(mnist_input, reshape_dim, &reshape_out);
delete mnist_input;
delete reshape_dim;
//min
//input
Tensor* min_reduce_dim = t_import.int_import("/fs/testData/mlpTest/runQuantization/in/import-MatMul_eightbit_reduction_dims_0_min.idx");
//output
Tensor* min_out = new RamTensor<float>({1});
Min<float, int, float>(reshape_out, min_reduce_dim, min_out);
delete min_reduce_dim;
//max
//input
Tensor* max_reduce_dim = t_import.int_import("/fs/testData/mlpTest/runQuantization/in/import-MatMul_eightbit_reduction_dims_0_max.idx");
//output
Tensor* max_out = new RamTensor<float>({1});
Max<float, int, float>(reshape_out, max_reduce_dim, max_out);
delete max_reduce_dim;
//quantization
//output
Tensor* qnt_out = new RamTensor<unsigned char>(reshape_out->getShape());
Tensor* qnt_min = new RamTensor<float>({1});
Tensor* qnt_max = new RamTensor<float>({1});
QuantizeV2<unsigned char>(reshape_out, min_out, max_out, qnt_out, qnt_min, qnt_max);
delete reshape_out;
timer_stop();
Tensor* qnt_ref = t_import.ubyte_import("/fs/testData/mlpTest/runQuantization/out/import-MatMul_eightbit_quantize_Placeholder_0.idx");
Tensor* qnt_min_ref = t_import.float_import("/fs/testData/mlpTest/runQuantization/out/import-MatMul_eightbit_quantize_Placeholder_1.idx");
Tensor* qnt_max_ref = t_import.float_import("/fs/testData/mlpTest/runQuantization/out/import-MatMul_eightbit_quantize_Placeholder_2.idx");
double result = meanPercentErr<unsigned char>(qnt_ref, qnt_out);
result += meanPercentErr<float>(qnt_min_ref, qnt_min);
result += meanPercentErr<float>(qnt_max_ref, qnt_max);
passed(result == 0);
delete qnt_ref;
delete qnt_min_ref;
delete qnt_max_ref;
delete qnt_out;
delete qnt_min;
delete qnt_max;
delete max_out;
delete min_out;
}
//quantized matmul dequant add
//layer value prior to activation function
void runQntDeqntLayerZ() {
DEBUG("running runQntDeqntLayerZ\r\n");
testStart("runQntDeqntLayerZ");
timer_start();
//quantized matrix multiplication
//input
Tensor* x =
t_import.ubyte_import("/fs/testData/mlpTest/runQntDeqntLayerZ/in/import-MatMul_eightbit_quantize_Placeholder_0.idx");
Tensor* x_min =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/in/import-MatMul_eightbit_quantize_Placeholder_1.idx");
Tensor* x_max =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/in/import-MatMul_eightbit_quantize_Placeholder_2.idx");
Tensor* w =
t_import.ubyte_import("/fs/testData/mlpTest/runQntDeqntLayerZ/in/import-Variable_quint8_const_0.idx");
Tensor* w_min =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/in/import-Variable_min_0.idx");
Tensor* w_max =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/in/import-Variable_max_0.idx");
DEBUG("all QuantizedMatMul input imported...\r\n");
//output
uint32_t out_col = (x->getShape())[0];
uint32_t out_row = (w->getShape())[1];
Tensor* out_c = new RamTensor<int>({out_col, out_row});
// printf("x[0] = %d, x[1] = %d, b[0] = %d, b[1] = %d\r\n", (x.getShape())[0], (x.getShape())[1],
// (w.getShape())[0], (w.getShape())[1]);
// printf("c[0] = %d, c[1] = %d\r\n", (out_c.getShape())[0], (out_c.getShape())[1]);
// fflush(stdout);
Tensor* matmul_out_min = new RamTensor<float>({1});
Tensor* matmul_out_max = new RamTensor<float>({1});
QuantizedMatMul<uint8_t, uint8_t, int>(x, w, &out_c, x_min, w_min, x_max,
w_max, matmul_out_min, matmul_out_max);
//clean up
delete x;
delete w;
delete x_min;
delete w_min;
delete x_max;
delete w_max;
Tensor* ref_out_c =
t_import.int_import("/fs/testData/mlpTest/runQntDeqntLayerZ/import-MatMul_eightbit_quantized_mat_mul_0.idx");
Tensor* ref_matmul_out_min =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/import-MatMul_eightbit_quantized_mat_mul_1.idx");
Tensor* ref_matmul_out_max =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/import-MatMul_eightbit_quantized_mat_mul_2.idx");
double temp_result = (meanPercentErr<int>(ref_out_c, out_c) + meanPercentErr<float>(ref_matmul_out_min, matmul_out_min) + meanPercentErr<float>(ref_matmul_out_max, matmul_out_max));
if(temp_result > 0) {
DEBUG("matrix mul failed\r\n");
failed();
return;
} else {
DEBUG("matrix mul passed\r\n");
}
delete ref_out_c;
delete ref_matmul_out_max;
delete ref_matmul_out_min;
DEBUG("QuantizedMatMul completed!\r\n");
//output
Tensor* req_out_min = new RamTensor<float>({1});
Tensor* req_out_max = new RamTensor<float>({1});
Requantization_Range<int, float>(out_c, matmul_out_min, matmul_out_max, req_out_min, req_out_max);
Tensor* ref_req_out_min =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/in/import-MatMul_eightbit_requant_range_0.idx");
Tensor* ref_req_out_max =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/in/import-MatMul_eightbit_requant_range_1.idx");
temp_result = (meanPercentErr<float>(ref_req_out_min, req_out_min) + meanPercentErr<float>(ref_req_out_max, req_out_max));
if(temp_result > 0) {
DEBUG("Requantization_Range failed\r\n");
failed();
return;
} else {
DEBUG("Requantization_Range passed\r\n");
}
delete ref_req_out_min;
delete ref_req_out_max;
DEBUG("Requantization_Range completed!\r\n");
//output
Tensor* reqnt_out = new RamTensor<unsigned char>(out_c->getShape());
Tensor* reqnt_out_min = new RamTensor<float>({1});
Tensor* reqnt_out_max = new RamTensor<float>({1});
Requantize<int, float, unsigned char>(out_c, matmul_out_min, matmul_out_max, req_out_min, req_out_max,
reqnt_out, reqnt_out_min, reqnt_out_max);
//clean up
delete matmul_out_min;
delete matmul_out_max;
delete req_out_min;
delete req_out_max;
Tensor* ref_reqnt_out =
t_import.ubyte_import("/fs/testData/mlpTest/runQntDeqntLayerZ/import-MatMul_eightbit_requantize_0.idx");
Tensor* ref_reqnt_out_min =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/import-MatMul_eightbit_requantize_1.idx");
Tensor* ref_reqnt_out_max =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/import-MatMul_eightbit_requantize_2.idx");
temp_result = (meanPercentErr<unsigned char>(ref_reqnt_out, reqnt_out) + meanPercentErr<float>(ref_reqnt_out_min, reqnt_out_min) + meanPercentErr<float>(ref_reqnt_out_max, reqnt_out_max));
if(temp_result > 0) {
DEBUG("Requantize failed\r\n");
failed();
return;
} else {
DEBUG("Requantize passed\r\n");
}
delete ref_reqnt_out;
delete ref_reqnt_out_min;
delete ref_reqnt_out_max;
DEBUG("Requantize completed!\r\n");
//output
Tensor* deqnt_out = new RamTensor<float>(out_c->getShape());
dequantize<unsigned char>(reqnt_out, reqnt_out_min, reqnt_out_max, &deqnt_out);
delete out_c;
delete reqnt_out_min;
delete reqnt_out_max;
delete reqnt_out;
Tensor* ref_deqnt_out = t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/import-MatMul_0.idx");
double temp;
if((temp = meanPercentErr<float>(ref_deqnt_out, deqnt_out)) > 0) {
printf("dequantize failed (%.6f)\r\n", temp);
float* ref_ptr = ref_deqnt_out->read<float>(0, 0);
float* test_ptr = deqnt_out->read<float>(0, 0);
for(uint32_t i; i < ref_deqnt_out->getSize(); i++) {
if(ref_ptr[i] != test_ptr[i]) {
DEBUG("%d: %.3f != %.3f, diff: %.8f%%\r\n", i, ref_ptr[i], test_ptr[i], test_ptr[i]/ref_ptr[i]);
} else {
DEBUG("%d: %.3f == %.3f\r\n", i, ref_ptr[i], test_ptr[i]);
}
}
failed();
return;
} else {
DEBUG("dequantize passed\r\n");
}
delete ref_deqnt_out;
DEBUG("dequantize completed!\r\n");
//input
Tensor* bias = t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/out/import-Variable_1_0.idx");
//output
Tensor* output_z = new RamTensor<float>(deqnt_out->getShape());
Add<float, float>(deqnt_out, bias, &output_z);
delete deqnt_out;
DEBUG("Add completed!\r\n");
timer_stop();
//load reference
Tensor* ref_z = t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/out/import-add_0.idx");
double result = meanPercentErr<float>(ref_z, output_z);
passed(result < 0.0001);
delete ref_z;
delete output_z;
delete bias;
}
void runQntRelu() {
testStart("runQntRelu");
Tensor* input_z = t_import.float_import("/fs/testData/mlpTest/runQntRelu/in/import-add_0.idx");
Tensor* reshape_dim = t_import.int_import("/fs/testData/mlpTest/runQntRelu/in/import-Relu_eightbit_reshape_dims_0.idx");
Tensor* reshape_out = nullptr;
timer_start();
reshape<float>(input_z, reshape_dim, &reshape_out);
//min
//input
Tensor* min_reduce_dim = t_import.int_import("/fs/testData/mlpTest/runQntRelu/in/import-Relu_eightbit_reduction_dims_0_min.idx");
//output
Tensor* min_out = new RamTensor<float>({1});
Min<float, int, float>(reshape_out, min_reduce_dim, min_out);
delete min_reduce_dim;
//max
//input
Tensor* max_reduce_dim = t_import.int_import("/fs/testData/mlpTest/runQntRelu/in/import-Relu_eightbit_reduction_dims_0_max.idx");
//output
Tensor* max_out = new RamTensor<float>({1});
Max<float, int, float>(reshape_out, max_reduce_dim, max_out);
delete max_reduce_dim;
//quantization
//output
Tensor* qnt_out = new RamTensor<unsigned char>(reshape_out->getShape());
Tensor* qnt_min = new RamTensor<float>({1});
Tensor* qnt_max = new RamTensor<float>({1});
QuantizeV2<unsigned char>(reshape_out, min_out, max_out, qnt_out, qnt_min, qnt_max);
delete reshape_out;
Tensor* out = new RamTensor<unsigned char>(qnt_out->getShape());
Tensor* out_min = new RamTensor<float>({1});
Tensor* out_max = new RamTensor<float>({1});
Relu<unsigned char, float, unsigned char>(qnt_out, qnt_min, qnt_max, out, out_min,
out_max);
timer_stop();
Tensor* ref_out =
t_import.ubyte_import("/fs/testData/mlpTest/runQntRelu/out/import-Relu_eightbit_quantized_0.idx");
Tensor* ref_out_min =
t_import.float_import("/fs/testData/mlpTest/runQntRelu/out/import-Relu_eightbit_quantized_1.idx");
Tensor* ref_out_max =
t_import.float_import("/fs/testData/mlpTest/runQntRelu/out/import-Relu_eightbit_quantized_2.idx");
double result = meanPercentErr<unsigned char>(ref_out, out);
result += meanPercentErr<float>(ref_out_min, out_min);
result += meanPercentErr<float>(ref_out_max, out_max);
passed(result == 0);
}
void runAll() {
runQuantization();
runQntDeqntLayerZ();
runQntRelu();
}
};
#endif //UTENSOR_MLP_TEST
<commit_msg> 1. when the code is compiled with release mode, the dequantize error would be 10-7. it will be bigger than 0, and failed 2. 10-7 should be ignorable.<commit_after>#ifndef UTENSOR_MLP_TEST
#define UTENSOR_MLP_TEST
#include "tensor.hpp"
#include "ArrayOps.hpp"
#include "MathOps.hpp"
#include "MatrixOps.hpp"
class mlpTest : public Test {
public:
TensorIdxImporter t_import;
void runQuantization() {
testStart("runQuantization");
timer_start();
//reshape
//input
Tensor* mnist_input = t_import.float_import("/fs/testData/mlpTest/runQuantization/in/import-Placeholder_0.idx");
Tensor* reshape_dim = t_import.int_import("/fs/testData/mlpTest/runQuantization/in/import-MatMul_eightbit_reshape_dims_0.idx");
//output
Tensor* reshape_out = nullptr;
reshape<float>(mnist_input, reshape_dim, &reshape_out);
delete mnist_input;
delete reshape_dim;
//min
//input
Tensor* min_reduce_dim = t_import.int_import("/fs/testData/mlpTest/runQuantization/in/import-MatMul_eightbit_reduction_dims_0_min.idx");
//output
Tensor* min_out = new RamTensor<float>({1});
Min<float, int, float>(reshape_out, min_reduce_dim, min_out);
delete min_reduce_dim;
//max
//input
Tensor* max_reduce_dim = t_import.int_import("/fs/testData/mlpTest/runQuantization/in/import-MatMul_eightbit_reduction_dims_0_max.idx");
//output
Tensor* max_out = new RamTensor<float>({1});
Max<float, int, float>(reshape_out, max_reduce_dim, max_out);
delete max_reduce_dim;
//quantization
//output
Tensor* qnt_out = new RamTensor<unsigned char>(reshape_out->getShape());
Tensor* qnt_min = new RamTensor<float>({1});
Tensor* qnt_max = new RamTensor<float>({1});
QuantizeV2<unsigned char>(reshape_out, min_out, max_out, qnt_out, qnt_min, qnt_max);
delete reshape_out;
timer_stop();
Tensor* qnt_ref = t_import.ubyte_import("/fs/testData/mlpTest/runQuantization/out/import-MatMul_eightbit_quantize_Placeholder_0.idx");
Tensor* qnt_min_ref = t_import.float_import("/fs/testData/mlpTest/runQuantization/out/import-MatMul_eightbit_quantize_Placeholder_1.idx");
Tensor* qnt_max_ref = t_import.float_import("/fs/testData/mlpTest/runQuantization/out/import-MatMul_eightbit_quantize_Placeholder_2.idx");
double result = meanPercentErr<unsigned char>(qnt_ref, qnt_out);
result += meanPercentErr<float>(qnt_min_ref, qnt_min);
result += meanPercentErr<float>(qnt_max_ref, qnt_max);
passed(result == 0);
delete qnt_ref;
delete qnt_min_ref;
delete qnt_max_ref;
delete qnt_out;
delete qnt_min;
delete qnt_max;
delete max_out;
delete min_out;
}
//quantized matmul dequant add
//layer value prior to activation function
void runQntDeqntLayerZ() {
DEBUG("running runQntDeqntLayerZ\r\n");
testStart("runQntDeqntLayerZ");
timer_start();
//quantized matrix multiplication
//input
Tensor* x =
t_import.ubyte_import("/fs/testData/mlpTest/runQntDeqntLayerZ/in/import-MatMul_eightbit_quantize_Placeholder_0.idx");
Tensor* x_min =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/in/import-MatMul_eightbit_quantize_Placeholder_1.idx");
Tensor* x_max =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/in/import-MatMul_eightbit_quantize_Placeholder_2.idx");
Tensor* w =
t_import.ubyte_import("/fs/testData/mlpTest/runQntDeqntLayerZ/in/import-Variable_quint8_const_0.idx");
Tensor* w_min =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/in/import-Variable_min_0.idx");
Tensor* w_max =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/in/import-Variable_max_0.idx");
DEBUG("all QuantizedMatMul input imported...\r\n");
//output
uint32_t out_col = (x->getShape())[0];
uint32_t out_row = (w->getShape())[1];
Tensor* out_c = new RamTensor<int>({out_col, out_row});
// printf("x[0] = %d, x[1] = %d, b[0] = %d, b[1] = %d\r\n", (x.getShape())[0], (x.getShape())[1],
// (w.getShape())[0], (w.getShape())[1]);
// printf("c[0] = %d, c[1] = %d\r\n", (out_c.getShape())[0], (out_c.getShape())[1]);
// fflush(stdout);
Tensor* matmul_out_min = new RamTensor<float>({1});
Tensor* matmul_out_max = new RamTensor<float>({1});
QuantizedMatMul<uint8_t, uint8_t, int>(x, w, &out_c, x_min, w_min, x_max,
w_max, matmul_out_min, matmul_out_max);
//clean up
delete x;
delete w;
delete x_min;
delete w_min;
delete x_max;
delete w_max;
Tensor* ref_out_c =
t_import.int_import("/fs/testData/mlpTest/runQntDeqntLayerZ/import-MatMul_eightbit_quantized_mat_mul_0.idx");
Tensor* ref_matmul_out_min =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/import-MatMul_eightbit_quantized_mat_mul_1.idx");
Tensor* ref_matmul_out_max =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/import-MatMul_eightbit_quantized_mat_mul_2.idx");
double temp_result = (meanPercentErr<int>(ref_out_c, out_c) + meanPercentErr<float>(ref_matmul_out_min, matmul_out_min) + meanPercentErr<float>(ref_matmul_out_max, matmul_out_max));
if(temp_result > 0) {
DEBUG("matrix mul failed\r\n");
failed();
return;
} else {
DEBUG("matrix mul passed\r\n");
}
delete ref_out_c;
delete ref_matmul_out_max;
delete ref_matmul_out_min;
DEBUG("QuantizedMatMul completed!\r\n");
//output
Tensor* req_out_min = new RamTensor<float>({1});
Tensor* req_out_max = new RamTensor<float>({1});
Requantization_Range<int, float>(out_c, matmul_out_min, matmul_out_max, req_out_min, req_out_max);
Tensor* ref_req_out_min =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/in/import-MatMul_eightbit_requant_range_0.idx");
Tensor* ref_req_out_max =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/in/import-MatMul_eightbit_requant_range_1.idx");
temp_result = (meanPercentErr<float>(ref_req_out_min, req_out_min) + meanPercentErr<float>(ref_req_out_max, req_out_max));
if(temp_result > 0) {
DEBUG("Requantization_Range failed\r\n");
failed();
return;
} else {
DEBUG("Requantization_Range passed\r\n");
}
delete ref_req_out_min;
delete ref_req_out_max;
DEBUG("Requantization_Range completed!\r\n");
//output
Tensor* reqnt_out = new RamTensor<unsigned char>(out_c->getShape());
Tensor* reqnt_out_min = new RamTensor<float>({1});
Tensor* reqnt_out_max = new RamTensor<float>({1});
Requantize<int, float, unsigned char>(out_c, matmul_out_min, matmul_out_max, req_out_min, req_out_max,
reqnt_out, reqnt_out_min, reqnt_out_max);
//clean up
delete matmul_out_min;
delete matmul_out_max;
delete req_out_min;
delete req_out_max;
Tensor* ref_reqnt_out =
t_import.ubyte_import("/fs/testData/mlpTest/runQntDeqntLayerZ/import-MatMul_eightbit_requantize_0.idx");
Tensor* ref_reqnt_out_min =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/import-MatMul_eightbit_requantize_1.idx");
Tensor* ref_reqnt_out_max =
t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/import-MatMul_eightbit_requantize_2.idx");
temp_result = (meanPercentErr<unsigned char>(ref_reqnt_out, reqnt_out) + meanPercentErr<float>(ref_reqnt_out_min, reqnt_out_min) + meanPercentErr<float>(ref_reqnt_out_max, reqnt_out_max));
if(temp_result > 0) {
DEBUG("Requantize failed\r\n");
failed();
return;
} else {
DEBUG("Requantize passed\r\n");
}
delete ref_reqnt_out;
delete ref_reqnt_out_min;
delete ref_reqnt_out_max;
DEBUG("Requantize completed!\r\n");
//output
Tensor* deqnt_out = new RamTensor<float>(out_c->getShape());
dequantize<unsigned char>(reqnt_out, reqnt_out_min, reqnt_out_max, &deqnt_out);
delete out_c;
delete reqnt_out_min;
delete reqnt_out_max;
delete reqnt_out;
Tensor* ref_deqnt_out = t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/import-MatMul_0.idx");
double temp = meanPercentErr<float>(ref_deqnt_out, deqnt_out);
if(temp > 0.0001) {
printf("dequantize failed (%.6f)\r\n", temp);
float* ref_ptr = ref_deqnt_out->read<float>(0, 0);
float* test_ptr = deqnt_out->read<float>(0, 0);
for(uint32_t i; i < ref_deqnt_out->getSize(); i++) {
if(ref_ptr[i] != test_ptr[i]) {
DEBUG("%d: %.3f != %.3f, diff: %.8f%%\r\n", i, ref_ptr[i], test_ptr[i], test_ptr[i]/ref_ptr[i]);
} else {
DEBUG("%d: %.3f == %.3f\r\n", i, ref_ptr[i], test_ptr[i]);
}
}
failed();
return;
} else {
DEBUG("dequantize passed\r\n");
}
delete ref_deqnt_out;
DEBUG("dequantize completed!\r\n");
//input
Tensor* bias = t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/out/import-Variable_1_0.idx");
//output
Tensor* output_z = new RamTensor<float>(deqnt_out->getShape());
Add<float, float>(deqnt_out, bias, &output_z);
delete deqnt_out;
DEBUG("Add completed!\r\n");
timer_stop();
//load reference
Tensor* ref_z = t_import.float_import("/fs/testData/mlpTest/runQntDeqntLayerZ/out/import-add_0.idx");
double result = meanPercentErr<float>(ref_z, output_z);
std::cout << result << std::endl;
passed(result < 0.001);
delete ref_z;
delete output_z;
delete bias;
}
void runQntRelu() {
testStart("runQntRelu");
Tensor* input_z = t_import.float_import("/fs/testData/mlpTest/runQntRelu/in/import-add_0.idx");
Tensor* reshape_dim = t_import.int_import("/fs/testData/mlpTest/runQntRelu/in/import-Relu_eightbit_reshape_dims_0.idx");
Tensor* reshape_out = nullptr;
timer_start();
reshape<float>(input_z, reshape_dim, &reshape_out);
//min
//input
Tensor* min_reduce_dim = t_import.int_import("/fs/testData/mlpTest/runQntRelu/in/import-Relu_eightbit_reduction_dims_0_min.idx");
//output
Tensor* min_out = new RamTensor<float>({1});
Min<float, int, float>(reshape_out, min_reduce_dim, min_out);
delete min_reduce_dim;
//max
//input
Tensor* max_reduce_dim = t_import.int_import("/fs/testData/mlpTest/runQntRelu/in/import-Relu_eightbit_reduction_dims_0_max.idx");
//output
Tensor* max_out = new RamTensor<float>({1});
Max<float, int, float>(reshape_out, max_reduce_dim, max_out);
delete max_reduce_dim;
//quantization
//output
Tensor* qnt_out = new RamTensor<unsigned char>(reshape_out->getShape());
Tensor* qnt_min = new RamTensor<float>({1});
Tensor* qnt_max = new RamTensor<float>({1});
QuantizeV2<unsigned char>(reshape_out, min_out, max_out, qnt_out, qnt_min, qnt_max);
delete reshape_out;
Tensor* out = new RamTensor<unsigned char>(qnt_out->getShape());
Tensor* out_min = new RamTensor<float>({1});
Tensor* out_max = new RamTensor<float>({1});
Relu<unsigned char, float, unsigned char>(qnt_out, qnt_min, qnt_max, out, out_min,
out_max);
timer_stop();
Tensor* ref_out =
t_import.ubyte_import("/fs/testData/mlpTest/runQntRelu/out/import-Relu_eightbit_quantized_0.idx");
Tensor* ref_out_min =
t_import.float_import("/fs/testData/mlpTest/runQntRelu/out/import-Relu_eightbit_quantized_1.idx");
Tensor* ref_out_max =
t_import.float_import("/fs/testData/mlpTest/runQntRelu/out/import-Relu_eightbit_quantized_2.idx");
double result = meanPercentErr<unsigned char>(ref_out, out);
result += meanPercentErr<float>(ref_out_min, out_min);
result += meanPercentErr<float>(ref_out_max, out_max);
passed(result == 0);
}
void runAll() {
runQuantization();
runQntDeqntLayerZ();
runQntRelu();
}
};
#endif //UTENSOR_MLP_TEST
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief rules for the query optimizer
///
/// @file arangod/Aql/OptimizerRules.cpp
///
/// DISCLAIMER
///
/// Copyright 2010-2014 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Max Neunhoeffer
/// @author Copyright 2014, triagens GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "Aql/OptimizerRules.h"
using namespace triagens::aql;
// -----------------------------------------------------------------------------
// --SECTION-- rules for the optimizer
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief remove all unnecessary filters
/// this modifies the plan in place
////////////////////////////////////////////////////////////////////////////////
int triagens::aql::removeUnnecessaryFiltersRule (Optimizer* opt,
ExecutionPlan* plan,
Optimizer::PlanList& out,
bool& keep) {
keep = true;
std::vector<ExecutionNode*> nodes = plan->findNodesOfType(triagens::aql::ExecutionNode::FILTER);
for (auto n : nodes) {
// filter has one input variable
auto varsUsedHere = n->getVariablesUsedHere();
TRI_ASSERT(varsUsedHere.size() == 1);
// now check who introduced our variable
auto variable = varsUsedHere[0];
auto setter = plan->getVarSetBy(variable->id);
if (setter != nullptr &&
setter->getType() == triagens::aql::ExecutionNode::CALCULATION) {
// if it was a CalculationNode, check its expression
auto s = static_cast<CalculationNode*>(setter);
auto root = s->expression()->node();
if (root->isConstant()) {
// the expression is a constant value
if (root->toBoolean()) {
// TODO: remove filter node and merge with following node
std::cout << "FOUND A CONSTANT FILTER WHICH IS ALWAYS TRUE. TODO: optimize it away!\n";
}
else {
// TODO: remove filter node plus all dependencies
std::cout << "FOUND A CONSTANT FILTER WHICH IS ALWAYS FALSE. TODO: optimize all the stuff above!\n";
}
}
}
}
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief remove CalculationNode(s) that are never needed
////////////////////////////////////////////////////////////////////////////////
int triagens::aql::removeUnnecessaryCalc (Optimizer* opt,
ExecutionPlan* plan,
Optimizer::PlanList& out,
bool& keep) {
std::vector<ExecutionNode*> nodes
= plan->findNodesOfType(triagens::aql::ExecutionNode::CALCULATION);
std::unordered_set<ExecutionNode*> toRemove;
for (auto n : nodes) {
auto nn = static_cast<CalculationNode*>(n);
if (! nn->expression()->canThrow()) {
// If this node can throw, we must not optimize it away!
auto outvar = n->getVariablesSetHere();
TRI_ASSERT(outvar.size() == 1);
auto varsUsedLater = n->getVarsUsedLater();
if (varsUsedLater.find(outvar[0]) == varsUsedLater.end()) {
// The variable whose value is calculated here is not used at
// all further down the pipeline! We remove the whole
// calculation node,
toRemove.insert(n);
}
}
}
if (! toRemove.empty()) {
std::cout << "Removing " << toRemove.size() << " unnecessary "
"CalculationNodes..." << std::endl;
plan->removeNodes(toRemove);
out.push_back(plan);
keep = false;
}
else {
keep = true;
}
return TRI_ERROR_NO_ERROR;
}
// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
<commit_msg>remove filters which are always true<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief rules for the query optimizer
///
/// @file arangod/Aql/OptimizerRules.cpp
///
/// DISCLAIMER
///
/// Copyright 2010-2014 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Max Neunhoeffer
/// @author Copyright 2014, triagens GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "Aql/OptimizerRules.h"
using namespace triagens::aql;
// -----------------------------------------------------------------------------
// --SECTION-- rules for the optimizer
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief remove all unnecessary filters
/// this modifies the plan in place
////////////////////////////////////////////////////////////////////////////////
int triagens::aql::removeUnnecessaryFiltersRule (Optimizer* opt,
ExecutionPlan* plan,
Optimizer::PlanList& out,
bool& keep) {
keep = true;
std::unordered_set<ExecutionNode*> toRemove;
std::vector<ExecutionNode*> nodes = plan->findNodesOfType(triagens::aql::ExecutionNode::FILTER);
for (auto n : nodes) {
// filter has one input variable
auto varsUsedHere = n->getVariablesUsedHere();
TRI_ASSERT(varsUsedHere.size() == 1);
// now check who introduced our variable
auto variable = varsUsedHere[0];
auto setter = plan->getVarSetBy(variable->id);
if (setter != nullptr &&
setter->getType() == triagens::aql::ExecutionNode::CALCULATION) {
// if it was a CalculationNode, check its expression
auto s = static_cast<CalculationNode*>(setter);
auto root = s->expression()->node();
if (root->isConstant()) {
// the expression is a constant value
if (root->toBoolean()) {
// TODO: remove filter node and merge with following node
toRemove.insert(n);
}
else {
// TODO: remove filter node plus all dependencies
std::cout << "FOUND A CONSTANT FILTER WHICH IS ALWAYS FALSE. TODO: optimize all the stuff above!\n";
}
}
}
}
if (! toRemove.empty()) {
std::cout << "Removing " << toRemove.size() << " unnecessary "
"FilterNodes..." << std::endl;
plan->removeNodes(toRemove);
}
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief remove CalculationNode(s) that are never needed
////////////////////////////////////////////////////////////////////////////////
int triagens::aql::removeUnnecessaryCalc (Optimizer* opt,
ExecutionPlan* plan,
Optimizer::PlanList& out,
bool& keep) {
std::vector<ExecutionNode*> nodes
= plan->findNodesOfType(triagens::aql::ExecutionNode::CALCULATION);
std::unordered_set<ExecutionNode*> toRemove;
for (auto n : nodes) {
auto nn = static_cast<CalculationNode*>(n);
if (! nn->expression()->canThrow()) {
// If this node can throw, we must not optimize it away!
auto outvar = n->getVariablesSetHere();
TRI_ASSERT(outvar.size() == 1);
auto varsUsedLater = n->getVarsUsedLater();
if (varsUsedLater.find(outvar[0]) == varsUsedLater.end()) {
// The variable whose value is calculated here is not used at
// all further down the pipeline! We remove the whole
// calculation node,
toRemove.insert(n);
}
}
}
if (! toRemove.empty()) {
std::cout << "Removing " << toRemove.size() << " unnecessary "
"CalculationNodes..." << std::endl;
plan->removeNodes(toRemove);
out.push_back(plan);
keep = false;
}
else {
keep = true;
}
return TRI_ERROR_NO_ERROR;
}
// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
<|endoftext|> |
<commit_before>/* ****************************************************************************
*
* FILE main_samsonController.cpp
*
* AUTHOR Ken Zangelin
*
* CREATION DATE Dec 14 2010
*
*/
#include <unistd.h> // read
#include <fcntl.h> // open, O_RDONLY, ...
#include <sys/stat.h> // struct stat
#include "parseArgs.h" // parseArgs
#include "ports.h" // CONTROLLER_PORT
#include "samsonDirectories.h" // SAMSON_PLATFORM_PROCESSES
#include "SamsonController.h" // ss::SamsonController
#include "SamsonSetup.h" // ss::SamsonSetup
#include "platformProcesses.h" // ss::platformProcessesGet, ss::platformProcessesSave
#include "MemoryManager.h" // ss::MemoryManager
#include "DiskManager.h" // ss::DiskManager
#include "FileManager.h" // ss::FileManager
#include "LockDebugger.h" // au::LockDebugger
/* ****************************************************************************
*
* Option variables
*/
int endpoints;
char workingDir[1024];
#define DEF_WD _i SAMSON_DEFAULT_WORKING_DIRECTORY
#define DEF_WF _i SAMSON_PLATFORM_PROCESSES
/* ****************************************************************************
*
* parse arguments
*/
PaArgument paArgs[] =
{
{ "-working", workingDir, "WORKING", PaString, PaOpt, DEF_WD, PaNL, PaNL, "working directory" },
{ "-endpoints", &endpoints, "ENDPOINTS", PaInt, PaOpt, 80, 3, 100, "number of endpoints" },
PA_END_OF_ARGS
};
/* ****************************************************************************
*
* logFd - file descriptor for log file used in all libraries
*/
int logFd = -1;
/* ****************************************************************************
*
* main - main routine for the samsonController
*/
int main(int argC, const char* argV[])
{
ss::ProcessVector* processVec;
int processVecSize;
paConfig("prefix", (void*) "SSC_");
paConfig("usage and exit on any warning", (void*) true);
paConfig("log to screen", (void*) "only errors");
paConfig("log file line format", (void*) "TYPE:DATE:EXEC/FILE[LINE] FUNC: TEXT");
paConfig("screen line format", (void*) "TYPE:EXEC: TEXT");
paConfig("log to file", (void*) true);
paParse(paArgs, argC, (char**) argV, 1, false);
LM_T(LmtInit, ("Started with arguments:"));
for (int ix = 0; ix < argC; ix++)
LM_T(LmtInit, (" %02d: '%s'", ix, argV[ix]));
processVec = ss::platformProcessesGet(&processVecSize);
if (processVec == NULL)
LM_X(1, ("Error retreiving info about the platform processes - can't function without it!"));
LM_T(LmtInit, ("%d workers", processVec->processes - 1));
au::LockDebugger::shared(); // Lock usage debugging (necessary here where there is only one thread)
ss::SamsonSetup::load(workingDir); // Load setup and create all directories
ss::DiskManager::shared(); // Disk manager
ss::MemoryManager::init(); // Memory manager
ss::ModulesManager::init(); // Init the modules manager
// Instance of network object and initialization
// ---------------------------------------------
ss::Network network(ss::Endpoint::Controller, "Controller", CONTROLLER_PORT, endpoints, processVec->processes);
network.initAsSamsonController();
network.procVecSet(processVec, processVecSize, ss::platformProcessesSave);
network.runInBackground();
// Instance of the Samson Controller
// ---------------------------------
ss::SamsonController controller(&network);
controller.runBackgroundProcesses();
controller.touch();
while (true)
sleep(10000);
}
<commit_msg>number of workers is processVec->processes - 1<commit_after>/* ****************************************************************************
*
* FILE main_samsonController.cpp
*
* AUTHOR Ken Zangelin
*
* CREATION DATE Dec 14 2010
*
*/
#include <unistd.h> // read
#include <fcntl.h> // open, O_RDONLY, ...
#include <sys/stat.h> // struct stat
#include "parseArgs.h" // parseArgs
#include "ports.h" // CONTROLLER_PORT
#include "samsonDirectories.h" // SAMSON_PLATFORM_PROCESSES
#include "SamsonController.h" // ss::SamsonController
#include "SamsonSetup.h" // ss::SamsonSetup
#include "platformProcesses.h" // ss::platformProcessesGet, ss::platformProcessesSave
#include "MemoryManager.h" // ss::MemoryManager
#include "DiskManager.h" // ss::DiskManager
#include "FileManager.h" // ss::FileManager
#include "LockDebugger.h" // au::LockDebugger
/* ****************************************************************************
*
* Option variables
*/
int endpoints;
char workingDir[1024];
#define DEF_WD _i SAMSON_DEFAULT_WORKING_DIRECTORY
#define DEF_WF _i SAMSON_PLATFORM_PROCESSES
/* ****************************************************************************
*
* parse arguments
*/
PaArgument paArgs[] =
{
{ "-working", workingDir, "WORKING", PaString, PaOpt, DEF_WD, PaNL, PaNL, "working directory" },
{ "-endpoints", &endpoints, "ENDPOINTS", PaInt, PaOpt, 80, 3, 100, "number of endpoints" },
PA_END_OF_ARGS
};
/* ****************************************************************************
*
* logFd - file descriptor for log file used in all libraries
*/
int logFd = -1;
/* ****************************************************************************
*
* main - main routine for the samsonController
*/
int main(int argC, const char* argV[])
{
ss::ProcessVector* processVec;
int processVecSize;
paConfig("prefix", (void*) "SSC_");
paConfig("usage and exit on any warning", (void*) true);
paConfig("log to screen", (void*) "only errors");
paConfig("log file line format", (void*) "TYPE:DATE:EXEC/FILE[LINE] FUNC: TEXT");
paConfig("screen line format", (void*) "TYPE:EXEC: TEXT");
paConfig("log to file", (void*) true);
paParse(paArgs, argC, (char**) argV, 1, false);
LM_T(LmtInit, ("Started with arguments:"));
for (int ix = 0; ix < argC; ix++)
LM_T(LmtInit, (" %02d: '%s'", ix, argV[ix]));
processVec = ss::platformProcessesGet(&processVecSize);
if (processVec == NULL)
LM_X(1, ("Error retreiving info about the platform processes - can't function without it!"));
LM_T(LmtInit, ("%d workers", processVec->processes - 1));
au::LockDebugger::shared(); // Lock usage debugging (necessary here where there is only one thread)
ss::SamsonSetup::load(workingDir); // Load setup and create all directories
ss::DiskManager::shared(); // Disk manager
ss::MemoryManager::init(); // Memory manager
ss::ModulesManager::init(); // Init the modules manager
// Instance of network object and initialization
// ---------------------------------------------
ss::Network network(ss::Endpoint::Controller, "Controller", CONTROLLER_PORT, endpoints, processVec->processes - 1);
network.initAsSamsonController();
network.procVecSet(processVec, processVecSize, ss::platformProcessesSave);
network.runInBackground();
// Instance of the Samson Controller
// ---------------------------------
ss::SamsonController controller(&network);
controller.runBackgroundProcesses();
controller.touch();
while (true)
sleep(10000);
}
<|endoftext|> |
<commit_before>/** \file add_synonyms.cc
* \brief Generic version for augmenting title data with synonyms found
in the authority data
* \author Johannes Riedl
*/
/*
Copyright (C) 2016, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* We offer a list of tags and subfields where the primary data resides along
with a list of tags and subfields where the synonym data is found and
a list of unused fields in the title data where the synonyms can be stored
*/
#include <iostream>
#include <map>
#include <vector>
#include <cstdlib>
#include "Compiler.h"
#include "FileUtil.h"
#include "MarcReader.h"
#include "MarcRecord.h"
#include "MarcWriter.h"
#include "MediaTypeUtil.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"
static unsigned modified_count(0);
static unsigned record_count(0);
const unsigned FIELD_METADATA_SIZE(4);
void Usage() {
std::cerr << "Usage: " << ::progname << " master_marc_input norm_data_marc_input marc_output\n";
std::exit(EXIT_FAILURE);
}
std::string GetTag(const std::string &tag_and_subfields_spec) {
return tag_and_subfields_spec.substr(0, 3);
}
std::string GetSubfieldCodes(const std::string &tag_and_subfields_spec) {
return tag_and_subfields_spec.substr(3);
}
bool FilterPasses(const MarcRecord &record, const std::map<std::string, std::pair<std::string, std::string>> &filter_specs, const std::string &field_spec) {
auto filter_spec(filter_specs.find(field_spec));
if (filter_spec == filter_specs.cend())
return true;
auto rule(filter_spec->second);
// We have field_spec in key and rule to match in value
std::string subfield_codes(GetSubfieldCodes(rule.first));
if (subfield_codes.length() != 1)
Error("Invalid subfield specification " + subfield_codes + " for filter");
std::string subfield_value;
if ((subfield_value = record.extractFirstSubfield(GetTag(rule.first), subfield_codes.c_str()[0])).empty())
return false;
return subfield_value == rule.second;
}
void ExtractSynonyms(MarcReader * const authority_reader,
const std::set<std::string> &primary_tags_and_subfield_codes,
const std::set<std::string> &synonym_tags_and_subfield_codes,
std::vector<std::map<std::string, std::string>> * const synonym_maps,
const std::map<std::string, std::pair<std::string, std::string>> &filter_spec)
{
while (const MarcRecord record = authority_reader->read()) {
std::set<std::string>::const_iterator primary;
std::set<std::string>::const_iterator synonym;
unsigned int i(0);
for (primary = primary_tags_and_subfield_codes.begin(), synonym = synonym_tags_and_subfield_codes.begin();
primary != primary_tags_and_subfield_codes.end();
++primary, ++synonym, ++i)
{
// Fill maps with synonyms
std::vector<std::string> primary_values;
std::vector<std::string> synonym_values;
if (FilterPasses(record, filter_spec, *primary) and
record.extractSubfields(GetTag(*primary), GetSubfieldCodes(*primary), &primary_values) and
record.extractSubfields(GetTag(*synonym), GetSubfieldCodes(*synonym), &synonym_values))
(*synonym_maps)[i].emplace(StringUtil::Join(primary_values, ','),
StringUtil::Join(synonym_values, ','));
}
}
}
inline std::string GetMapValueOrEmptyString(const std::map<std::string, std::string> &map,
const std::string &searchterm)
{
auto value(map.find(searchterm));
return (value != map.cend()) ? value->second : "";
}
void ProcessRecord(MarcRecord * const record, const std::vector<std::map<std::string, std::string>> &synonym_maps,
const std::set<std::string> &primary_tags_and_subfield_codes,
const std::set<std::string> &output_tags_and_subfield_codes)
{
std::set<std::string>::const_iterator primary;
std::set<std::string>::const_iterator output;
unsigned int i(0);
bool modified_record(false);
if (primary_tags_and_subfield_codes.size() == output_tags_and_subfield_codes.size()) {
for (primary = primary_tags_and_subfield_codes.begin(), output = output_tags_and_subfield_codes.begin();
primary != primary_tags_and_subfield_codes.end();
++primary, ++output, ++i)
{
std::vector<std::string> primary_values;
std::set<std::string> synonym_values;
std::vector<size_t> field_indices;
if (record->getFieldIndices(GetTag(*primary), &field_indices) != MarcRecord::FIELD_NOT_FOUND) {
for (auto field_index : field_indices) {
primary_values.clear();
if (record->getSubfields(field_index).extractSubfields(GetSubfieldCodes(*primary), &primary_values)) {
std::string searchterm = StringUtil::Join(primary_values, ',');
// First case: Look up synonyms only in one category
if (i < synonym_maps.size()) {
const auto &synonym_map(synonym_maps[i]);
const auto synonym(GetMapValueOrEmptyString(synonym_map, searchterm));
if (not synonym.empty())
synonym_values.insert(synonym);
}
// Second case: Look up synonyms in all categories
else {
for (auto &synonym_map : synonym_maps) {
const auto &synonym(GetMapValueOrEmptyString(synonym_map, searchterm));
if (not synonym.empty())
synonym_values.insert(synonym);
}
}
}
}
if (synonym_values.empty())
continue;
// Insert synonyms
// Abort if field is already populated
std::string tag(GetTag(*output));
if (record->getFieldIndex(tag) != MarcRecord::FIELD_NOT_FOUND)
Error("Field with tag " + tag + " is not empty for PPN " + record->getControlNumber() + '\n');
std::string subfield_spec(GetSubfieldCodes(*output));
if (unlikely(subfield_spec.size() != 1))
Error("We currently only support a single subfield and thus specifying " + subfield_spec
+ " as output subfield is not valid\n");
std::string synonyms;
unsigned current_length(0);
unsigned indicator2(0);
for (auto synonym_it(synonym_values.cbegin()); synonym_it != synonym_values.cend(); /*Intentionally empty*/) {
if (indicator2 > 9)
Error ("Currently cannot handle synonyms with total length greater than " + std::to_string(9 * (MarcRecord::MAX_FIELD_LENGTH - FIELD_METADATA_SIZE)) + '\n');
if (current_length + synonym_it->length() < MarcRecord::MAX_FIELD_LENGTH - (FIELD_METADATA_SIZE + 3 /* consider " , " */) {
bool synonyms_empty(synonyms.empty());
synonyms += (synonyms_empty ? *synonym_it : " , " + *synonym_it);
current_length += synonym_it->length() + (synonyms_empty ? 0 : 3);
++synonym_it;
} else {
if (not(record->insertSubfield(tag, subfield_spec[0], synonyms, '0', indicator2 + '0')))
Error("Could not insert field " + tag + " for PPN " + record->getControlNumber() + '\n');
synonyms.clear();
current_length = 0;
++indicator2;
modified_record = true;
}
}
// Write rest of data
if (not synonyms.empty()) {
if (not(record->insertSubfield(tag, subfield_spec[0], synonyms, '0', indicator2 + '0')))
Error("Could not insert field " + tag + " for PPN " + record->getControlNumber() + '\n');
modified_record = true;
}
}
}
if (modified_record)
++modified_count;
}
}
void InsertSynonyms(MarcReader * const marc_reader, MarcWriter * const marc_writer,
const std::set<std::string> &primary_tags_and_subfield_codes,
const std::set<std::string> &output_tags_and_subfield_codes,
std::vector<std::map<std::string, std::string>> &synonym_maps)
{
while (MarcRecord record = marc_reader->read()) {
ProcessRecord(&record, synonym_maps, primary_tags_and_subfield_codes, output_tags_and_subfield_codes);
marc_writer->write(record);
++record_count;
}
std::cerr << "Modified " << modified_count << " of " << record_count << " record(s).\n";
}
bool ParseSpec(std::string spec_str, std::set<std::string> * const field_specs, std::map<std::string, std::pair<std::string, std::string>> * filter_specs = nullptr) {
std::set<std::string> raw_field_specs;
if (unlikely(StringUtil::Split(spec_str, ':', &raw_field_specs) == 0)) {
Error("Need at least one field");
return false;
}
if (filter_specs == nullptr) {
*field_specs = raw_field_specs;
return true;
}
// Iterate over all Field-specs and extract possible filters
static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory("(\\d{1,3}[a-z]+)\\[(\\d{1,3}[a-z])=(.*)\\]"));
for (auto field_spec : raw_field_specs) {
if (matcher->matched(field_spec)) {
filter_specs->emplace((*matcher)[1], std::make_pair((*matcher)[2], (*matcher)[3]));
auto bracket = field_spec.find("[");
field_spec = (bracket != std::string::npos) ? field_spec.erase(bracket, field_spec.length()) : field_spec;
}
field_specs->insert(field_spec);
}
return true;
}
int main(int argc, char **argv) {
::progname = argv[0];
if (argc != 4)
Usage();
const std::string marc_input_filename(argv[1]);
const std::string authority_data_marc_input_filename(argv[2]);
const std::string marc_output_filename(argv[3]);
if (unlikely(marc_input_filename == marc_output_filename))
Error("Title data input file name equals output file name!");
if (unlikely(authority_data_marc_input_filename == marc_output_filename))
Error("Authority data input file name equals output file name!");
std::unique_ptr<MarcReader> marc_reader(MarcReader::Factory(marc_input_filename, MarcReader::BINARY));
std::unique_ptr<MarcReader> authority_reader(MarcReader::Factory(authority_data_marc_input_filename,
MarcReader::BINARY));
std::unique_ptr<MarcWriter> marc_writer(MarcWriter::Factory(marc_output_filename, MarcWriter::BINARY));
try {
// Determine possible mappings
// Values in square brackets specify a positive criterion for values to be taken into account
const std::string AUTHORITY_DATA_PRIMARY_SPEC("100abcd[079v=piz]:110abcd:111abcd:130abcd:150abcd:151abcd");
const std::string AUTHORITY_DATA_SYNONYM_SPEC("400abcd:410abcd:411abcd:430abcd:450abcd:451abcd");
const std::string TITLE_DATA_PRIMARY_SPEC("600abcd:610abcd:611abcd:630abcd:650abcd:651abcd:689abcd");
const std::string TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS("180a:181a:182a:183a:184a:185a:186a");
// Determine fields to handle
std::set<std::string> primary_tags_and_subfield_codes;
std::set<std::string> synonym_tags_and_subfield_codes;
std::set<std::string> input_tags_and_subfield_codes;
std::set<std::string> output_tags_and_subfield_codes;
std::map<std::string, std::pair<std::string, std::string>> filter_specs;
if (not unlikely(ParseSpec(AUTHORITY_DATA_PRIMARY_SPEC, &primary_tags_and_subfield_codes, &filter_specs)))
Error("Could not properly parse " + AUTHORITY_DATA_PRIMARY_SPEC);
if (unlikely(StringUtil::Split(AUTHORITY_DATA_SYNONYM_SPEC, ":", &synonym_tags_and_subfield_codes) == 0))
Error("Need at least one synonym field");
if (unlikely(StringUtil::Split(TITLE_DATA_PRIMARY_SPEC, ":", &input_tags_and_subfield_codes) == 0))
Error("Need at least one input field");
if (unlikely(StringUtil::Split(TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS, ":", &output_tags_and_subfield_codes)
== 0))
Error("Need at least one output field");
unsigned num_of_authority_entries(primary_tags_and_subfield_codes.size());
if (synonym_tags_and_subfield_codes.size() != num_of_authority_entries)
Error("Number of authority primary specs must match number of synonym specs");
if (input_tags_and_subfield_codes.size() != output_tags_and_subfield_codes.size())
Error("Number of fields title entry specs must match number of output specs");
std::vector<std::map<std::string, std::string>> synonym_maps(num_of_authority_entries,
std::map<std::string, std::string>());
// Extract the synonyms from authority data
ExtractSynonyms(authority_reader.get(), primary_tags_and_subfield_codes, synonym_tags_and_subfield_codes,
&synonym_maps, filter_specs);
// Iterate over the title data
InsertSynonyms(marc_reader.get(), marc_writer.get(), input_tags_and_subfield_codes,
output_tags_and_subfield_codes, synonym_maps);
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
}
<commit_msg>Even more clarification<commit_after>/** \file add_synonyms.cc
* \brief Generic version for augmenting title data with synonyms found
in the authority data
* \author Johannes Riedl
*/
/*
Copyright (C) 2016, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* We offer a list of tags and subfields where the primary data resides along
with a list of tags and subfields where the synonym data is found and
a list of unused fields in the title data where the synonyms can be stored
*/
#include <iostream>
#include <map>
#include <vector>
#include <cstdlib>
#include "Compiler.h"
#include "FileUtil.h"
#include "MarcReader.h"
#include "MarcRecord.h"
#include "MarcWriter.h"
#include "MediaTypeUtil.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"
static unsigned modified_count(0);
static unsigned record_count(0);
const unsigned FIELD_MIN_NON_DATA_SIZE(4); // Indicator 1 + 2, unit separator and subfield code
void Usage() {
std::cerr << "Usage: " << ::progname << " master_marc_input norm_data_marc_input marc_output\n";
std::exit(EXIT_FAILURE);
}
std::string GetTag(const std::string &tag_and_subfields_spec) {
return tag_and_subfields_spec.substr(0, 3);
}
std::string GetSubfieldCodes(const std::string &tag_and_subfields_spec) {
return tag_and_subfields_spec.substr(3);
}
bool FilterPasses(const MarcRecord &record, const std::map<std::string, std::pair<std::string, std::string>> &filter_specs, const std::string &field_spec) {
auto filter_spec(filter_specs.find(field_spec));
if (filter_spec == filter_specs.cend())
return true;
auto rule(filter_spec->second);
// We have field_spec in key and rule to match in value
std::string subfield_codes(GetSubfieldCodes(rule.first));
if (subfield_codes.length() != 1)
Error("Invalid subfield specification " + subfield_codes + " for filter");
std::string subfield_value;
if ((subfield_value = record.extractFirstSubfield(GetTag(rule.first), subfield_codes.c_str()[0])).empty())
return false;
return subfield_value == rule.second;
}
void ExtractSynonyms(MarcReader * const authority_reader,
const std::set<std::string> &primary_tags_and_subfield_codes,
const std::set<std::string> &synonym_tags_and_subfield_codes,
std::vector<std::map<std::string, std::string>> * const synonym_maps,
const std::map<std::string, std::pair<std::string, std::string>> &filter_spec)
{
while (const MarcRecord record = authority_reader->read()) {
std::set<std::string>::const_iterator primary;
std::set<std::string>::const_iterator synonym;
unsigned int i(0);
for (primary = primary_tags_and_subfield_codes.begin(), synonym = synonym_tags_and_subfield_codes.begin();
primary != primary_tags_and_subfield_codes.end();
++primary, ++synonym, ++i)
{
// Fill maps with synonyms
std::vector<std::string> primary_values;
std::vector<std::string> synonym_values;
if (FilterPasses(record, filter_spec, *primary) and
record.extractSubfields(GetTag(*primary), GetSubfieldCodes(*primary), &primary_values) and
record.extractSubfields(GetTag(*synonym), GetSubfieldCodes(*synonym), &synonym_values))
(*synonym_maps)[i].emplace(StringUtil::Join(primary_values, ','),
StringUtil::Join(synonym_values, ','));
}
}
}
inline std::string GetMapValueOrEmptyString(const std::map<std::string, std::string> &map,
const std::string &searchterm)
{
auto value(map.find(searchterm));
return (value != map.cend()) ? value->second : "";
}
void ProcessRecord(MarcRecord * const record, const std::vector<std::map<std::string, std::string>> &synonym_maps,
const std::set<std::string> &primary_tags_and_subfield_codes,
const std::set<std::string> &output_tags_and_subfield_codes)
{
std::set<std::string>::const_iterator primary;
std::set<std::string>::const_iterator output;
unsigned int i(0);
bool modified_record(false);
if (primary_tags_and_subfield_codes.size() == output_tags_and_subfield_codes.size()) {
for (primary = primary_tags_and_subfield_codes.begin(), output = output_tags_and_subfield_codes.begin();
primary != primary_tags_and_subfield_codes.end();
++primary, ++output, ++i)
{
std::vector<std::string> primary_values;
std::set<std::string> synonym_values;
std::vector<size_t> field_indices;
if (record->getFieldIndices(GetTag(*primary), &field_indices) != MarcRecord::FIELD_NOT_FOUND) {
for (auto field_index : field_indices) {
primary_values.clear();
if (record->getSubfields(field_index).extractSubfields(GetSubfieldCodes(*primary), &primary_values)) {
std::string searchterm = StringUtil::Join(primary_values, ',');
// First case: Look up synonyms only in one category
if (i < synonym_maps.size()) {
const auto &synonym_map(synonym_maps[i]);
const auto synonym(GetMapValueOrEmptyString(synonym_map, searchterm));
if (not synonym.empty())
synonym_values.insert(synonym);
}
// Second case: Look up synonyms in all categories
else {
for (auto &synonym_map : synonym_maps) {
const auto &synonym(GetMapValueOrEmptyString(synonym_map, searchterm));
if (not synonym.empty())
synonym_values.insert(synonym);
}
}
}
}
if (synonym_values.empty())
continue;
// Insert synonyms
// Abort if field is already populated
std::string tag(GetTag(*output));
if (record->getFieldIndex(tag) != MarcRecord::FIELD_NOT_FOUND)
Error("Field with tag " + tag + " is not empty for PPN " + record->getControlNumber() + '\n');
std::string subfield_spec(GetSubfieldCodes(*output));
if (unlikely(subfield_spec.size() != 1))
Error("We currently only support a single subfield and thus specifying " + subfield_spec
+ " as output subfield is not valid\n");
std::string synonyms;
unsigned current_length(0);
unsigned indicator2(0);
for (auto synonym_it(synonym_values.cbegin()); synonym_it != synonym_values.cend(); /*Intentionally empty*/) {
if (indicator2 > 9)
Error ("Currently cannot handle synonyms with total length greater than " + std::to_string(9 * (MarcRecord::MAX_FIELD_LENGTH - FIELD_MIN_NON_DATA_SIZE)) + '\n');
if (current_length + synonym_it->length() < MarcRecord::MAX_FIELD_LENGTH - (FIELD_MIN_NON_DATA_SIZE + 3 /* consider " , " */)) {
bool synonyms_empty(synonyms.empty());
synonyms += (synonyms_empty ? *synonym_it : " , " + *synonym_it);
current_length += synonym_it->length() + (synonyms_empty ? 0 : 3);
++synonym_it;
} else {
if (not(record->insertSubfield(tag, subfield_spec[0], synonyms, '0', indicator2 + '0')))
Error("Could not insert field " + tag + " for PPN " + record->getControlNumber() + '\n');
synonyms.clear();
current_length = 0;
++indicator2;
modified_record = true;
}
}
// Write rest of data
if (not synonyms.empty()) {
if (not(record->insertSubfield(tag, subfield_spec[0], synonyms, '0', indicator2 + '0')))
Error("Could not insert field " + tag + " for PPN " + record->getControlNumber() + '\n');
modified_record = true;
}
}
}
if (modified_record)
++modified_count;
}
}
void InsertSynonyms(MarcReader * const marc_reader, MarcWriter * const marc_writer,
const std::set<std::string> &primary_tags_and_subfield_codes,
const std::set<std::string> &output_tags_and_subfield_codes,
std::vector<std::map<std::string, std::string>> &synonym_maps)
{
while (MarcRecord record = marc_reader->read()) {
ProcessRecord(&record, synonym_maps, primary_tags_and_subfield_codes, output_tags_and_subfield_codes);
marc_writer->write(record);
++record_count;
}
std::cerr << "Modified " << modified_count << " of " << record_count << " record(s).\n";
}
bool ParseSpec(std::string spec_str, std::set<std::string> * const field_specs, std::map<std::string, std::pair<std::string, std::string>> * filter_specs = nullptr) {
std::set<std::string> raw_field_specs;
if (unlikely(StringUtil::Split(spec_str, ':', &raw_field_specs) == 0)) {
Error("Need at least one field");
return false;
}
if (filter_specs == nullptr) {
*field_specs = raw_field_specs;
return true;
}
// Iterate over all Field-specs and extract possible filters
static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory("(\\d{1,3}[a-z]+)\\[(\\d{1,3}[a-z])=(.*)\\]"));
for (auto field_spec : raw_field_specs) {
if (matcher->matched(field_spec)) {
filter_specs->emplace((*matcher)[1], std::make_pair((*matcher)[2], (*matcher)[3]));
auto bracket = field_spec.find("[");
field_spec = (bracket != std::string::npos) ? field_spec.erase(bracket, field_spec.length()) : field_spec;
}
field_specs->insert(field_spec);
}
return true;
}
int main(int argc, char **argv) {
::progname = argv[0];
if (argc != 4)
Usage();
const std::string marc_input_filename(argv[1]);
const std::string authority_data_marc_input_filename(argv[2]);
const std::string marc_output_filename(argv[3]);
if (unlikely(marc_input_filename == marc_output_filename))
Error("Title data input file name equals output file name!");
if (unlikely(authority_data_marc_input_filename == marc_output_filename))
Error("Authority data input file name equals output file name!");
std::unique_ptr<MarcReader> marc_reader(MarcReader::Factory(marc_input_filename, MarcReader::BINARY));
std::unique_ptr<MarcReader> authority_reader(MarcReader::Factory(authority_data_marc_input_filename,
MarcReader::BINARY));
std::unique_ptr<MarcWriter> marc_writer(MarcWriter::Factory(marc_output_filename, MarcWriter::BINARY));
try {
// Determine possible mappings
// Values in square brackets specify a positive criterion for values to be taken into account
const std::string AUTHORITY_DATA_PRIMARY_SPEC("100abcd[079v=piz]:110abcd:111abcd:130abcd:150abcd:151abcd");
const std::string AUTHORITY_DATA_SYNONYM_SPEC("400abcd:410abcd:411abcd:430abcd:450abcd:451abcd");
const std::string TITLE_DATA_PRIMARY_SPEC("600abcd:610abcd:611abcd:630abcd:650abcd:651abcd:689abcd");
const std::string TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS("180a:181a:182a:183a:184a:185a:186a");
// Determine fields to handle
std::set<std::string> primary_tags_and_subfield_codes;
std::set<std::string> synonym_tags_and_subfield_codes;
std::set<std::string> input_tags_and_subfield_codes;
std::set<std::string> output_tags_and_subfield_codes;
std::map<std::string, std::pair<std::string, std::string>> filter_specs;
if (not unlikely(ParseSpec(AUTHORITY_DATA_PRIMARY_SPEC, &primary_tags_and_subfield_codes, &filter_specs)))
Error("Could not properly parse " + AUTHORITY_DATA_PRIMARY_SPEC);
if (unlikely(StringUtil::Split(AUTHORITY_DATA_SYNONYM_SPEC, ":", &synonym_tags_and_subfield_codes) == 0))
Error("Need at least one synonym field");
if (unlikely(StringUtil::Split(TITLE_DATA_PRIMARY_SPEC, ":", &input_tags_and_subfield_codes) == 0))
Error("Need at least one input field");
if (unlikely(StringUtil::Split(TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS, ":", &output_tags_and_subfield_codes)
== 0))
Error("Need at least one output field");
unsigned num_of_authority_entries(primary_tags_and_subfield_codes.size());
if (synonym_tags_and_subfield_codes.size() != num_of_authority_entries)
Error("Number of authority primary specs must match number of synonym specs");
if (input_tags_and_subfield_codes.size() != output_tags_and_subfield_codes.size())
Error("Number of fields title entry specs must match number of output specs");
std::vector<std::map<std::string, std::string>> synonym_maps(num_of_authority_entries,
std::map<std::string, std::string>());
// Extract the synonyms from authority data
ExtractSynonyms(authority_reader.get(), primary_tags_and_subfield_codes, synonym_tags_and_subfield_codes,
&synonym_maps, filter_specs);
// Iterate over the title data
InsertSynonyms(marc_reader.get(), marc_writer.get(), input_tags_and_subfield_codes,
output_tags_and_subfield_codes, synonym_maps);
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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 "ppapi/cpp/dev/find_dev.h"
#include "ppapi/c/dev/ppb_find_dev.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/module_impl.h"
namespace pp {
namespace {
static const char kPPPFindInterface[] = PPP_FIND_DEV_INTERFACE;
bool StartFind(PP_Instance instance,
const char* text,
bool case_sensitive) {
void* object =
pp::Instance::GetPerInstanceObject(instance, kPPPFindInterface);
if (!object)
return false;
return static_cast<Find_Dev*>(object)->StartFind(text, case_sensitive);
}
void SelectFindResult(PP_Instance instance, bool forward) {
void* object =
pp::Instance::GetPerInstanceObject(instance, kPPPFindInterface);
if (object)
static_cast<Find_Dev*>(object)->SelectFindResult(forward);
}
void StopFind(PP_Instance instance) {
void* object =
pp::Instance::GetPerInstanceObject(instance, kPPPFindInterface);
if (object)
static_cast<Find_Dev*>(object)->StopFind();
}
const PPP_Find_Dev ppp_find = {
&StartFind,
&SelectFindResult,
&StopFind
};
DeviceFuncs<PPB_Find_Dev> ppb_find_f(PPB_FIND_DEV_INTERFACE);
} // namespace
Find_Dev::Find_Dev(Instance* instance) : associated_instance_(instance) {
pp::Module::Get()->AddPluginInterface(kPPPFindInterface, this);
associated_instance_->AddPerInstanceObject(kPPPFindInterface, this);
}
Find_Dev::~Find_Dev() {
associated_instance_->RemovePerInstanceObject(kPPPFindInterface, this);
}
void Find_Dev::NumberOfFindResultsChanged(int32_t total, bool final_result) {
if (ppb_find_f) {
ppb_find_f->NumberOfFindResultsChanged(associated_instance_->pp_instance(),
total, final_result);
}
}
void Find_Dev::SelectedFindResultChanged(int32_t index) {
if (ppb_find_f) {
ppb_find_f->SelectedFindResultChanged(associated_instance_->pp_instance(),
index);
}
}
} // namespace pp
<commit_msg>Fix crash in new Find interface. Review URL: http://codereview.chromium.org/3295009<commit_after>// Copyright (c) 2010 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 "ppapi/cpp/dev/find_dev.h"
#include "ppapi/c/dev/ppb_find_dev.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/module_impl.h"
namespace pp {
namespace {
static const char kPPPFindInterface[] = PPP_FIND_DEV_INTERFACE;
bool StartFind(PP_Instance instance,
const char* text,
bool case_sensitive) {
void* object =
pp::Instance::GetPerInstanceObject(instance, kPPPFindInterface);
if (!object)
return false;
return static_cast<Find_Dev*>(object)->StartFind(text, case_sensitive);
}
void SelectFindResult(PP_Instance instance, bool forward) {
void* object =
pp::Instance::GetPerInstanceObject(instance, kPPPFindInterface);
if (object)
static_cast<Find_Dev*>(object)->SelectFindResult(forward);
}
void StopFind(PP_Instance instance) {
void* object =
pp::Instance::GetPerInstanceObject(instance, kPPPFindInterface);
if (object)
static_cast<Find_Dev*>(object)->StopFind();
}
const PPP_Find_Dev ppp_find = {
&StartFind,
&SelectFindResult,
&StopFind
};
DeviceFuncs<PPB_Find_Dev> ppb_find_f(PPB_FIND_DEV_INTERFACE);
} // namespace
Find_Dev::Find_Dev(Instance* instance) : associated_instance_(instance) {
pp::Module::Get()->AddPluginInterface(kPPPFindInterface, &ppp_find);
associated_instance_->AddPerInstanceObject(kPPPFindInterface, this);
}
Find_Dev::~Find_Dev() {
associated_instance_->RemovePerInstanceObject(kPPPFindInterface, this);
}
void Find_Dev::NumberOfFindResultsChanged(int32_t total, bool final_result) {
if (ppb_find_f) {
ppb_find_f->NumberOfFindResultsChanged(associated_instance_->pp_instance(),
total, final_result);
}
}
void Find_Dev::SelectedFindResultChanged(int32_t index) {
if (ppb_find_f) {
ppb_find_f->SelectedFindResultChanged(associated_instance_->pp_instance(),
index);
}
}
} // namespace pp
<|endoftext|> |
<commit_before>#include "QSettingsItemModel.h"
#include "xo/container/prop_node_tools.h"
using xo::prop_node;
using xo::settings;
std::string get_item_id( const QModelIndex& index )
{
QString id = index.data().toString();
for ( auto idx = index.parent(); idx.isValid(); idx = idx.parent() )
id = idx.data().toString() + "." + id;
return id.toStdString();
}
static std::pair< int, const prop_node* > find_parent_node( const prop_node* pn, const prop_node* child )
{
for ( int row = 0; row < pn->size(); ++row )
{
if ( &pn->get_child( row ) == child )
return std::make_pair( row, pn );
}
for ( auto& child_pair : *pn )
{
auto result = find_parent_node( &child_pair.second, child );
if ( result.second )
return result;
}
return std::pair< int, prop_node* >( -1, nullptr );
}
QModelIndex QSettingsItemModel::index( int row, int column, const QModelIndex &parent ) const
{
if ( parent.isValid() )
{
auto* pn = (prop_node*)parent.internalPointer();
auto* ch = &pn->get_child( pn->has_key( "label" ) ? row + 1 : row );
return createIndex( row, column, (void*)ch );
}
else if ( row < settings_.schema().size() )
return createIndex( row, column, (void*)&settings_.schema().get_child( row ) );
else return QModelIndex();
}
QModelIndex QSettingsItemModel::parent( const QModelIndex &child ) const
{
prop_node* pn = (prop_node*)child.internalPointer();
auto parent = find_parent_node( &settings_.schema(), pn );
if ( parent.second != &settings_.schema() )
return createIndex( parent.first, 0, (void*)parent.second );
else return QModelIndex();
}
int QSettingsItemModel::rowCount( const QModelIndex &parent ) const
{
if ( parent.isValid() )
{
auto* pn = reinterpret_cast<prop_node*>( parent.internalPointer() );
if ( pn->has_key( "default" ) )
return 0;
else if ( pn->has_key( "label" ) )
return (int)pn->size() - 1;
else return (int)pn->size();
}
else return (int)settings_.schema().size();
}
int QSettingsItemModel::columnCount( const QModelIndex &parent ) const
{
return 2;
}
QVariant QSettingsItemModel::data( const QModelIndex &index, int role ) const
{
if ( role == Qt::DisplayRole || role == Qt::EditRole )
{
auto* pn = reinterpret_cast<prop_node*>( index.internalPointer() );
auto parent = find_parent_node( &settings_.schema(), pn );
auto parent_key = parent.second->get_key( parent.first );
auto id = xo::find_query_to_node( &settings_.schema(), pn ).second;
if ( index.column() == 0 )
{
return QVariant( QString( pn->get< std::string >( "label", parent_key ).c_str() ) );
}
else if ( index.column() == 1 && pn->has_key( "default" ) )
{
return QVariant( QString( settings_.get< std::string >( id ).c_str() ) );
}
}
return QVariant();
}
bool QSettingsItemModel::setData( const QModelIndex &index, const QVariant &value, int role )
{
if ( role == Qt::EditRole )
{
auto* pn = reinterpret_cast<prop_node*>( index.internalPointer() );
auto id = xo::find_query_to_node( &settings_.schema(), pn ).second;
auto id_check = get_item_id( index );
settings_.set( id, value.toString().toStdString() );
return true;
}
else return false;
}
Qt::ItemFlags QSettingsItemModel::flags( const QModelIndex &index ) const
{
if ( !index.isValid() )
return 0;
else if ( index.column() == 1 )
return Qt::ItemIsEditable | QAbstractItemModel::flags( index );
else return QAbstractItemModel::flags( index );
}
QVariant QSettingsItemModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
if ( role != Qt::DisplayRole )
return QVariant();
switch ( section )
{
case 0: return tr( "Setting" );
case 1: return tr( "Value" );
default: return tr( "Whatever" );
}
}
<commit_msg>U: QSettingsItemModel::setData() returns false if conversion failed<commit_after>#include "QSettingsItemModel.h"
#include "xo/container/prop_node_tools.h"
using xo::prop_node;
using xo::settings;
std::string get_item_id( const QModelIndex& index )
{
QString id = index.data().toString();
for ( auto idx = index.parent(); idx.isValid(); idx = idx.parent() )
id = idx.data().toString() + "." + id;
return id.toStdString();
}
static std::pair< int, const prop_node* > find_parent_node( const prop_node* pn, const prop_node* child )
{
for ( int row = 0; row < pn->size(); ++row )
{
if ( &pn->get_child( row ) == child )
return std::make_pair( row, pn );
}
for ( auto& child_pair : *pn )
{
auto result = find_parent_node( &child_pair.second, child );
if ( result.second )
return result;
}
return std::pair< int, prop_node* >( -1, nullptr );
}
QModelIndex QSettingsItemModel::index( int row, int column, const QModelIndex &parent ) const
{
if ( parent.isValid() )
{
auto* pn = (prop_node*)parent.internalPointer();
auto* ch = &pn->get_child( pn->has_key( "label" ) ? row + 1 : row );
return createIndex( row, column, (void*)ch );
}
else if ( row < settings_.schema().size() )
return createIndex( row, column, (void*)&settings_.schema().get_child( row ) );
else return QModelIndex();
}
QModelIndex QSettingsItemModel::parent( const QModelIndex &child ) const
{
prop_node* pn = (prop_node*)child.internalPointer();
auto parent = find_parent_node( &settings_.schema(), pn );
if ( parent.second != &settings_.schema() )
return createIndex( parent.first, 0, (void*)parent.second );
else return QModelIndex();
}
int QSettingsItemModel::rowCount( const QModelIndex &parent ) const
{
if ( parent.isValid() )
{
auto* pn = reinterpret_cast<prop_node*>( parent.internalPointer() );
if ( pn->has_key( "default" ) )
return 0;
else if ( pn->has_key( "label" ) )
return (int)pn->size() - 1;
else return (int)pn->size();
}
else return (int)settings_.schema().size();
}
int QSettingsItemModel::columnCount( const QModelIndex &parent ) const
{
return 2;
}
QVariant QSettingsItemModel::data( const QModelIndex &index, int role ) const
{
if ( role == Qt::DisplayRole || role == Qt::EditRole )
{
auto* pn = reinterpret_cast<prop_node*>( index.internalPointer() );
auto parent = find_parent_node( &settings_.schema(), pn );
auto parent_key = parent.second->get_key( parent.first );
auto id = xo::find_query_to_node( &settings_.schema(), pn ).second;
if ( index.column() == 0 )
{
return QVariant( QString( pn->get< std::string >( "label", parent_key ).c_str() ) );
}
else if ( index.column() == 1 && pn->has_key( "default" ) )
{
return QVariant( QString( settings_.get< std::string >( id ).c_str() ) );
}
}
return QVariant();
}
bool QSettingsItemModel::setData( const QModelIndex &index, const QVariant &value, int role )
{
if ( role == Qt::EditRole )
{
auto* pn = reinterpret_cast<prop_node*>( index.internalPointer() );
auto id = xo::find_query_to_node( &settings_.schema(), pn ).second;
auto id_check = get_item_id( index );
return settings_.set( id, value.toString().toStdString() );
}
else return false;
}
Qt::ItemFlags QSettingsItemModel::flags( const QModelIndex &index ) const
{
if ( !index.isValid() )
return 0;
else if ( index.column() == 1 )
return Qt::ItemIsEditable | QAbstractItemModel::flags( index );
else return QAbstractItemModel::flags( index );
}
QVariant QSettingsItemModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
if ( role != Qt::DisplayRole )
return QVariant();
switch ( section )
{
case 0: return tr( "Setting" );
case 1: return tr( "Value" );
default: return tr( "Whatever" );
}
}
<|endoftext|> |
<commit_before>#ifndef CATCH_CONFIG_MAIN
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#endif
#ifndef __CATCH_HPP_INCLUDED
#define __CATCH_HPP_INCLUDED
#include "catch.hpp"
#endif
#include "cpp/common/globals.hpp"
#include "cpp/common/shader_loader.hpp"
#include "cpp/common/texture_loader.hpp"
#include "cpp/common/vboindexer.hpp"
#include "cpp/common/text2D.hpp"
#include "cpp/common/text3D.hpp"
#include "cpp/common/world.hpp"
#include "cpp/common/shader.hpp"
#include "cpp/common/material.hpp"
#include "cpp/common/font.hpp"
#include "cpp/common/glyph.hpp"
#include "cpp/common/species.hpp"
#include "cpp/common/object.hpp"
#include "cpp/common/triangulation.hpp"
#include "cpp/common/triangulation.cpp"
#include "cpp/common/heightmap_loader.hpp"
#include "cpp/common/heightmap_loader.cpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
#include <cmath> // std::isnan
#include <string>
#include <vector> // std::vector
TEST_CASE("SHADERSTRUCT must be initialized appropriately", "[SHADERSTRUCT]")
{
ShaderStruct test_shader_struct;
REQUIRE(test_shader_struct.parent_pointer == NULL);
REQUIRE(test_shader_struct.vertex_shader.empty());
REQUIRE(test_shader_struct.fragment_shader.empty());
}
TEST_CASE("MATERIALSTRUCT must be initialized appropriately", "[MATERIALSTRUCT]")
{
MaterialStruct test_material_struct;
REQUIRE(test_material_struct.parent_pointer == NULL);
REQUIRE(test_material_struct.texture_file_format.empty());
REQUIRE(test_material_struct.texture_filename.empty());
REQUIRE(test_material_struct.image_path.empty());
}
TEST_CASE("NODESTRUCT must be initialized appropriately", "[NODESTRUCT]")
{
NodeStruct test_node_struct;
REQUIRE(test_node_struct.parent_pointer == NULL);
REQUIRE(test_node_struct.coordinate_vector == glm::vec3(0.0f, 0.0f, 0.0f));
REQUIRE(test_node_struct.neighbor_nodeIDs.size() == 0);
}
TEST_CASE("OBJECTSTRUCT must be initialized appropriately", "[OBJECTSTRUCT]")
{
ObjectStruct test_object_struct;
REQUIRE(test_object_struct.species_parent_pointer == NULL);
REQUIRE(test_object_struct.glyph_parent_pointer == NULL);
REQUIRE(test_object_struct.original_scale_vector == glm::vec3(1.0f, 1.0f, 1.0f));
REQUIRE(std::isnan(test_object_struct.rotate_angle));
REQUIRE(test_object_struct.is_character == false);
REQUIRE(test_object_struct.coordinate_vector == glm::vec3(0.0f, 0.0f, 0.0f));
REQUIRE(test_object_struct.rotate_vector == glm::vec3(0.0f, 0.0f, 0.0f));
REQUIRE(test_object_struct.translate_vector == glm::vec3(0.0f, 0.0f, 0.0f));
}
TEST_CASE("SPECIESSTRUCT must be initialized appropriately", "[SPECIESSTRUCT]")
{
SpeciesStruct test_species_struct;
REQUIRE(test_species_struct.parent_pointer == NULL);
REQUIRE(test_species_struct.is_world == false);
REQUIRE(std::isnan(test_species_struct.world_radius));
REQUIRE(test_species_struct.model_file_format.empty());
REQUIRE(test_species_struct.model_filename.empty());
REQUIRE(test_species_struct.color_channel.empty());
REQUIRE(test_species_struct.light_position == glm::vec3(0.0f, 0.0f, 0.0f));
REQUIRE(test_species_struct.coordinate_system.empty());
}
TEST_CASE("FONTSTRUCT must be initialized appropriately", "[FONTSTRUCT]")
{
FontStruct test_font_struct;
REQUIRE(test_font_struct.parent_pointer == NULL);
REQUIRE(test_font_struct.vertex_scaling_factor == DEFAULT_VERTEX_SCALING_FACTOR);
REQUIRE(test_font_struct.font_file_format.empty());
REQUIRE(test_font_struct.font_filename.empty());
}
TEST_CASE("GLYPHSTRUCT must be initialized appropriately", "[GLYPHSTRUCT]")
{
GlyphStruct test_glyph_struct;
REQUIRE(test_glyph_struct.parent_pointer == NULL);
REQUIRE(test_glyph_struct.light_position == glm::vec3(0.0f, 0.0f, 0.0f));
}
TEST_CASE("3x3 BMP world must be loaded appropriately", "[load_3x3_BMP_world]")
{
std::string image_path = "test3x3.bmp";
std::vector<glm::vec3> out_vertices;
std::vector<glm::vec2> out_UVs;
std::vector<glm::vec3> out_normals;
GLuint image_width = 0;
GLuint image_height = 0;
std::string color_channel = "mean";
std::string triangulation_type = "bilinear_interpolation";
bool model_loading_result = model::load_BMP_world(
image_path,
*&out_vertices,
*&out_UVs,
*&out_normals,
*&image_width,
*&image_height,
color_channel,
triangulation_type);
#define N_VERTICES_FOR_FACE 3
#define N_FACES_FOR_BILINEAR_TRIANGULATION 4
#define N_WIDTH_OF_IMAGE_FILE 3
#define N_HEIGHT_OF_IMAGE_FILE 3
REQUIRE(out_vertices.size() == N_VERTICES_FOR_FACE * N_FACES_FOR_BILINEAR_TRIANGULATION * (N_WIDTH_OF_IMAGE_FILE - 1) * (N_HEIGHT_OF_IMAGE_FILE - 1));
REQUIRE(out_UVs.size() == N_VERTICES_FOR_FACE * N_FACES_FOR_BILINEAR_TRIANGULATION * (N_WIDTH_OF_IMAGE_FILE - 1) * (N_HEIGHT_OF_IMAGE_FILE - 1));
REQUIRE(out_normals.size() == N_VERTICES_FOR_FACE * N_FACES_FOR_BILINEAR_TRIANGULATION * (N_WIDTH_OF_IMAGE_FILE - 1) * (N_HEIGHT_OF_IMAGE_FILE - 1));
#undef N_VERTICES_FOR_FACE
#undef N_FACES_FOR_BILINEAR_TRIANGULATION
#undef N_WIDTH_OF_IMAGE_FILE
#undef N_HEIGHT_OF_IMAGE_FILE
}
TEST_CASE("256x256 BMP world must be loaded appropriately", "[load_256x256_BMP_world]")
{
std::string image_path = "noise256x256.bmp";
std::vector<glm::vec3> out_vertices;
std::vector<glm::vec2> out_UVs;
std::vector<glm::vec3> out_normals;
GLuint image_width = 0;
GLuint image_height = 0;
std::string color_channel = "mean";
std::string triangulation_type = "bilinear_interpolation";
bool model_loading_result = model::load_BMP_world(
image_path,
*&out_vertices,
*&out_UVs,
*&out_normals,
*&image_width,
*&image_height,
color_channel,
triangulation_type);
#define N_VERTICES_FOR_FACE 3
#define N_FACES_FOR_BILINEAR_TRIANGULATION 4
#define N_WIDTH_OF_IMAGE_FILE 256
#define N_HEIGHT_OF_IMAGE_FILE 256
REQUIRE(out_vertices.size() == N_VERTICES_FOR_FACE * N_FACES_FOR_BILINEAR_TRIANGULATION * (N_WIDTH_OF_IMAGE_FILE - 1) * (N_HEIGHT_OF_IMAGE_FILE - 1));
REQUIRE(out_UVs.size() == N_VERTICES_FOR_FACE * N_FACES_FOR_BILINEAR_TRIANGULATION * (N_WIDTH_OF_IMAGE_FILE - 1) * (N_HEIGHT_OF_IMAGE_FILE - 1));
REQUIRE(out_normals.size() == N_VERTICES_FOR_FACE * N_FACES_FOR_BILINEAR_TRIANGULATION * (N_WIDTH_OF_IMAGE_FILE - 1) * (N_HEIGHT_OF_IMAGE_FILE - 1));
#undef N_VERTICES_FOR_FACE
#undef N_FACES_FOR_BILINEAR_TRIANGULATION
#undef N_WIDTH_OF_IMAGE_FILE
#undef N_HEIGHT_OF_IMAGE_FILE
}
<commit_msg>Muokattu `TEST_CASE`:jen nimiä.<commit_after>#ifndef CATCH_CONFIG_MAIN
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#endif
#ifndef __CATCH_HPP_INCLUDED
#define __CATCH_HPP_INCLUDED
#include "catch.hpp"
#endif
#include "cpp/common/globals.hpp"
#include "cpp/common/shader_loader.hpp"
#include "cpp/common/texture_loader.hpp"
#include "cpp/common/vboindexer.hpp"
#include "cpp/common/text2D.hpp"
#include "cpp/common/text3D.hpp"
#include "cpp/common/world.hpp"
#include "cpp/common/shader.hpp"
#include "cpp/common/material.hpp"
#include "cpp/common/font.hpp"
#include "cpp/common/glyph.hpp"
#include "cpp/common/species.hpp"
#include "cpp/common/object.hpp"
#include "cpp/common/triangulation.hpp"
#include "cpp/common/triangulation.cpp"
#include "cpp/common/heightmap_loader.hpp"
#include "cpp/common/heightmap_loader.cpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
#include <cmath> // std::isnan
#include <string>
#include <vector> // std::vector
TEST_CASE("ShaderStruct must be initialized appropriately", "[ShaderStruct]")
{
ShaderStruct test_shader_struct;
REQUIRE(test_shader_struct.parent_pointer == NULL);
REQUIRE(test_shader_struct.vertex_shader.empty());
REQUIRE(test_shader_struct.fragment_shader.empty());
}
TEST_CASE("MaterialStruct must be initialized appropriately", "[MaterialStruct]")
{
MaterialStruct test_material_struct;
REQUIRE(test_material_struct.parent_pointer == NULL);
REQUIRE(test_material_struct.texture_file_format.empty());
REQUIRE(test_material_struct.texture_filename.empty());
REQUIRE(test_material_struct.image_path.empty());
}
TEST_CASE("NodeStruct must be initialized appropriately", "[NodeStruct]")
{
NodeStruct test_node_struct;
REQUIRE(test_node_struct.parent_pointer == NULL);
REQUIRE(test_node_struct.coordinate_vector == glm::vec3(0.0f, 0.0f, 0.0f));
REQUIRE(test_node_struct.neighbor_nodeIDs.size() == 0);
}
TEST_CASE("ObjectStruct must be initialized appropriately", "[ObjectStruct]")
{
ObjectStruct test_object_struct;
REQUIRE(test_object_struct.species_parent_pointer == NULL);
REQUIRE(test_object_struct.glyph_parent_pointer == NULL);
REQUIRE(test_object_struct.original_scale_vector == glm::vec3(1.0f, 1.0f, 1.0f));
REQUIRE(std::isnan(test_object_struct.rotate_angle));
REQUIRE(test_object_struct.is_character == false);
REQUIRE(test_object_struct.coordinate_vector == glm::vec3(0.0f, 0.0f, 0.0f));
REQUIRE(test_object_struct.rotate_vector == glm::vec3(0.0f, 0.0f, 0.0f));
REQUIRE(test_object_struct.translate_vector == glm::vec3(0.0f, 0.0f, 0.0f));
}
TEST_CASE("SpeciesStruct must be initialized appropriately", "[SpeciesStruct]")
{
SpeciesStruct test_species_struct;
REQUIRE(test_species_struct.parent_pointer == NULL);
REQUIRE(test_species_struct.is_world == false);
REQUIRE(std::isnan(test_species_struct.world_radius));
REQUIRE(test_species_struct.model_file_format.empty());
REQUIRE(test_species_struct.model_filename.empty());
REQUIRE(test_species_struct.color_channel.empty());
REQUIRE(test_species_struct.light_position == glm::vec3(0.0f, 0.0f, 0.0f));
REQUIRE(test_species_struct.coordinate_system.empty());
}
TEST_CASE("FontStruct must be initialized appropriately", "[FontStruct]")
{
FontStruct test_font_struct;
REQUIRE(test_font_struct.parent_pointer == NULL);
REQUIRE(test_font_struct.vertex_scaling_factor == DEFAULT_VERTEX_SCALING_FACTOR);
REQUIRE(test_font_struct.font_file_format.empty());
REQUIRE(test_font_struct.font_filename.empty());
}
TEST_CASE("GlyphStruct must be initialized appropriately", "[GlyphStruct]")
{
GlyphStruct test_glyph_struct;
REQUIRE(test_glyph_struct.parent_pointer == NULL);
REQUIRE(test_glyph_struct.light_position == glm::vec3(0.0f, 0.0f, 0.0f));
}
TEST_CASE("3x3 BMP world must be loaded appropriately", "[load_3x3_BMP_world]")
{
std::string image_path = "test3x3.bmp";
std::vector<glm::vec3> out_vertices;
std::vector<glm::vec2> out_UVs;
std::vector<glm::vec3> out_normals;
GLuint image_width = 0;
GLuint image_height = 0;
std::string color_channel = "mean";
std::string triangulation_type = "bilinear_interpolation";
bool model_loading_result = model::load_BMP_world(
image_path,
*&out_vertices,
*&out_UVs,
*&out_normals,
*&image_width,
*&image_height,
color_channel,
triangulation_type);
#define N_VERTICES_FOR_FACE 3
#define N_FACES_FOR_BILINEAR_TRIANGULATION 4
#define N_WIDTH_OF_IMAGE_FILE 3
#define N_HEIGHT_OF_IMAGE_FILE 3
REQUIRE(out_vertices.size() == N_VERTICES_FOR_FACE * N_FACES_FOR_BILINEAR_TRIANGULATION * (N_WIDTH_OF_IMAGE_FILE - 1) * (N_HEIGHT_OF_IMAGE_FILE - 1));
REQUIRE(out_UVs.size() == N_VERTICES_FOR_FACE * N_FACES_FOR_BILINEAR_TRIANGULATION * (N_WIDTH_OF_IMAGE_FILE - 1) * (N_HEIGHT_OF_IMAGE_FILE - 1));
REQUIRE(out_normals.size() == N_VERTICES_FOR_FACE * N_FACES_FOR_BILINEAR_TRIANGULATION * (N_WIDTH_OF_IMAGE_FILE - 1) * (N_HEIGHT_OF_IMAGE_FILE - 1));
#undef N_VERTICES_FOR_FACE
#undef N_FACES_FOR_BILINEAR_TRIANGULATION
#undef N_WIDTH_OF_IMAGE_FILE
#undef N_HEIGHT_OF_IMAGE_FILE
}
TEST_CASE("256x256 BMP world must be loaded appropriately", "[load_256x256_BMP_world]")
{
std::string image_path = "noise256x256.bmp";
std::vector<glm::vec3> out_vertices;
std::vector<glm::vec2> out_UVs;
std::vector<glm::vec3> out_normals;
GLuint image_width = 0;
GLuint image_height = 0;
std::string color_channel = "mean";
std::string triangulation_type = "bilinear_interpolation";
bool model_loading_result = model::load_BMP_world(
image_path,
*&out_vertices,
*&out_UVs,
*&out_normals,
*&image_width,
*&image_height,
color_channel,
triangulation_type);
#define N_VERTICES_FOR_FACE 3
#define N_FACES_FOR_BILINEAR_TRIANGULATION 4
#define N_WIDTH_OF_IMAGE_FILE 256
#define N_HEIGHT_OF_IMAGE_FILE 256
REQUIRE(out_vertices.size() == N_VERTICES_FOR_FACE * N_FACES_FOR_BILINEAR_TRIANGULATION * (N_WIDTH_OF_IMAGE_FILE - 1) * (N_HEIGHT_OF_IMAGE_FILE - 1));
REQUIRE(out_UVs.size() == N_VERTICES_FOR_FACE * N_FACES_FOR_BILINEAR_TRIANGULATION * (N_WIDTH_OF_IMAGE_FILE - 1) * (N_HEIGHT_OF_IMAGE_FILE - 1));
REQUIRE(out_normals.size() == N_VERTICES_FOR_FACE * N_FACES_FOR_BILINEAR_TRIANGULATION * (N_WIDTH_OF_IMAGE_FILE - 1) * (N_HEIGHT_OF_IMAGE_FILE - 1));
#undef N_VERTICES_FOR_FACE
#undef N_FACES_FOR_BILINEAR_TRIANGULATION
#undef N_WIDTH_OF_IMAGE_FILE
#undef N_HEIGHT_OF_IMAGE_FILE
}
<|endoftext|> |
<commit_before>
// (c) COPYRIGHT URI/MIT 1996
// Please read the full copyright statement in the file COPYRIGH.
//
// Authors:
// jhrg,jimg James Gallagher ([email protected])
#include "config_writedap.h"
static char rcsid[] not_used = {"$Id: name_map.cc,v 1.4 2004/02/06 00:49:59 jimg Exp $"};
#include <vector>
#include <string>
#include <Regex.h>
#include "escaping.h"
#include "name_map.h"
/* I expect this should really be here under UNIX also */
/* 10/2001 - rom. */
#ifdef WIN32
#include <assert.h>
#endif
name_map::name_map(char *raw_equiv)
{
_names.push_back(name_equiv(raw_equiv));
}
name_map::name_map()
{
}
void
name_map::add(char *raw_equiv)
{
name_equiv equiv(raw_equiv);
_names.push_back(equiv);
}
static string
munge(string name)
{
unsigned char ascii = *(name.substr(0, 1).data());
if (!isalpha(ascii)) name = "ml_" + name;
name = char2ASCII(name);
return char2ASCII(name, "[^A-Za-z0-9_]");
}
string
name_map::lookup(string name, const bool canonical_names)
{
string new_name = lookup(name);
if (!canonical_names)
return new_name;
else
return munge(new_name);
}
string
name_map::lookup(string name)
{
// NEItor is the name_eqiv const interator. 7/23/99 jhrg
for (NEItor p = _names.begin(); p != _names.end(); ++p)
if (name == p->from)
return p->to;
return name;
}
void
name_map::delete_all()
{
_names.erase(_names.begin(), _names.end());
}
#ifdef DODS_NAME_MAP_TEST
int
main(int argc, char *argv[])
{
name_map *nm = new name_map();
string res = nm->lookup("id.long", true);
cerr << "id.long" << ": " << res << endl;
res = nm->lookup("id$long", true);
cerr << "id$long" << ": " << res << endl;
res = nm->lookup("id%20long", true);
cerr << "id%20long" << ": " << res << endl;
delete nm;
}
#endif
// $Log: name_map.cc,v $
// Revision 1.4 2004/02/06 00:49:59 jimg
// Removed strstream include.
//
// Revision 1.3 2003/12/08 17:59:50 edavis
// Merge release-3-4 into trunk
//
// Revision 1.1.1.1 2003/10/22 19:43:33 dan
// Version of the Matlab CommandLine client which uses Matlab Structure
// variables to maintain the shape of the underlying DODS data.
// Revision 1.1.1.1.2.2 2003/10/29 19:03:21 dan
// Removed 'pragma interface' directive from all subclass
// source files.
//
// Revision 1.1.1.1.2.1 2003/10/27 16:48:59 dan
// Changed config include to 'config_writedap.h' to designate
// new version of 'writeval' now called 'writedap'. The only
// substantive change in 'writedap' is that nested sequence
// variables are now supported.
//
// Revision 1.2 2003/10/23 18:53:02 dan
// Changed config include to config_writedap.h from config_writeval.h
// This is to remain consistent with the renaming used from loaddods
// to loaddap. To support nested sequences writeval was modified
// to send an end-of-sequence marker to delimit sequence instances.
//
//
// Revision 1.10 2003/01/29 16:18:14 dan
// Merged with release-3-2-7
//
// Revision 1.9.2.4 2002/08/20 13:39:21 dan
// Added 'ml_' to beginning of variable names
// which need to be 'munged' to conform to the
// Matlab variable naming convention.
//
// Revision 1.9.2.3 2002/01/29 22:41:19 dan
// Removed function char2ASCII, this function is now included
// in the dap/escaping.cc code.
//
// Revision 1.9.2.2 2002/01/29 20:37:28 dan
// Modified char2ASCII to return Ascii characters representing
// the Hex numbers in the escaped string, and not their Ascii
// Decimal representation.
//
// Revision 1.9.2.1 2001/11/01 15:11:12 rmorris
// Added include of assert.h.
//
// Revision 1.9 2000/11/22 23:43:00 jimg
// Merge with pre-release 3.2
//
// Revision 1.6.2.3 2000/09/22 21:16:14 jimg
// Added char2ASCII function. Given a string, replace any characters that
// match the regular expression with `_<ASCII code>'. Changed the munge
// function so that it now calls char2ASCII() and not esc2underscore().
//
// Revision 1.8 2000/08/30 00:13:29 jimg
// Merged with 3.1.7
//
// Revision 1.6.2.2 2000/08/25 23:34:30 jimg
// Added a lookup(string) method that does only the thesaurus lookup and
// rewrite lookup(string, bool) to use it.
//
// Revision 1.6.2.1 2000/08/17 23:53:18 jimg
// Switched from config_dap.h to config_writedap.h.
//
// Revision 1.7 2000/07/21 10:21:56 rmorris
// Merged with win32-mlclient-branch.
//
// Revision 1.6 1999/07/24 00:10:07 jimg
// Repaired the munge function and removed SLList.
//
// Revision 1.5 1999/03/24 06:23:43 brent
// convert String.h to std lib <string>, convert to packages regex -- B^2
//
// Revision 1.4 1997/02/06 20:44:51 jimg
// Fixed log messages
//
// Revision 1.3 1997/01/10 06:50:30 jimg
// Added to lookup mfunc the ability to map non-alphanmerics to underscore.
//
// Revision 1.2 1996/11/23 05:17:39 jimg
// Added name_map() because g++ wants it.
//
// Revision 1.1 1996/11/22 23:52:01 jimg
// Created.
<commit_msg>Added ctype.h include.<commit_after>
// (c) COPYRIGHT URI/MIT 1996
// Please read the full copyright statement in the file COPYRIGH.
//
// Authors:
// jhrg,jimg James Gallagher ([email protected])
#include "config_writedap.h"
static char rcsid[] not_used = {"$Id: name_map.cc,v 1.5 2004/02/06 15:52:12 jimg Exp $"};
#include <ctype.h>
#include <vector>
#include <string>
#include <Regex.h>
#include "escaping.h"
#include "name_map.h"
/* I expect this should really be here under UNIX also */
/* 10/2001 - rom. */
#ifdef WIN32
#include <assert.h>
#endif
name_map::name_map(char *raw_equiv)
{
_names.push_back(name_equiv(raw_equiv));
}
name_map::name_map()
{
}
void
name_map::add(char *raw_equiv)
{
name_equiv equiv(raw_equiv);
_names.push_back(equiv);
}
static string
munge(string name)
{
unsigned char ascii = *(name.substr(0, 1).data());
if (!isalpha(ascii)) name = "ml_" + name;
name = char2ASCII(name);
return char2ASCII(name, "[^A-Za-z0-9_]");
}
string
name_map::lookup(string name, const bool canonical_names)
{
string new_name = lookup(name);
if (!canonical_names)
return new_name;
else
return munge(new_name);
}
string
name_map::lookup(string name)
{
// NEItor is the name_eqiv const interator. 7/23/99 jhrg
for (NEItor p = _names.begin(); p != _names.end(); ++p)
if (name == p->from)
return p->to;
return name;
}
void
name_map::delete_all()
{
_names.erase(_names.begin(), _names.end());
}
#ifdef DODS_NAME_MAP_TEST
int
main(int argc, char *argv[])
{
name_map *nm = new name_map();
string res = nm->lookup("id.long", true);
cerr << "id.long" << ": " << res << endl;
res = nm->lookup("id$long", true);
cerr << "id$long" << ": " << res << endl;
res = nm->lookup("id%20long", true);
cerr << "id%20long" << ": " << res << endl;
delete nm;
}
#endif
// $Log: name_map.cc,v $
// Revision 1.5 2004/02/06 15:52:12 jimg
// Added ctype.h include.
//
// Revision 1.4 2004/02/06 00:49:59 jimg
// Removed strstream include.
//
// Revision 1.3 2003/12/08 17:59:50 edavis
// Merge release-3-4 into trunk
//
// Revision 1.1.1.1 2003/10/22 19:43:33 dan
// Version of the Matlab CommandLine client which uses Matlab Structure
// variables to maintain the shape of the underlying DODS data.
// Revision 1.1.1.1.2.2 2003/10/29 19:03:21 dan
// Removed 'pragma interface' directive from all subclass
// source files.
//
// Revision 1.1.1.1.2.1 2003/10/27 16:48:59 dan
// Changed config include to 'config_writedap.h' to designate
// new version of 'writeval' now called 'writedap'. The only
// substantive change in 'writedap' is that nested sequence
// variables are now supported.
//
// Revision 1.2 2003/10/23 18:53:02 dan
// Changed config include to config_writedap.h from config_writeval.h
// This is to remain consistent with the renaming used from loaddods
// to loaddap. To support nested sequences writeval was modified
// to send an end-of-sequence marker to delimit sequence instances.
//
//
// Revision 1.10 2003/01/29 16:18:14 dan
// Merged with release-3-2-7
//
// Revision 1.9.2.4 2002/08/20 13:39:21 dan
// Added 'ml_' to beginning of variable names
// which need to be 'munged' to conform to the
// Matlab variable naming convention.
//
// Revision 1.9.2.3 2002/01/29 22:41:19 dan
// Removed function char2ASCII, this function is now included
// in the dap/escaping.cc code.
//
// Revision 1.9.2.2 2002/01/29 20:37:28 dan
// Modified char2ASCII to return Ascii characters representing
// the Hex numbers in the escaped string, and not their Ascii
// Decimal representation.
//
// Revision 1.9.2.1 2001/11/01 15:11:12 rmorris
// Added include of assert.h.
//
// Revision 1.9 2000/11/22 23:43:00 jimg
// Merge with pre-release 3.2
//
// Revision 1.6.2.3 2000/09/22 21:16:14 jimg
// Added char2ASCII function. Given a string, replace any characters that
// match the regular expression with `_<ASCII code>'. Changed the munge
// function so that it now calls char2ASCII() and not esc2underscore().
//
// Revision 1.8 2000/08/30 00:13:29 jimg
// Merged with 3.1.7
//
// Revision 1.6.2.2 2000/08/25 23:34:30 jimg
// Added a lookup(string) method that does only the thesaurus lookup and
// rewrite lookup(string, bool) to use it.
//
// Revision 1.6.2.1 2000/08/17 23:53:18 jimg
// Switched from config_dap.h to config_writedap.h.
//
// Revision 1.7 2000/07/21 10:21:56 rmorris
// Merged with win32-mlclient-branch.
//
// Revision 1.6 1999/07/24 00:10:07 jimg
// Repaired the munge function and removed SLList.
//
// Revision 1.5 1999/03/24 06:23:43 brent
// convert String.h to std lib <string>, convert to packages regex -- B^2
//
// Revision 1.4 1997/02/06 20:44:51 jimg
// Fixed log messages
//
// Revision 1.3 1997/01/10 06:50:30 jimg
// Added to lookup mfunc the ability to map non-alphanmerics to underscore.
//
// Revision 1.2 1996/11/23 05:17:39 jimg
// Added name_map() because g++ wants it.
//
// Revision 1.1 1996/11/22 23:52:01 jimg
// Created.
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File AdvectionDiffusionReactionSolver.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Advection Diffusion Reaction solver
//
///////////////////////////////////////////////////////////////////////////////
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <../solvers_new/Auxiliary/AdvectionDiffusionReaction.h>
using namespace Nektar;
int main(int argc, char *argv[])
{
ASSERTL0(argc == 2,"\n \t Usage: AdvectionDiffusionReactionSolver meshfile \n");
string fileNameString(argv[1]);
//----------------------------------------------------------------
// Read the mesh and construct container class
AdvectionDiffusionReaction dom(fileNameString);
int nsteps = dom.GetSteps();
// Set up the intial conditions -- Could put in initialisation??
dom.SetInitialConditions();
// Integrate from start time to end time
dom.ExplicitlyIntegrateAdvection(nsteps);
// Dump output
dom.Output();
cout << "L2 Error: " << dom.L2Error(0) << endl;
}
/**
* $Log $
**/
<commit_msg>Added a Summary method<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File AdvectionDiffusionReactionSolver.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Advection Diffusion Reaction solver
//
///////////////////////////////////////////////////////////////////////////////
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <../solvers_new/Auxiliary/AdvectionDiffusionReaction.h>
using namespace Nektar;
int main(int argc, char *argv[])
{
ASSERTL0(argc == 2,"\n \t Usage: AdvectionDiffusionReactionSolver meshfile \n");
string fileNameString(argv[1]);
//----------------------------------------------------------------
// Read the mesh and construct container class
AdvectionDiffusionReaction dom(fileNameString);
int nsteps = dom.GetSteps();
dom.Summary(cout);
// Set up the intial conditions -- Could put in initialisation??
dom.SetInitialConditions();
// Integrate from start time to end time
dom.ExplicitlyIntegrateAdvection(nsteps);
// Dump output
dom.Output();
cout << "L2 Error: " << dom.L2Error(0) << endl;
}
/**
* $Log $
**/
<|endoftext|> |
<commit_before>#ifndef SERIALIZER_HPP
#define SERIALIZER_HPP
#include <string>
#include <cstddef> // size_t
#include "cppa/uniform_type_info.hpp"
#include "cppa/detail/to_uniform_name.hpp"
namespace cppa {
// forward declaration
class primitive_variant;
class serializer
{
public:
virtual ~serializer();
virtual void begin_object(const std::string& type_name) = 0;
virtual void end_object() = 0;
virtual void begin_sequence(size_t size) = 0;
virtual void end_sequence() = 0;
/**
* @brief Writes a single value.
*/
virtual void write_value(const primitive_variant& value) = 0;
/**
* @brief Writes @p size values.
*/
virtual void write_tuple(size_t size, const primitive_variant* values) = 0;
};
template<typename T>
serializer& operator<<(serializer& s, const T& what)
{
auto mtype = uniform_typeid<T>();
if (mtype == nullptr)
{
throw std::logic_error( "no uniform type info found for "
+ cppa::detail::to_uniform_name(typeid(T)));
}
mtype->serialize(&what, &s);
return s;
}
} // namespace cppa
#endif // SERIALIZER_HPP
<commit_msg>noncopyable serializer<commit_after>#ifndef SERIALIZER_HPP
#define SERIALIZER_HPP
#include <string>
#include <cstddef> // size_t
#include "cppa/uniform_type_info.hpp"
#include "cppa/detail/to_uniform_name.hpp"
namespace cppa {
// forward declaration
class primitive_variant;
class serializer
{
serializer(const serializer&) = delete;
serializer& operator=(const serializer&) = delete;
public:
serializer() = default;
virtual ~serializer();
virtual void begin_object(const std::string& type_name) = 0;
virtual void end_object() = 0;
virtual void begin_sequence(size_t size) = 0;
virtual void end_sequence() = 0;
/**
* @brief Writes a single value.
*/
virtual void write_value(const primitive_variant& value) = 0;
/**
* @brief Writes @p size values.
*/
virtual void write_tuple(size_t size, const primitive_variant* values) = 0;
};
template<typename T>
serializer& operator<<(serializer& s, const T& what)
{
auto mtype = uniform_typeid<T>();
if (mtype == nullptr)
{
throw std::logic_error( "no uniform type info found for "
+ cppa::detail::to_uniform_name(typeid(T)));
}
mtype->serialize(&what, &s);
return s;
}
} // namespace cppa
#endif // SERIALIZER_HPP
<|endoftext|> |
<commit_before>#include <iostream>
// #include <cstring>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include "thor/PrimitiveTypes.h"
#include "thor/lang/Language.h"
#include "thor/lang/String.h"
#include "thor/container/Vector.h"
using namespace thor;
namespace
{
void draw_background(SDL_Renderer *renderer, int w, int h)
{
SDL_Color col[2] = {
{ 0x66, 0x66, 0x66, 0xff },
{ 0x99, 0x99, 0x99, 0xff },
};
int i, x, y;
SDL_Rect rect;
rect.w = 8;
rect.h = 8;
for (y = 0; y < h; y += rect.h) {
for (x = 0; x < w; x += rect.w) {
/* use an 8x8 checkerboard pattern */
i = (((x ^ y) >> 3) & 1);
SDL_SetRenderDrawColor(renderer, col[i].r, col[i].g, col[i].b, col[i].a);
rect.x = x;
rect.y = y;
SDL_RenderFillRect(renderer, &rect);
}
}
}
}
namespace imgutil
{
class Image : thor::lang::Object
{
public:
using PixCont = thor::container::Vector<int32>;
Image();
~Image();
bool load(thor::lang::String* filename);
PixCont* getAllPixels();
void setAllPixels(PixCont* pixs);
SDL_Surface *surface;
};
Image::Image() : surface(nullptr)
{
}
Image::~Image()
{
}
bool Image::load(thor::lang::String* filename)
{
char cfilename[64];
wcstombs(cfilename, filename->data->c_str(), sizeof(cfilename));
surface = IMG_Load(cfilename);
return surface != nullptr;
}
auto Image::getAllPixels() -> PixCont*
{
int w = surface->w;
int h = surface->h;
int total = w*h;
int* ori_pixs = reinterpret_cast<int*>(surface->pixels);
// FIXME: instead of total, create() always get a UINT_MAX...WTF?
// PixCont* pixs = PixCont::create(static_cast<int64>(total));
PixCont* pixs = PixCont::create();
for(int i = 0; i < total; ++i)
{
int val = *ori_pixs;
// pixs->set(i, val);
pixs->pushBack(val);
++ori_pixs;
}
return pixs;
}
void Image::setAllPixels(PixCont* pixs)
{
int w = surface->w;
int h = surface->h;
int total = w*h;
int* ori_pixs = reinterpret_cast<int*>(surface->pixels);
for(int i = 0; i < total; ++i)
{
int val = pixs->get(i);
*ori_pixs = val;
++ori_pixs;
}
}
class Window : thor::lang::Object
{
public:
Window(int32 x, int32 y);
~Window();
bool isQuit();
void handleEvent();
void showImage(Image* img);
private:
SDL_Window *_window;
SDL_Renderer *_render;
SDL_Texture *_texture;
bool _quit;
};
Window::Window(int32 x, int32 y) :
_window(nullptr),
_render(nullptr),
_texture(nullptr),
_quit(false)
{
SDL_CreateWindowAndRenderer(0, 0, 0, &_window, &_render);
SDL_SetWindowPosition(_window, 0, 0);
SDL_SetWindowTitle(_window, "Thorlang Monochrome");
}
Window::~Window()
{
}
bool Window::isQuit()
{
return _quit;
}
void Window::handleEvent()
{
SDL_Event event;
while(SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_KEYUP:
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
_quit = 1;
default:
break;
}
break;
case SDL_QUIT:
_quit = 1;
break;
default:
break;
}
}
}
void Window::showImage(Image* img)
{
int w, h;
_texture = SDL_CreateTextureFromSurface(_render, img->surface);
SDL_QueryTexture(_texture, nullptr, nullptr, &w, &h);
SDL_SetWindowSize(_window, w, h);
draw_background(_render, w, h);
SDL_RenderCopy(_render, _texture, nullptr, nullptr);
SDL_RenderPresent(_render);
SDL_ShowWindow(_window);
}
bool initialize()
{
int result = SDL_Init(SDL_INIT_VIDEO);
return result == 0;
}
void finalize()
{
SDL_Quit();
}
}
<commit_msg>Fix: pulic inherit to thor::lang::Object<commit_after>#include <iostream>
// #include <cstring>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include "thor/PrimitiveTypes.h"
#include "thor/lang/Language.h"
#include "thor/lang/String.h"
#include "thor/container/Vector.h"
using namespace thor;
namespace
{
void draw_background(SDL_Renderer *renderer, int w, int h)
{
SDL_Color col[2] = {
{ 0x66, 0x66, 0x66, 0xff },
{ 0x99, 0x99, 0x99, 0xff },
};
int i, x, y;
SDL_Rect rect;
rect.w = 8;
rect.h = 8;
for (y = 0; y < h; y += rect.h) {
for (x = 0; x < w; x += rect.w) {
/* use an 8x8 checkerboard pattern */
i = (((x ^ y) >> 3) & 1);
SDL_SetRenderDrawColor(renderer, col[i].r, col[i].g, col[i].b, col[i].a);
rect.x = x;
rect.y = y;
SDL_RenderFillRect(renderer, &rect);
}
}
}
}
namespace imgutil
{
class Image : public thor::lang::Object
{
public:
using PixCont = thor::container::Vector<int32>;
Image();
~Image();
bool load(thor::lang::String* filename);
PixCont* getAllPixels();
void setAllPixels(PixCont* pixs);
SDL_Surface *surface;
};
Image::Image() : surface(nullptr)
{
}
Image::~Image()
{
}
bool Image::load(thor::lang::String* filename)
{
char cfilename[64];
wcstombs(cfilename, filename->data->c_str(), sizeof(cfilename));
surface = IMG_Load(cfilename);
return surface != nullptr;
}
auto Image::getAllPixels() -> PixCont*
{
int w = surface->w;
int h = surface->h;
int total = w*h;
int* ori_pixs = reinterpret_cast<int*>(surface->pixels);
// FIXME: instead of total, create() always get a UINT_MAX...WTF?
// PixCont* pixs = PixCont::create(static_cast<int64>(total));
PixCont* pixs = PixCont::create();
for(int i = 0; i < total; ++i)
{
int val = *ori_pixs;
// pixs->set(i, val);
pixs->pushBack(val);
++ori_pixs;
}
return pixs;
}
void Image::setAllPixels(PixCont* pixs)
{
int w = surface->w;
int h = surface->h;
int total = w*h;
int* ori_pixs = reinterpret_cast<int*>(surface->pixels);
for(int i = 0; i < total; ++i)
{
int val = pixs->get(i);
*ori_pixs = val;
++ori_pixs;
}
}
class Window : public thor::lang::Object
{
public:
Window(int32 x, int32 y);
~Window();
bool isQuit();
void handleEvent();
void showImage(Image* img);
private:
SDL_Window *_window;
SDL_Renderer *_render;
SDL_Texture *_texture;
bool _quit;
};
Window::Window(int32 x, int32 y) :
_window(nullptr),
_render(nullptr),
_texture(nullptr),
_quit(false)
{
SDL_CreateWindowAndRenderer(0, 0, 0, &_window, &_render);
SDL_SetWindowPosition(_window, 0, 0);
SDL_SetWindowTitle(_window, "Thorlang Monochrome");
}
Window::~Window()
{
}
bool Window::isQuit()
{
return _quit;
}
void Window::handleEvent()
{
SDL_Event event;
while(SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_KEYUP:
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
_quit = 1;
default:
break;
}
break;
case SDL_QUIT:
_quit = 1;
break;
default:
break;
}
}
}
void Window::showImage(Image* img)
{
int w, h;
_texture = SDL_CreateTextureFromSurface(_render, img->surface);
SDL_QueryTexture(_texture, nullptr, nullptr, &w, &h);
SDL_SetWindowSize(_window, w, h);
draw_background(_render, w, h);
SDL_RenderCopy(_render, _texture, nullptr, nullptr);
SDL_RenderPresent(_render);
SDL_ShowWindow(_window);
}
bool initialize()
{
int result = SDL_Init(SDL_INIT_VIDEO);
return result == 0;
}
void finalize()
{
SDL_Quit();
}
}
<|endoftext|> |
<commit_before>///
/// @file pi_meissel.cpp
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include "pmath.hpp"
#include <primecount.hpp>
#include <algorithm>
#include <stdint.h>
#ifdef _OPENMP
#include <omp.h>
#include "get_omp_threads.hpp"
#endif
using std::max;
namespace primecount {
/// Calculate the number of primes below x using Meissel's formula.
/// Run time: O(x/(log x)^3) operations, O(x^0.5 / log x) space.
///
int64_t pi_meissel(int64_t x, int threads)
{
if (x < 2)
return 0;
int64_t x13 = iroot<3>(x);
int64_t a = pi_legendre(x13, 1);
int64_t phi_xa, p2;
#ifdef _OPENMP
omp_set_nested(true);
threads = get_omp_threads(threads);
#pragma omp parallel sections num_threads(threads)
{
#pragma omp section
phi_xa = phi(x, a, max(1, threads - 1));
#pragma omp section
p2 = P2(x, a, x13);
}
#else
phi_xa = phi(x, a, threads);
p2 = P2(x, a, x13);
#endif
int64_t sum = phi_xa + a - 1 - p2;
return sum;
}
} // namespace primecount
<commit_msg>Signature of P2(x, a) modified<commit_after>///
/// @file pi_meissel.cpp
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include "pmath.hpp"
#include <primecount.hpp>
#include <algorithm>
#include <stdint.h>
#ifdef _OPENMP
#include <omp.h>
#include "get_omp_threads.hpp"
#endif
using std::max;
namespace primecount {
/// Calculate the number of primes below x using Meissel's formula.
/// Run time: O(x/(log x)^3) operations, O(x^0.5 / log x) space.
///
int64_t pi_meissel(int64_t x, int threads)
{
if (x < 2)
return 0;
int64_t x13 = iroot<3>(x);
int64_t a = pi_legendre(x13, 1);
int64_t phi_xa, p2;
#ifdef _OPENMP
omp_set_nested(true);
threads = get_omp_threads(threads);
#pragma omp parallel sections num_threads(threads)
{
#pragma omp section
phi_xa = phi(x, a, max(1, threads - 1));
#pragma omp section
p2 = P2(x, a);
}
#else
phi_xa = phi(x, a, threads);
p2 = P2(x, a);
#endif
int64_t sum = phi_xa + a - 1 - p2;
return sum;
}
} // namespace primecount
<|endoftext|> |
<commit_before>#include "ts/ts.h"
using namespace cv;
namespace {
TEST(MatAssertionsTest, MatFEq) {
const int R = 3;
const int C = 2;
Mat a = Mat::zeros(R, C, CV_32FC1);
Mat b = Mat::zeros(R, C, CV_32FC1);
EXPECT_EQ(a.rows, R) << "No. of rows do not match.";
EXPECT_EQ(a.cols, C) << "No. of columns do not match.";
EXPECT_EQ(a.rows, b.rows) << "No. of rows do not match.";
EXPECT_EQ(a.cols, b.cols) << "No. of columns do not match.";
EXPECT_EQ(a.total(), b.total()) << "No. of elements do not match.";
EXPECT_EQ(a.total(), R*C) << "No. of elements do not match.";
EXPECT_TRUE( EqualDims(a, b) );
EXPECT_MAT_DIMS_EQ(a, b);
for(int r=0; r<R; r++) {
for(int c=0; c<C; c++) {
EXPECT_FLOAT_EQ(a.at<float>(r, c), 0.f);
EXPECT_FLOAT_EQ(b.at<float>(r, c), 0.f);
EXPECT_FLOAT_EQ(a.at<float>(r, c), b.at<float>(r, c));
}
}
EXPECT_TRUE( Equal(a, b) );
EXPECT_MAT_EQ(a, b);
}
TEST(MatAssertionsTest, MatFNotEq) {
const int R=3, C=2;
Mat a = Mat::zeros(R, C, CV_32FC1);
Mat b = Mat::ones(R, C, CV_32FC1);
EXPECT_MAT_DIMS_EQ(a, b);
EXPECT_FALSE( Equal(a, b) );
}
TEST(MatAssertionsTest, MatFNotEqDims) {
Mat a = Mat::zeros(3, 2, CV_32FC1);
Mat b = Mat::ones(2, 3, CV_32FC1);
EXPECT_FALSE( EqualDims(a, b) );
EXPECT_FALSE( Equal(a, b) );
}
TEST(MatAssertionsTest, FailureMessage) {
Mat a = Mat::zeros(3, 2, CV_32FC1);
Mat b = Mat::ones(3, 2, CV_32FC1);
Mat cmp_out;
compare(a, b, cmp_out, CMP_NE);
EXPECT_GT( MatFailureMessageNonZero(a, b, cmp_out).size(), 0) << "Failure message is empty";
}
} // namespace
<commit_msg>add brief description to tests<commit_after>#include "ts/ts.h"
using namespace cv;
namespace {
/**
* @brief test OpenCV Mat Assertions with 2 Mats of float (equal dims and elem. values)
*/
TEST(MatAssertionsTest, MatFEq) {
const int R = 3;
const int C = 2;
Mat a = Mat::zeros(R, C, CV_32FC1);
Mat b = Mat::zeros(R, C, CV_32FC1);
EXPECT_EQ(a.rows, R) << "No. of rows do not match.";
EXPECT_EQ(a.cols, C) << "No. of columns do not match.";
EXPECT_EQ(a.rows, b.rows) << "No. of rows do not match.";
EXPECT_EQ(a.cols, b.cols) << "No. of columns do not match.";
EXPECT_EQ(a.total(), b.total()) << "No. of elements do not match.";
EXPECT_EQ(a.total(), R*C) << "No. of elements do not match.";
EXPECT_TRUE( EqualDims(a, b) );
EXPECT_MAT_DIMS_EQ(a, b);
for(int r=0; r<R; r++) {
for(int c=0; c<C; c++) {
EXPECT_FLOAT_EQ(a.at<float>(r, c), 0.f);
EXPECT_FLOAT_EQ(b.at<float>(r, c), 0.f);
EXPECT_FLOAT_EQ(a.at<float>(r, c), b.at<float>(r, c));
}
}
EXPECT_TRUE( Equal(a, b) );
EXPECT_MAT_EQ(a, b);
}
/**
* @brief test OpenCV Mat Assertions with 2 Mats of float (equal dims, non-equal elem. values)
*/
TEST(MatAssertionsTest, MatFNotEq) {
const int R=3, C=2;
Mat a = Mat::zeros(R, C, CV_32FC1);
Mat b = Mat::ones(R, C, CV_32FC1);
EXPECT_MAT_DIMS_EQ(a, b);
EXPECT_FALSE( Equal(a, b) );
}
/**
* @brief test OpenCV Mat Assertions with 2 Mats of float (equal dims, single value different)
*/
TEST(MatAssertionsTest, MatFNotEqSingleEl) {
const int R=3, C=2;
Mat a = Mat::ones(R, C, CV_32FC1);
for(int r=0; r<R; r++) {
for(int c=0; c<C; c++) {
Mat b = a.clone();
EXPECT_MAT_DIMS_EQ(a, b);
EXPECT_MAT_EQ(a, b);
b.at<float>(r, c) += 123;
EXPECT_FALSE( Equal(a, b) );
}
}
}
/**
* @brief test OpenCV Mat Assertions with 2 Mats of float (non-equal dims, non-equal elem. values)
*/
TEST(MatAssertionsTest, MatFNotEqDims) {
Mat a = Mat::zeros(3, 2, CV_32FC1);
Mat b = Mat::ones(2, 3, CV_32FC1);
EXPECT_FALSE( EqualDims(a, b) );
EXPECT_FALSE( Equal(a, b) );
}
/**
* @brief test OpenCV Mat Assertions with 2 Mats of float (non-equal dims, equal elem. values)
*/
TEST(MatAssertionsTest, MatFNotEqDimsAllZeros) {
Mat a = Mat::zeros(3, 2, CV_32FC1);
Mat b = Mat::zeros(2, 3, CV_32FC1);
EXPECT_FALSE( EqualDims(a, b) );
EXPECT_FALSE( Equal(a, b) );
}
/**
* @brief test failure message
*/
TEST(MatAssertionsTest, FailureMessage) {
Mat a = Mat::zeros(3, 2, CV_32FC1);
Mat b = Mat::ones(3, 2, CV_32FC1);
Mat cmp_out;
compare(a, b, cmp_out, CMP_NE);
EXPECT_GT( MatFailureMessageNonZero(a, b, cmp_out).size(), 0) << "Failure message is empty";
}
} // namespace
<|endoftext|> |
<commit_before>/*
Copyright (c) 2018, Richard Eakin - All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE 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 "mason/RenderToTexture.h"
#include "cinder/Log.h"
#include "cinder/gl/Context.h"
#include "cinder/gl/scoped.h"
using namespace ci;
using namespace std;
namespace mason {
RenderToTexture::RenderToTexture( const ci::ivec2 &size )
{
if( size.x > 0 && size.y > 0 ) {
setSize( size );
}
}
void RenderToTexture::setSize( const ci::ivec2 &size )
{
ivec2 clampedSize = ivec2( max<int>( 1, size.x ), max<int>( 1, size.y ) );
if( mFbo && mFbo->getSize() == clampedSize )
return;
// TODO: expose params as a setter and / or format
auto fboFormat = gl::Fbo::Format();
fboFormat.colorTexture(
gl::Texture2d::Format()
.internalFormat( GL_RGBA )
.minFilter( GL_LINEAR ).magFilter( GL_LINEAR )
);
fboFormat.samples( 8 );
mFbo = gl::Fbo::create( clampedSize.x, clampedSize.y, fboFormat );
}
ci::ivec2 RenderToTexture::getSize() const
{
if( ! mFbo )
return { 0, 0 };
return mFbo->getSize();
}
ci::gl::Texture2dRef RenderToTexture::getTexture() const
{
if( ! mFbo )
return {};
return mFbo->getColorTexture();
}
void RenderToTexture::render()
{
if( ! mFbo )
return;
const ivec2 size = mFbo->getSize();
gl::ScopedFramebuffer fboScope( mFbo );
gl::ScopedViewport viewportScope( size );
gl::ScopedMatrices matScope;
gl::setMatricesWindow( size );
gl::clear( ColorA::zero() );
mSignalDraw.emit();
}
} // namespace mason
<commit_msg>temp disable loadTopDown(), will add params to this later<commit_after>/*
Copyright (c) 2018, Richard Eakin - All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE 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 "mason/RenderToTexture.h"
#include "cinder/Log.h"
#include "cinder/gl/Context.h"
#include "cinder/gl/scoped.h"
using namespace ci;
using namespace std;
namespace mason {
RenderToTexture::RenderToTexture( const ci::ivec2 &size )
{
if( size.x > 0 && size.y > 0 ) {
setSize( size );
}
}
void RenderToTexture::setSize( const ci::ivec2 &size )
{
ivec2 clampedSize = ivec2( max<int>( 1, size.x ), max<int>( 1, size.y ) );
if( mFbo && mFbo->getSize() == clampedSize )
return;
// TODO: expose params as a setter and / or format
auto fboFormat = gl::Fbo::Format();
fboFormat.colorTexture(
gl::Texture2d::Format()
.internalFormat( GL_RGBA )
.minFilter( GL_LINEAR ).magFilter( GL_LINEAR )
//.loadTopDown()
);
fboFormat.samples( 8 );
mFbo = gl::Fbo::create( clampedSize.x, clampedSize.y, fboFormat );
}
ci::ivec2 RenderToTexture::getSize() const
{
if( ! mFbo )
return { 0, 0 };
return mFbo->getSize();
}
ci::gl::Texture2dRef RenderToTexture::getTexture() const
{
if( ! mFbo )
return {};
return mFbo->getColorTexture();
}
void RenderToTexture::render()
{
if( ! mFbo )
return;
const ivec2 size = mFbo->getSize();
gl::ScopedFramebuffer fboScope( mFbo );
gl::ScopedViewport viewportScope( size );
gl::ScopedMatrices matScope;
bool mOriginUpperLeft = false; // TODO: expose param
gl::setMatricesWindow( size, mOriginUpperLeft );
gl::clear( ColorA::zero() );
mSignalDraw.emit();
}
} // namespace mason
<|endoftext|> |
<commit_before>// XRUN: %clang_cc1 -emit-pch -o %t.1.ast %S/Inputs/class1.cpp
// XRUN: %clang_cc1 -emit-pch -o %t.2.ast %S/Inputs/class2.cpp
// XRUN: %clang_cc1 -ast-merge %t.1.ast -ast-merge %t.2.ast -fsyntax-only %s 2>&1 | FileCheck %s
// CHECK: class1.cpp:5:8: warning: type 'B' has incompatible definitions in different translation units
// CHECK: class1.cpp:6:9: note: field 'y' has type 'float' here
// CHECK: class2.cpp:6:7: note: field 'y' has type 'int' here
// FIXME: we should also complain about mismatched types on the method
<commit_msg>Try to disable this again.<commit_after>// RUN: %clang_cc1 -emit-pch -o %t.1.ast %S/Inputs/class1.cpp
// RUN: %clang_cc1 -emit-pch -o %t.2.ast %S/Inputs/class2.cpp
// RUN: %clang_cc1 -ast-merge %t.1.ast -ast-merge %t.2.ast -fsyntax-only %s 2>&1 | FileCheck %s
// RUN: false
// XFAIL: *
// CHECK: class1.cpp:5:8: warning: type 'B' has incompatible definitions in different translation units
// CHECK: class1.cpp:6:9: note: field 'y' has type 'float' here
// CHECK: class2.cpp:6:7: note: field 'y' has type 'int' here
// FIXME: we should also complain about mismatched types on the method
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef HW_SERIAL_HPP
#define HW_SERIAL_HPP
//#define DEBUG
#include <os>
#include <hw/ioport.hpp>
#include <kernel/irq_manager.hpp>
namespace hw{
class Serial {
public:
/** On Data handler. Return value indicates if the buffer should be flushed **/
using on_data_handler = delegate<void(char c)>;
using on_string_handler = delegate<void(const std::string s)>;
using irq_delg = IRQ_manager::irq_delegate;
template <uint16_t PORT>
static Serial& port(){
static Serial s{PORT};
return s;
}
void on_data(on_data_handler del);
void on_readline(on_string_handler del, char delim = '\r');
void enable_interrupt();
void disable_interrupt();
char read();
void write(char c);
int received();
int is_transmit_empty();
// We don't want copies
Serial( Serial& ) = delete;
Serial( Serial&& ) = delete;
Serial& operator=(Serial&) = delete;
Serial operator=(Serial&&) = delete;
void init();
private:
Serial(int port);
static constexpr uint16_t ports_[] {0x3F8, 0x2F8, 0x3E8, 0x2E8 };
static constexpr uint8_t irqs_[] {4, 3, 15, 15 };
//static const char default_newline = '\r';
char newline = '\r'; //default_newline;
int nr_{0};
int port_{0};
uint8_t irq_{4};
std::string buf{};
on_data_handler on_data_ = [](char c){ debug("Default on_data: %c \n", c); };
on_string_handler on_readline_ = [](std::string s) { (void)s; };
void irq_handler_ ();
void readline_handler_(char c);
};
}
#endif
<commit_msg>Unused lambda param cast to void<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef HW_SERIAL_HPP
#define HW_SERIAL_HPP
//#define DEBUG
#include <os>
#include <hw/ioport.hpp>
#include <kernel/irq_manager.hpp>
namespace hw{
class Serial {
public:
/** On Data handler. Return value indicates if the buffer should be flushed **/
using on_data_handler = delegate<void(char c)>;
using on_string_handler = delegate<void(const std::string s)>;
using irq_delg = IRQ_manager::irq_delegate;
template <uint16_t PORT>
static Serial& port(){
static Serial s{PORT};
return s;
}
void on_data(on_data_handler del);
void on_readline(on_string_handler del, char delim = '\r');
void enable_interrupt();
void disable_interrupt();
char read();
void write(char c);
int received();
int is_transmit_empty();
// We don't want copies
Serial( Serial& ) = delete;
Serial( Serial&& ) = delete;
Serial& operator=(Serial&) = delete;
Serial operator=(Serial&&) = delete;
void init();
private:
Serial(int port);
static constexpr uint16_t ports_[] {0x3F8, 0x2F8, 0x3E8, 0x2E8 };
static constexpr uint8_t irqs_[] {4, 3, 15, 15 };
//static const char default_newline = '\r';
char newline = '\r'; //default_newline;
int nr_{0};
int port_{0};
uint8_t irq_{4};
std::string buf{};
on_data_handler on_data_ = [](char c){ debug("Default on_data: %c \n", c); (void)c; };
on_string_handler on_readline_ {}= [](std::string s) { (void)s; };
void irq_handler_ ();
void readline_handler_(char c);
};
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright © 2012 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "main/core.h"
#include "ir.h"
#include "linker.h"
#include "ir_uniform.h"
#include "util/string_to_uint_map.h"
/* These functions are put in a "private" namespace instead of being marked
* static so that the unit tests can access them. See
* http://code.google.com/p/googletest/wiki/AdvancedGuide#Testing_Private_Code
*/
namespace linker {
gl_uniform_storage *
get_storage(struct gl_shader_program *prog, const char *name)
{
unsigned id;
if (prog->UniformHash->get(id, name))
return &prog->data->UniformStorage[id];
assert(!"No uniform storage found!");
return NULL;
}
void
copy_constant_to_storage(union gl_constant_value *storage,
const ir_constant *val,
const enum glsl_base_type base_type,
const unsigned int elements,
unsigned int boolean_true)
{
for (unsigned int i = 0; i < elements; i++) {
switch (base_type) {
case GLSL_TYPE_UINT:
storage[i].u = val->value.u[i];
break;
case GLSL_TYPE_INT:
case GLSL_TYPE_SAMPLER:
storage[i].i = val->value.i[i];
break;
case GLSL_TYPE_FLOAT:
storage[i].f = val->value.f[i];
break;
case GLSL_TYPE_DOUBLE:
/* XXX need to check on big-endian */
memcpy(&storage[i * 2].u, &val->value.d[i], sizeof(double));
break;
case GLSL_TYPE_BOOL:
storage[i].b = val->value.b[i] ? boolean_true : 0;
break;
case GLSL_TYPE_INT64:
case GLSL_TYPE_UINT64:
case GLSL_TYPE_ARRAY:
case GLSL_TYPE_STRUCT:
case GLSL_TYPE_IMAGE:
case GLSL_TYPE_ATOMIC_UINT:
case GLSL_TYPE_INTERFACE:
case GLSL_TYPE_VOID:
case GLSL_TYPE_SUBROUTINE:
case GLSL_TYPE_FUNCTION:
case GLSL_TYPE_ERROR:
/* All other types should have already been filtered by other
* paths in the caller.
*/
assert(!"Should not get here.");
break;
}
}
}
/**
* Initialize an opaque uniform from the value of an explicit binding
* qualifier specified in the shader. Atomic counters are different because
* they have no storage and should be handled elsewhere.
*/
void
set_opaque_binding(void *mem_ctx, gl_shader_program *prog,
const glsl_type *type, const char *name, int *binding)
{
if (type->is_array() && type->fields.array->is_array()) {
const glsl_type *const element_type = type->fields.array;
for (unsigned int i = 0; i < type->length; i++) {
const char *element_name = ralloc_asprintf(mem_ctx, "%s[%d]", name, i);
set_opaque_binding(mem_ctx, prog, element_type,
element_name, binding);
}
} else {
struct gl_uniform_storage *const storage = get_storage(prog, name);
if (!storage)
return;
const unsigned elements = MAX2(storage->array_elements, 1);
/* Section 4.4.4 (Opaque-Uniform Layout Qualifiers) of the GLSL 4.20 spec
* says:
*
* "If the binding identifier is used with an array, the first element
* of the array takes the specified unit and each subsequent element
* takes the next consecutive unit."
*/
for (unsigned int i = 0; i < elements; i++) {
storage->storage[i].i = (*binding)++;
}
for (int sh = 0; sh < MESA_SHADER_STAGES; sh++) {
gl_linked_shader *shader = prog->_LinkedShaders[sh];
if (shader) {
if (storage->type->base_type == GLSL_TYPE_SAMPLER &&
storage->opaque[sh].active) {
for (unsigned i = 0; i < elements; i++) {
const unsigned index = storage->opaque[sh].index + i;
shader->Program->SamplerUnits[index] =
storage->storage[i].i;
}
} else if (storage->type->base_type == GLSL_TYPE_IMAGE &&
storage->opaque[sh].active) {
for (unsigned i = 0; i < elements; i++) {
const unsigned index = storage->opaque[sh].index + i;
if (index >= ARRAY_SIZE(shader->Program->sh.ImageUnits))
break;
shader->Program->sh.ImageUnits[index] =
storage->storage[i].i;
}
}
}
}
}
}
void
set_block_binding(gl_shader_program *prog, const char *block_name,
unsigned mode, int binding)
{
unsigned num_blocks = mode == ir_var_uniform ?
prog->data->NumUniformBlocks :
prog->data->NumShaderStorageBlocks;
struct gl_uniform_block *blks = mode == ir_var_uniform ?
prog->data->UniformBlocks : prog->data->ShaderStorageBlocks;
for (unsigned i = 0; i < num_blocks; i++) {
if (!strcmp(blks[i].Name, block_name)) {
blks[i].Binding = binding;
return;
}
}
unreachable("Failed to initialize block binding");
}
void
set_uniform_initializer(void *mem_ctx, gl_shader_program *prog,
const char *name, const glsl_type *type,
ir_constant *val, unsigned int boolean_true)
{
const glsl_type *t_without_array = type->without_array();
if (type->is_record()) {
ir_constant *field_constant;
field_constant = (ir_constant *)val->components.get_head();
for (unsigned int i = 0; i < type->length; i++) {
const glsl_type *field_type = type->fields.structure[i].type;
const char *field_name = ralloc_asprintf(mem_ctx, "%s.%s", name,
type->fields.structure[i].name);
set_uniform_initializer(mem_ctx, prog, field_name,
field_type, field_constant, boolean_true);
field_constant = (ir_constant *)field_constant->next;
}
return;
} else if (t_without_array->is_record() ||
(type->is_array() && type->fields.array->is_array())) {
const glsl_type *const element_type = type->fields.array;
for (unsigned int i = 0; i < type->length; i++) {
const char *element_name = ralloc_asprintf(mem_ctx, "%s[%d]", name, i);
set_uniform_initializer(mem_ctx, prog, element_name,
element_type, val->array_elements[i],
boolean_true);
}
return;
}
struct gl_uniform_storage *const storage = get_storage(prog, name);
if (!storage)
return;
if (val->type->is_array()) {
const enum glsl_base_type base_type =
val->array_elements[0]->type->base_type;
const unsigned int elements = val->array_elements[0]->type->components();
unsigned int idx = 0;
unsigned dmul = glsl_base_type_is_64bit(base_type) ? 2 : 1;
assert(val->type->length >= storage->array_elements);
for (unsigned int i = 0; i < storage->array_elements; i++) {
copy_constant_to_storage(& storage->storage[idx],
val->array_elements[i],
base_type,
elements,
boolean_true);
idx += elements * dmul;
}
} else {
copy_constant_to_storage(storage->storage,
val,
val->type->base_type,
val->type->components(),
boolean_true);
if (storage->type->is_sampler()) {
for (int sh = 0; sh < MESA_SHADER_STAGES; sh++) {
gl_linked_shader *shader = prog->_LinkedShaders[sh];
if (shader && storage->opaque[sh].active) {
unsigned index = storage->opaque[sh].index;
shader->Program->SamplerUnits[index] = storage->storage[0].i;
}
}
}
}
}
}
void
link_set_uniform_initializers(struct gl_shader_program *prog,
unsigned int boolean_true)
{
void *mem_ctx = NULL;
for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
struct gl_linked_shader *shader = prog->_LinkedShaders[i];
if (shader == NULL)
continue;
foreach_in_list(ir_instruction, node, shader->ir) {
ir_variable *const var = node->as_variable();
if (!var || (var->data.mode != ir_var_uniform &&
var->data.mode != ir_var_shader_storage))
continue;
if (!mem_ctx)
mem_ctx = ralloc_context(NULL);
if (var->data.explicit_binding) {
const glsl_type *const type = var->type;
if (type->without_array()->is_sampler() ||
type->without_array()->is_image()) {
int binding = var->data.binding;
linker::set_opaque_binding(mem_ctx, prog, var->type,
var->name, &binding);
} else if (var->is_in_buffer_block()) {
const glsl_type *const iface_type = var->get_interface_type();
/* If the variable is an array and it is an interface instance,
* we need to set the binding for each array element. Just
* checking that the variable is an array is not sufficient.
* The variable could be an array element of a uniform block
* that lacks an instance name. For example:
*
* uniform U {
* float f[4];
* };
*
* In this case "f" would pass is_in_buffer_block (above) and
* type->is_array(), but it will fail is_interface_instance().
*/
if (var->is_interface_instance() && var->type->is_array()) {
for (unsigned i = 0; i < var->type->length; i++) {
const char *name =
ralloc_asprintf(mem_ctx, "%s[%u]", iface_type->name, i);
/* Section 4.4.3 (Uniform Block Layout Qualifiers) of the
* GLSL 4.20 spec says:
*
* "If the binding identifier is used with a uniform
* block instanced as an array then the first element
* of the array takes the specified block binding and
* each subsequent element takes the next consecutive
* uniform block binding point."
*/
linker::set_block_binding(prog, name, var->data.mode,
var->data.binding + i);
}
} else {
linker::set_block_binding(prog, iface_type->name,
var->data.mode,
var->data.binding);
}
} else if (type->contains_atomic()) {
/* we don't actually need to do anything. */
} else {
assert(!"Explicit binding not on a sampler, UBO or atomic.");
}
} else if (var->constant_initializer) {
linker::set_uniform_initializer(mem_ctx, prog, var->name,
var->type, var->constant_initializer,
boolean_true);
}
}
}
ralloc_free(mem_ctx);
}
<commit_msg>glsl: Add 64-bit integer support to uniform initialiser code<commit_after>/*
* Copyright © 2012 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "main/core.h"
#include "ir.h"
#include "linker.h"
#include "ir_uniform.h"
#include "util/string_to_uint_map.h"
/* These functions are put in a "private" namespace instead of being marked
* static so that the unit tests can access them. See
* http://code.google.com/p/googletest/wiki/AdvancedGuide#Testing_Private_Code
*/
namespace linker {
gl_uniform_storage *
get_storage(struct gl_shader_program *prog, const char *name)
{
unsigned id;
if (prog->UniformHash->get(id, name))
return &prog->data->UniformStorage[id];
assert(!"No uniform storage found!");
return NULL;
}
void
copy_constant_to_storage(union gl_constant_value *storage,
const ir_constant *val,
const enum glsl_base_type base_type,
const unsigned int elements,
unsigned int boolean_true)
{
for (unsigned int i = 0; i < elements; i++) {
switch (base_type) {
case GLSL_TYPE_UINT:
storage[i].u = val->value.u[i];
break;
case GLSL_TYPE_INT:
case GLSL_TYPE_SAMPLER:
storage[i].i = val->value.i[i];
break;
case GLSL_TYPE_FLOAT:
storage[i].f = val->value.f[i];
break;
case GLSL_TYPE_DOUBLE:
case GLSL_TYPE_UINT64:
case GLSL_TYPE_INT64:
/* XXX need to check on big-endian */
memcpy(&storage[i * 2].u, &val->value.d[i], sizeof(double));
break;
case GLSL_TYPE_BOOL:
storage[i].b = val->value.b[i] ? boolean_true : 0;
break;
case GLSL_TYPE_ARRAY:
case GLSL_TYPE_STRUCT:
case GLSL_TYPE_IMAGE:
case GLSL_TYPE_ATOMIC_UINT:
case GLSL_TYPE_INTERFACE:
case GLSL_TYPE_VOID:
case GLSL_TYPE_SUBROUTINE:
case GLSL_TYPE_FUNCTION:
case GLSL_TYPE_ERROR:
/* All other types should have already been filtered by other
* paths in the caller.
*/
assert(!"Should not get here.");
break;
}
}
}
/**
* Initialize an opaque uniform from the value of an explicit binding
* qualifier specified in the shader. Atomic counters are different because
* they have no storage and should be handled elsewhere.
*/
void
set_opaque_binding(void *mem_ctx, gl_shader_program *prog,
const glsl_type *type, const char *name, int *binding)
{
if (type->is_array() && type->fields.array->is_array()) {
const glsl_type *const element_type = type->fields.array;
for (unsigned int i = 0; i < type->length; i++) {
const char *element_name = ralloc_asprintf(mem_ctx, "%s[%d]", name, i);
set_opaque_binding(mem_ctx, prog, element_type,
element_name, binding);
}
} else {
struct gl_uniform_storage *const storage = get_storage(prog, name);
if (!storage)
return;
const unsigned elements = MAX2(storage->array_elements, 1);
/* Section 4.4.4 (Opaque-Uniform Layout Qualifiers) of the GLSL 4.20 spec
* says:
*
* "If the binding identifier is used with an array, the first element
* of the array takes the specified unit and each subsequent element
* takes the next consecutive unit."
*/
for (unsigned int i = 0; i < elements; i++) {
storage->storage[i].i = (*binding)++;
}
for (int sh = 0; sh < MESA_SHADER_STAGES; sh++) {
gl_linked_shader *shader = prog->_LinkedShaders[sh];
if (shader) {
if (storage->type->base_type == GLSL_TYPE_SAMPLER &&
storage->opaque[sh].active) {
for (unsigned i = 0; i < elements; i++) {
const unsigned index = storage->opaque[sh].index + i;
shader->Program->SamplerUnits[index] =
storage->storage[i].i;
}
} else if (storage->type->base_type == GLSL_TYPE_IMAGE &&
storage->opaque[sh].active) {
for (unsigned i = 0; i < elements; i++) {
const unsigned index = storage->opaque[sh].index + i;
if (index >= ARRAY_SIZE(shader->Program->sh.ImageUnits))
break;
shader->Program->sh.ImageUnits[index] =
storage->storage[i].i;
}
}
}
}
}
}
void
set_block_binding(gl_shader_program *prog, const char *block_name,
unsigned mode, int binding)
{
unsigned num_blocks = mode == ir_var_uniform ?
prog->data->NumUniformBlocks :
prog->data->NumShaderStorageBlocks;
struct gl_uniform_block *blks = mode == ir_var_uniform ?
prog->data->UniformBlocks : prog->data->ShaderStorageBlocks;
for (unsigned i = 0; i < num_blocks; i++) {
if (!strcmp(blks[i].Name, block_name)) {
blks[i].Binding = binding;
return;
}
}
unreachable("Failed to initialize block binding");
}
void
set_uniform_initializer(void *mem_ctx, gl_shader_program *prog,
const char *name, const glsl_type *type,
ir_constant *val, unsigned int boolean_true)
{
const glsl_type *t_without_array = type->without_array();
if (type->is_record()) {
ir_constant *field_constant;
field_constant = (ir_constant *)val->components.get_head();
for (unsigned int i = 0; i < type->length; i++) {
const glsl_type *field_type = type->fields.structure[i].type;
const char *field_name = ralloc_asprintf(mem_ctx, "%s.%s", name,
type->fields.structure[i].name);
set_uniform_initializer(mem_ctx, prog, field_name,
field_type, field_constant, boolean_true);
field_constant = (ir_constant *)field_constant->next;
}
return;
} else if (t_without_array->is_record() ||
(type->is_array() && type->fields.array->is_array())) {
const glsl_type *const element_type = type->fields.array;
for (unsigned int i = 0; i < type->length; i++) {
const char *element_name = ralloc_asprintf(mem_ctx, "%s[%d]", name, i);
set_uniform_initializer(mem_ctx, prog, element_name,
element_type, val->array_elements[i],
boolean_true);
}
return;
}
struct gl_uniform_storage *const storage = get_storage(prog, name);
if (!storage)
return;
if (val->type->is_array()) {
const enum glsl_base_type base_type =
val->array_elements[0]->type->base_type;
const unsigned int elements = val->array_elements[0]->type->components();
unsigned int idx = 0;
unsigned dmul = glsl_base_type_is_64bit(base_type) ? 2 : 1;
assert(val->type->length >= storage->array_elements);
for (unsigned int i = 0; i < storage->array_elements; i++) {
copy_constant_to_storage(& storage->storage[idx],
val->array_elements[i],
base_type,
elements,
boolean_true);
idx += elements * dmul;
}
} else {
copy_constant_to_storage(storage->storage,
val,
val->type->base_type,
val->type->components(),
boolean_true);
if (storage->type->is_sampler()) {
for (int sh = 0; sh < MESA_SHADER_STAGES; sh++) {
gl_linked_shader *shader = prog->_LinkedShaders[sh];
if (shader && storage->opaque[sh].active) {
unsigned index = storage->opaque[sh].index;
shader->Program->SamplerUnits[index] = storage->storage[0].i;
}
}
}
}
}
}
void
link_set_uniform_initializers(struct gl_shader_program *prog,
unsigned int boolean_true)
{
void *mem_ctx = NULL;
for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
struct gl_linked_shader *shader = prog->_LinkedShaders[i];
if (shader == NULL)
continue;
foreach_in_list(ir_instruction, node, shader->ir) {
ir_variable *const var = node->as_variable();
if (!var || (var->data.mode != ir_var_uniform &&
var->data.mode != ir_var_shader_storage))
continue;
if (!mem_ctx)
mem_ctx = ralloc_context(NULL);
if (var->data.explicit_binding) {
const glsl_type *const type = var->type;
if (type->without_array()->is_sampler() ||
type->without_array()->is_image()) {
int binding = var->data.binding;
linker::set_opaque_binding(mem_ctx, prog, var->type,
var->name, &binding);
} else if (var->is_in_buffer_block()) {
const glsl_type *const iface_type = var->get_interface_type();
/* If the variable is an array and it is an interface instance,
* we need to set the binding for each array element. Just
* checking that the variable is an array is not sufficient.
* The variable could be an array element of a uniform block
* that lacks an instance name. For example:
*
* uniform U {
* float f[4];
* };
*
* In this case "f" would pass is_in_buffer_block (above) and
* type->is_array(), but it will fail is_interface_instance().
*/
if (var->is_interface_instance() && var->type->is_array()) {
for (unsigned i = 0; i < var->type->length; i++) {
const char *name =
ralloc_asprintf(mem_ctx, "%s[%u]", iface_type->name, i);
/* Section 4.4.3 (Uniform Block Layout Qualifiers) of the
* GLSL 4.20 spec says:
*
* "If the binding identifier is used with a uniform
* block instanced as an array then the first element
* of the array takes the specified block binding and
* each subsequent element takes the next consecutive
* uniform block binding point."
*/
linker::set_block_binding(prog, name, var->data.mode,
var->data.binding + i);
}
} else {
linker::set_block_binding(prog, iface_type->name,
var->data.mode,
var->data.binding);
}
} else if (type->contains_atomic()) {
/* we don't actually need to do anything. */
} else {
assert(!"Explicit binding not on a sampler, UBO or atomic.");
}
} else if (var->constant_initializer) {
linker::set_uniform_initializer(mem_ctx, prog, var->name,
var->type, var->constant_initializer,
boolean_true);
}
}
}
ralloc_free(mem_ctx);
}
<|endoftext|> |
<commit_before>/*************************************************************************/
/* wsl_server.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef JAVASCRIPT_ENABLED
#include "wsl_server.h"
#include "core/os/os.h"
#include "core/project_settings.h"
WSLServer::PendingPeer::PendingPeer() {
use_ssl = false;
time = 0;
has_request = false;
response_sent = 0;
req_pos = 0;
memset(req_buf, 0, sizeof(req_buf));
}
bool WSLServer::PendingPeer::_parse_request(const Vector<String> p_protocols) {
Vector<String> psa = String((char *)req_buf).split("\r\n");
int len = psa.size();
ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers, got: " + itos(len) + ", expected >= 4.");
Vector<String> req = psa[0].split(" ", false);
ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code.");
// Wrong protocol
ERR_FAIL_COND_V_MSG(req[0] != "GET" || req[2] != "HTTP/1.1", false, "Invalid method or HTTP version.");
Map<String, String> headers;
for (int i = 1; i < len; i++) {
Vector<String> header = psa[i].split(":", false, 1);
ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i]);
String name = header[0].to_lower();
String value = header[1].strip_edges();
if (headers.has(name)) {
headers[name] += "," + value;
} else {
headers[name] = value;
}
}
#define _WSL_CHECK(NAME, VALUE) \
ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \
"Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
#define _WSL_CHECK_EX(NAME) \
ERR_FAIL_COND_V_MSG(!headers.has(NAME), false, "Missing header '" + String(NAME) + "'.");
_WSL_CHECK("upgrade", "websocket");
_WSL_CHECK("sec-websocket-version", "13");
_WSL_CHECK_EX("sec-websocket-key");
_WSL_CHECK_EX("connection");
#undef _WSL_CHECK_EX
#undef _WSL_CHECK
key = headers["sec-websocket-key"];
if (headers.has("sec-websocket-protocol")) {
Vector<String> protos = headers["sec-websocket-protocol"].split(",");
for (int i = 0; i < protos.size(); i++) {
String proto = protos[i].strip_edges();
// Check if we have the given protocol
for (int j = 0; j < p_protocols.size(); j++) {
if (proto != p_protocols[j]) {
continue;
}
protocol = proto;
break;
}
// Found a protocol
if (protocol != "") {
break;
}
}
if (protocol == "") { // Invalid protocol(s) requested
return false;
}
} else if (p_protocols.size() > 0) { // No protocol requested, but we need one
return false;
}
return true;
}
Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols, uint64_t p_timeout) {
if (OS::get_singleton()->get_ticks_msec() - time > p_timeout) {
return ERR_TIMEOUT;
}
if (use_ssl) {
Ref<StreamPeerSSL> ssl = static_cast<Ref<StreamPeerSSL>>(connection);
if (ssl.is_null()) {
return FAILED;
}
ssl->poll();
if (ssl->get_status() == StreamPeerSSL::STATUS_HANDSHAKING) {
return ERR_BUSY;
} else if (ssl->get_status() != StreamPeerSSL::STATUS_CONNECTED) {
return FAILED;
}
}
if (!has_request) {
int read = 0;
while (true) {
ERR_FAIL_COND_V_MSG(req_pos >= WSL_MAX_HEADER_SIZE, ERR_OUT_OF_MEMORY, "Response headers too big.");
Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
if (err != OK) { // Got an error
return FAILED;
} else if (read != 1) { // Busy, wait next poll
return ERR_BUSY;
}
char *r = (char *)req_buf;
int l = req_pos;
if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
r[l - 3] = '\0';
if (!_parse_request(p_protocols)) {
return FAILED;
}
String s = "HTTP/1.1 101 Switching Protocols\r\n";
s += "Upgrade: websocket\r\n";
s += "Connection: Upgrade\r\n";
s += "Sec-WebSocket-Accept: " + WSLPeer::compute_key_response(key) + "\r\n";
if (protocol != "") {
s += "Sec-WebSocket-Protocol: " + protocol + "\r\n";
}
s += "\r\n";
response = s.utf8();
has_request = true;
break;
}
req_pos += 1;
}
}
if (has_request && response_sent < response.size() - 1) {
int sent = 0;
Error err = connection->put_partial_data((const uint8_t *)response.get_data() + response_sent, response.size() - response_sent - 1, sent);
if (err != OK) {
return err;
}
response_sent += sent;
}
if (response_sent < response.size() - 1) {
return ERR_BUSY;
}
return OK;
}
Error WSLServer::listen(int p_port, const Vector<String> p_protocols, bool gd_mp_api) {
ERR_FAIL_COND_V(is_listening(), ERR_ALREADY_IN_USE);
_is_multiplayer = gd_mp_api;
// Strip edges from protocols.
_protocols.resize(p_protocols.size());
String *pw = _protocols.ptrw();
for (int i = 0; i < p_protocols.size(); i++) {
pw[i] = p_protocols[i].strip_edges();
}
return _server->listen(p_port, bind_ip);
}
void WSLServer::poll() {
List<int> remove_ids;
for (Map<int, Ref<WebSocketPeer>>::Element *E = _peer_map.front(); E; E = E->next()) {
Ref<WSLPeer> peer = (WSLPeer *)E->get().ptr();
peer->poll();
if (!peer->is_connected_to_host()) {
_on_disconnect(E->key(), peer->close_code != -1);
remove_ids.push_back(E->key());
}
}
for (List<int>::Element *E = remove_ids.front(); E; E = E->next()) {
_peer_map.erase(E->get());
}
remove_ids.clear();
List<Ref<PendingPeer>> remove_peers;
for (List<Ref<PendingPeer>>::Element *E = _pending.front(); E; E = E->next()) {
Ref<PendingPeer> ppeer = E->get();
Error err = ppeer->do_handshake(_protocols, handshake_timeout);
if (err == ERR_BUSY) {
continue;
} else if (err != OK) {
remove_peers.push_back(ppeer);
continue;
}
// Creating new peer
int32_t id = _gen_unique_id();
WSLPeer::PeerData *data = memnew(struct WSLPeer::PeerData);
data->obj = this;
data->conn = ppeer->connection;
data->tcp = ppeer->tcp;
data->is_server = true;
data->id = id;
Ref<WSLPeer> ws_peer = memnew(WSLPeer);
ws_peer->make_context(data, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size);
ws_peer->set_no_delay(true);
_peer_map[id] = ws_peer;
remove_peers.push_back(ppeer);
_on_connect(id, ppeer->protocol);
}
for (List<Ref<PendingPeer>>::Element *E = remove_peers.front(); E; E = E->next()) {
_pending.erase(E->get());
}
remove_peers.clear();
if (!_server->is_listening()) {
return;
}
while (_server->is_connection_available()) {
Ref<StreamPeerTCP> conn = _server->take_connection();
if (is_refusing_new_connections()) {
continue; // Conn will go out-of-scope and be closed.
}
Ref<PendingPeer> peer = memnew(PendingPeer);
if (private_key.is_valid() && ssl_cert.is_valid()) {
Ref<StreamPeerSSL> ssl = Ref<StreamPeerSSL>(StreamPeerSSL::create());
ssl->set_blocking_handshake_enabled(false);
ssl->accept_stream(conn, private_key, ssl_cert, ca_chain);
peer->connection = ssl;
peer->use_ssl = true;
} else {
peer->connection = conn;
}
peer->tcp = conn;
peer->time = OS::get_singleton()->get_ticks_msec();
_pending.push_back(peer);
}
}
bool WSLServer::is_listening() const {
return _server->is_listening();
}
int WSLServer::get_max_packet_size() const {
return (1 << _out_buf_size) - PROTO_SIZE;
}
void WSLServer::stop() {
_server->stop();
for (Map<int, Ref<WebSocketPeer>>::Element *E = _peer_map.front(); E; E = E->next()) {
Ref<WSLPeer> peer = (WSLPeer *)E->get().ptr();
peer->close_now();
}
_pending.clear();
_peer_map.clear();
_protocols.clear();
}
bool WSLServer::has_peer(int p_id) const {
return _peer_map.has(p_id);
}
Ref<WebSocketPeer> WSLServer::get_peer(int p_id) const {
ERR_FAIL_COND_V(!has_peer(p_id), nullptr);
return _peer_map[p_id];
}
IP_Address WSLServer::get_peer_address(int p_peer_id) const {
ERR_FAIL_COND_V(!has_peer(p_peer_id), IP_Address());
return _peer_map[p_peer_id]->get_connected_host();
}
int WSLServer::get_peer_port(int p_peer_id) const {
ERR_FAIL_COND_V(!has_peer(p_peer_id), 0);
return _peer_map[p_peer_id]->get_connected_port();
}
void WSLServer::disconnect_peer(int p_peer_id, int p_code, String p_reason) {
ERR_FAIL_COND(!has_peer(p_peer_id));
get_peer(p_peer_id)->close(p_code, p_reason);
}
Error WSLServer::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) {
ERR_FAIL_COND_V_MSG(_server->is_listening(), FAILED, "Buffers sizes can only be set before listening or connecting.");
_in_buf_size = nearest_shift(p_in_buffer - 1) + 10;
_in_pkt_size = nearest_shift(p_in_packets - 1);
_out_buf_size = nearest_shift(p_out_buffer - 1) + 10;
_out_pkt_size = nearest_shift(p_out_packets - 1);
return OK;
}
WSLServer::WSLServer() {
_in_buf_size = nearest_shift((int)GLOBAL_GET(WSS_IN_BUF) - 1) + 10;
_in_pkt_size = nearest_shift((int)GLOBAL_GET(WSS_IN_PKT) - 1);
_out_buf_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_BUF) - 1) + 10;
_out_pkt_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_PKT) - 1);
_server.instance();
}
WSLServer::~WSLServer() {
stop();
}
#endif // JAVASCRIPT_ENABLED
<commit_msg>Improve error reporting in WebSocketServer<commit_after>/*************************************************************************/
/* wsl_server.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef JAVASCRIPT_ENABLED
#include "wsl_server.h"
#include "core/os/os.h"
#include "core/project_settings.h"
WSLServer::PendingPeer::PendingPeer() {
use_ssl = false;
time = 0;
has_request = false;
response_sent = 0;
req_pos = 0;
memset(req_buf, 0, sizeof(req_buf));
}
bool WSLServer::PendingPeer::_parse_request(const Vector<String> p_protocols) {
Vector<String> psa = String((char *)req_buf).split("\r\n");
int len = psa.size();
ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers, got: " + itos(len) + ", expected >= 4.");
Vector<String> req = psa[0].split(" ", false);
ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code.");
// Wrong protocol
ERR_FAIL_COND_V_MSG(req[0] != "GET" || req[2] != "HTTP/1.1", false, "Invalid method or HTTP version.");
Map<String, String> headers;
for (int i = 1; i < len; i++) {
Vector<String> header = psa[i].split(":", false, 1);
ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i]);
String name = header[0].to_lower();
String value = header[1].strip_edges();
if (headers.has(name)) {
headers[name] += "," + value;
} else {
headers[name] = value;
}
}
#define _WSL_CHECK(NAME, VALUE) \
ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \
"Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
#define _WSL_CHECK_EX(NAME) \
ERR_FAIL_COND_V_MSG(!headers.has(NAME), false, "Missing header '" + String(NAME) + "'.");
_WSL_CHECK("upgrade", "websocket");
_WSL_CHECK("sec-websocket-version", "13");
_WSL_CHECK_EX("sec-websocket-key");
_WSL_CHECK_EX("connection");
#undef _WSL_CHECK_EX
#undef _WSL_CHECK
key = headers["sec-websocket-key"];
if (headers.has("sec-websocket-protocol")) {
Vector<String> protos = headers["sec-websocket-protocol"].split(",");
for (int i = 0; i < protos.size(); i++) {
String proto = protos[i].strip_edges();
// Check if we have the given protocol
for (int j = 0; j < p_protocols.size(); j++) {
if (proto != p_protocols[j]) {
continue;
}
protocol = proto;
break;
}
// Found a protocol
if (protocol != "") {
break;
}
}
if (protocol == "") { // Invalid protocol(s) requested
return false;
}
} else if (p_protocols.size() > 0) { // No protocol requested, but we need one
return false;
}
return true;
}
Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols, uint64_t p_timeout) {
if (OS::get_singleton()->get_ticks_msec() - time > p_timeout) {
print_verbose(vformat("WebSocket handshake timed out after %.3f seconds.", p_timeout * 0.001));
return ERR_TIMEOUT;
}
if (use_ssl) {
Ref<StreamPeerSSL> ssl = static_cast<Ref<StreamPeerSSL>>(connection);
if (ssl.is_null()) {
ERR_FAIL_V_MSG(ERR_BUG, "Couldn't get StreamPeerSSL for WebSocket handshake.");
}
ssl->poll();
if (ssl->get_status() == StreamPeerSSL::STATUS_HANDSHAKING) {
return ERR_BUSY;
} else if (ssl->get_status() != StreamPeerSSL::STATUS_CONNECTED) {
print_verbose(vformat("WebSocket SSL connection error during handshake (StreamPeerSSL status code %d).", ssl->get_status()));
return FAILED;
}
}
if (!has_request) {
int read = 0;
while (true) {
ERR_FAIL_COND_V_MSG(req_pos >= WSL_MAX_HEADER_SIZE, ERR_OUT_OF_MEMORY, "WebSocket response headers are too big.");
Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
if (err != OK) { // Got an error
print_verbose(vformat("WebSocket error while getting partial data (StreamPeer error code %d).", err));
return FAILED;
} else if (read != 1) { // Busy, wait next poll
return ERR_BUSY;
}
char *r = (char *)req_buf;
int l = req_pos;
if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
r[l - 3] = '\0';
if (!_parse_request(p_protocols)) {
return FAILED;
}
String s = "HTTP/1.1 101 Switching Protocols\r\n";
s += "Upgrade: websocket\r\n";
s += "Connection: Upgrade\r\n";
s += "Sec-WebSocket-Accept: " + WSLPeer::compute_key_response(key) + "\r\n";
if (protocol != "") {
s += "Sec-WebSocket-Protocol: " + protocol + "\r\n";
}
s += "\r\n";
response = s.utf8();
has_request = true;
break;
}
req_pos += 1;
}
}
if (has_request && response_sent < response.size() - 1) {
int sent = 0;
Error err = connection->put_partial_data((const uint8_t *)response.get_data() + response_sent, response.size() - response_sent - 1, sent);
if (err != OK) {
print_verbose(vformat("WebSocket error while putting partial data (StreamPeer error code %d).", err));
return err;
}
response_sent += sent;
}
if (response_sent < response.size() - 1) {
return ERR_BUSY;
}
return OK;
}
Error WSLServer::listen(int p_port, const Vector<String> p_protocols, bool gd_mp_api) {
ERR_FAIL_COND_V(is_listening(), ERR_ALREADY_IN_USE);
_is_multiplayer = gd_mp_api;
// Strip edges from protocols.
_protocols.resize(p_protocols.size());
String *pw = _protocols.ptrw();
for (int i = 0; i < p_protocols.size(); i++) {
pw[i] = p_protocols[i].strip_edges();
}
return _server->listen(p_port, bind_ip);
}
void WSLServer::poll() {
List<int> remove_ids;
for (Map<int, Ref<WebSocketPeer>>::Element *E = _peer_map.front(); E; E = E->next()) {
Ref<WSLPeer> peer = (WSLPeer *)E->get().ptr();
peer->poll();
if (!peer->is_connected_to_host()) {
_on_disconnect(E->key(), peer->close_code != -1);
remove_ids.push_back(E->key());
}
}
for (List<int>::Element *E = remove_ids.front(); E; E = E->next()) {
_peer_map.erase(E->get());
}
remove_ids.clear();
List<Ref<PendingPeer>> remove_peers;
for (List<Ref<PendingPeer>>::Element *E = _pending.front(); E; E = E->next()) {
Ref<PendingPeer> ppeer = E->get();
Error err = ppeer->do_handshake(_protocols, handshake_timeout);
if (err == ERR_BUSY) {
continue;
} else if (err != OK) {
remove_peers.push_back(ppeer);
continue;
}
// Creating new peer
int32_t id = _gen_unique_id();
WSLPeer::PeerData *data = memnew(struct WSLPeer::PeerData);
data->obj = this;
data->conn = ppeer->connection;
data->tcp = ppeer->tcp;
data->is_server = true;
data->id = id;
Ref<WSLPeer> ws_peer = memnew(WSLPeer);
ws_peer->make_context(data, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size);
ws_peer->set_no_delay(true);
_peer_map[id] = ws_peer;
remove_peers.push_back(ppeer);
_on_connect(id, ppeer->protocol);
}
for (List<Ref<PendingPeer>>::Element *E = remove_peers.front(); E; E = E->next()) {
_pending.erase(E->get());
}
remove_peers.clear();
if (!_server->is_listening()) {
return;
}
while (_server->is_connection_available()) {
Ref<StreamPeerTCP> conn = _server->take_connection();
if (is_refusing_new_connections()) {
continue; // Conn will go out-of-scope and be closed.
}
Ref<PendingPeer> peer = memnew(PendingPeer);
if (private_key.is_valid() && ssl_cert.is_valid()) {
Ref<StreamPeerSSL> ssl = Ref<StreamPeerSSL>(StreamPeerSSL::create());
ssl->set_blocking_handshake_enabled(false);
ssl->accept_stream(conn, private_key, ssl_cert, ca_chain);
peer->connection = ssl;
peer->use_ssl = true;
} else {
peer->connection = conn;
}
peer->tcp = conn;
peer->time = OS::get_singleton()->get_ticks_msec();
_pending.push_back(peer);
}
}
bool WSLServer::is_listening() const {
return _server->is_listening();
}
int WSLServer::get_max_packet_size() const {
return (1 << _out_buf_size) - PROTO_SIZE;
}
void WSLServer::stop() {
_server->stop();
for (Map<int, Ref<WebSocketPeer>>::Element *E = _peer_map.front(); E; E = E->next()) {
Ref<WSLPeer> peer = (WSLPeer *)E->get().ptr();
peer->close_now();
}
_pending.clear();
_peer_map.clear();
_protocols.clear();
}
bool WSLServer::has_peer(int p_id) const {
return _peer_map.has(p_id);
}
Ref<WebSocketPeer> WSLServer::get_peer(int p_id) const {
ERR_FAIL_COND_V(!has_peer(p_id), nullptr);
return _peer_map[p_id];
}
IP_Address WSLServer::get_peer_address(int p_peer_id) const {
ERR_FAIL_COND_V(!has_peer(p_peer_id), IP_Address());
return _peer_map[p_peer_id]->get_connected_host();
}
int WSLServer::get_peer_port(int p_peer_id) const {
ERR_FAIL_COND_V(!has_peer(p_peer_id), 0);
return _peer_map[p_peer_id]->get_connected_port();
}
void WSLServer::disconnect_peer(int p_peer_id, int p_code, String p_reason) {
ERR_FAIL_COND(!has_peer(p_peer_id));
get_peer(p_peer_id)->close(p_code, p_reason);
}
Error WSLServer::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) {
ERR_FAIL_COND_V_MSG(_server->is_listening(), FAILED, "Buffers sizes can only be set before listening or connecting.");
_in_buf_size = nearest_shift(p_in_buffer - 1) + 10;
_in_pkt_size = nearest_shift(p_in_packets - 1);
_out_buf_size = nearest_shift(p_out_buffer - 1) + 10;
_out_pkt_size = nearest_shift(p_out_packets - 1);
return OK;
}
WSLServer::WSLServer() {
_in_buf_size = nearest_shift((int)GLOBAL_GET(WSS_IN_BUF) - 1) + 10;
_in_pkt_size = nearest_shift((int)GLOBAL_GET(WSS_IN_PKT) - 1);
_out_buf_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_BUF) - 1) + 10;
_out_pkt_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_PKT) - 1);
_server.instance();
}
WSLServer::~WSLServer() {
stop();
}
#endif // JAVASCRIPT_ENABLED
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativeapplication_p.h"
#include <private/qobject_p.h>
#include <QtGui/QGuiApplication>
#include <QtGui/QInputMethod>
#include <QtCore/QDebug>
QT_BEGIN_NAMESPACE
class QDeclarativeApplicationPrivate : public QObjectPrivate
{
Q_DECLARE_PUBLIC(QDeclarativeApplication)
public:
QDeclarativeApplicationPrivate() : active(QGuiApplication::activeWindow() != 0),
layoutDirection(QGuiApplication::layoutDirection()) {}
bool active;
Qt::LayoutDirection layoutDirection;
};
/*
This object and its properties are documented as part of the Qt object,
in qdeclarativengine.cpp
*/
QDeclarativeApplication::QDeclarativeApplication(QObject *parent) : QObject(*new QDeclarativeApplicationPrivate(), parent)
{
if (qApp)
qApp->installEventFilter(this);
}
QDeclarativeApplication::~QDeclarativeApplication()
{
}
bool QDeclarativeApplication::active() const
{
Q_D(const QDeclarativeApplication);
return d->active;
}
Qt::LayoutDirection QDeclarativeApplication::layoutDirection() const
{
Q_D(const QDeclarativeApplication);
return d->layoutDirection;
}
QObject *QDeclarativeApplication::inputPanel() const
{
qWarning() << "Qt.application.inputPanel is deprecated, use Qt.inputMethod instead";
return qApp ? qApp->inputMethod() : 0;
}
bool QDeclarativeApplication::eventFilter(QObject *obj, QEvent *event)
{
Q_UNUSED(obj)
Q_D(QDeclarativeApplication);
if (event->type() == QEvent::ApplicationActivate
|| event->type() == QEvent::ApplicationDeactivate) {
bool active = d->active;
if (event->type() == QEvent::ApplicationActivate)
active = true;
else if (event->type() == QEvent::ApplicationDeactivate)
active = false;
if (d->active != active) {
d->active = active;
emit activeChanged();
}
}
if (event->type() == QEvent::LayoutDirectionChange) {
Qt::LayoutDirection direction = QGuiApplication::layoutDirection();
if (d->layoutDirection != direction) {
d->layoutDirection = direction;
emit layoutDirectionChanged();
}
}
return false;
}
QT_END_NAMESPACE
<commit_msg>Qt.application.inputPanel to make deprecation warning only once<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativeapplication_p.h"
#include <private/qobject_p.h>
#include <QtGui/QGuiApplication>
#include <QtGui/QInputMethod>
#include <QtCore/QDebug>
QT_BEGIN_NAMESPACE
class QDeclarativeApplicationPrivate : public QObjectPrivate
{
Q_DECLARE_PUBLIC(QDeclarativeApplication)
public:
QDeclarativeApplicationPrivate() : active(QGuiApplication::activeWindow() != 0),
layoutDirection(QGuiApplication::layoutDirection()) {}
bool active;
Qt::LayoutDirection layoutDirection;
};
/*
This object and its properties are documented as part of the Qt object,
in qdeclarativengine.cpp
*/
QDeclarativeApplication::QDeclarativeApplication(QObject *parent) : QObject(*new QDeclarativeApplicationPrivate(), parent)
{
if (qApp)
qApp->installEventFilter(this);
}
QDeclarativeApplication::~QDeclarativeApplication()
{
}
bool QDeclarativeApplication::active() const
{
Q_D(const QDeclarativeApplication);
return d->active;
}
Qt::LayoutDirection QDeclarativeApplication::layoutDirection() const
{
Q_D(const QDeclarativeApplication);
return d->layoutDirection;
}
QObject *QDeclarativeApplication::inputPanel() const
{
static bool warned = false;
if (!warned) {
qWarning() << "Qt.application.inputPanel is deprecated, use Qt.inputMethod instead";
warned = true;
}
return qApp ? qApp->inputMethod() : 0;
}
bool QDeclarativeApplication::eventFilter(QObject *obj, QEvent *event)
{
Q_UNUSED(obj)
Q_D(QDeclarativeApplication);
if (event->type() == QEvent::ApplicationActivate
|| event->type() == QEvent::ApplicationDeactivate) {
bool active = d->active;
if (event->type() == QEvent::ApplicationActivate)
active = true;
else if (event->type() == QEvent::ApplicationDeactivate)
active = false;
if (d->active != active) {
d->active = active;
emit activeChanged();
}
}
if (event->type() == QEvent::LayoutDirectionChange) {
Qt::LayoutDirection direction = QGuiApplication::layoutDirection();
if (d->layoutDirection != direction) {
d->layoutDirection = direction;
emit layoutDirectionChanged();
}
}
return false;
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>#include <node.h>
#include <v8.h>
#include "protagonist.h"
using namespace v8;
using namespace protagonist;
void Init(Handle<Object> exports, Handle<Object> module) {
// Blueprint object
Blueprint::Init(exports);
// Parse function
exports->Set(String::NewSymbol("parse"), FunctionTemplate::New(Parse)->GetFunction());
}
NODE_MODULE(protagonist, Init)
<commit_msg>Build with node v0.8.15<commit_after>#include <node.h>
#include <v8.h>
#include "protagonist.h"
using namespace v8;
using namespace protagonist;
void Init(Handle<Object> exports) {
// Blueprint object
Blueprint::Init(exports);
// Parse function
exports->Set(String::NewSymbol("parse"), FunctionTemplate::New(Parse)->GetFunction());
}
NODE_MODULE(protagonist, Init)
<|endoftext|> |
<commit_before>/*
* Fiahil
* 12.05.2012
*/
#include <iostream>
#include <vector>
#include "APlayer.hpp"
APlayer::APlayer(Map & map)
: _map(map),
_pv(100),
_id(0),
_teamId(0),
_color(0),
_attack(false),
_timers(5, -1.0),
_weapon(BombType::NORMAL),
_skin(Skin::NORMAL),
_state(State::STATIC),
_dir(Dir::SOUTH),
_indic(0.5f, 0.5f, 0.8f, _color),
_rotFuncMap(Dir::LAST, 0)
{
this->_rotFuncMap[Dir::NORTH] = &APlayer::NORTHFunction;
this->_rotFuncMap[Dir::SOUTH] = &APlayer::SOUTHFunction;
this->_rotFuncMap[Dir::WEST] = &APlayer::WESTFunction;
this->_rotFuncMap[Dir::EAST] = &APlayer::EASTFunction;
this->_pos._scale = 2.0f;
this->setPos(1, 1);
this->_indic.setScale(2.0f);
this->_indic.setPos(1, 1);
}
APlayer::~APlayer()
{
}
void APlayer::initialize(void)
{
std::vector<std::string> refModel(Skin::LAST, "");
refModel[Skin::NORMAL] = "models/fifi.fbx";
this->_model = gdl::Model::load(refModel[this->_skin]);
this->_model.infos();
}
void APlayer::draw(void)
{
glPushMatrix();
glTranslatef(this->_pos._pos.x, this->_pos._pos.y - 1.0f, this->_pos._pos.z);
(this->*_rotFuncMap[this->_dir])();
// glScalef(0.005f, 0.005f, 0.005f);
glScalef(0.040f, 0.040f, 0.040f);
this->_model.draw();
glPopMatrix();
glPushMatrix();
glTranslatef(0.0f, 3.0f, 0.0f);
this->_indic.draw();
glPopMatrix();
}
void APlayer::update(gdl::GameClock const& clock, gdl::Input& input)
{
this->play(clock, input);
this->_model.update(clock);
this->_indic.setPos(this->_pos._x, this->_pos._y);
}
void APlayer::takeDamage(Pattern const&)
{
}
void APlayer::setPv(int pv)
{
this->_pv = pv;
}
int APlayer::getPv() const
{
return this->_pv;
}
void APlayer::setWeapon(BombType::eBomb weapon)
{
this->_weapon = weapon;
}
BombType::eBomb APlayer::getWeapon() const
{
return this->_weapon;
}
void APlayer::setTeamId(size_t team)
{
this->_teamId = team;
}
size_t APlayer::getTeamId() const
{
return this->_teamId;
}
void APlayer::setId(size_t id)
{
this->_id = id;
}
size_t APlayer::getId() const
{
return this->_id;
}
size_t APlayer::getColor() const
{
return this->_color;
}
void APlayer::setColor(size_t val)
{
this->_color = val;
this->_indic.setColor(val);
}
void APlayer::setState(State::eState state)
{
this->_state = state;
}
State::eState APlayer::getState() const
{
return this->_state;
}
void APlayer::setSkin(Skin::eSkin skin)
{
this->_skin = skin;
}
Skin::eSkin APlayer::getSkin(void) const
{
return this->_skin;
}
void APlayer::setDir(Dir::eDir dir)
{
this->_dir = dir;
}
Dir::eDir APlayer::getDir() const
{
return this->_dir;
}
size_t APlayer::getType() const
{
return this->_type;
}
void APlayer::setType(size_t t)
{
this->_type = t;
}
void APlayer::setName(std::string const& name)
{
this->_name = name;
}
void APlayer::setTeamName(std::string const& name)
{
this->_teamName = name;
}
std::string const& APlayer::getName() const
{
return this->_name;
}
std::string const& APlayer::getTeamName() const
{
return this->_teamName;
}
void APlayer::UPFunction(gdl::GameClock const& clock)
{
double current;
if ((current = static_cast<double>(clock.getTotalGameTime())) >=
this->_timers[HumGame::UP])
{
this->_timers[HumGame::UP] = current + 0.1;
this->_dir = Dir::NORTH;
if (this->_map.canMoveAt(this->_pos._x, this->_pos._y - 1))
this->_pos.setPos(this->_pos._x, this->_pos._y - 1);
}
}
void APlayer::LEFTFunction(gdl::GameClock const& clock)
{
double current;
if ((current = static_cast<double>(clock.getTotalGameTime())) >=
this->_timers[HumGame::LEFT])
{
this->_timers[HumGame::LEFT] = current + 0.1;
this->_dir = Dir::WEST;
if (this->_map.canMoveAt(this->_pos._x - 1, this->_pos._y))
this->_pos.setPos(this->_pos._x - 1, this->_pos._y);
}
}
void APlayer::RIGHTFunction(gdl::GameClock const& clock)
{
double current;
if ((current = static_cast<double>(clock.getTotalGameTime())) >=
this->_timers[HumGame::RIGHT])
{
this->_timers[HumGame::RIGHT] = current + 0.1;
this->_dir = Dir::EAST;
if (this->_map.canMoveAt(this->_pos._x + 1, this->_pos._y))
this->_pos.setPos(this->_pos._x + 1, this->_pos._y);
}
}
void APlayer::DOWNFunction(gdl::GameClock const& clock)
{
double current;
if ((current = static_cast<double>(clock.getTotalGameTime())) >=
this->_timers[HumGame::DOWN])
{
this->_timers[HumGame::DOWN] = current + 0.1;
this->_dir = Dir::SOUTH;
if (this->_map.canMoveAt(this->_pos._x, this->_pos._y + 1))
this->_pos.setPos(this->_pos._x, this->_pos._y + 1);
}
}
void APlayer::ATTACKFunction(gdl::GameClock const& clock)
{
double current;
if ((current = static_cast<double>(clock.getTotalGameTime())) >=
this->_timers[HumGame::ATTACK])
{
this->_timers[HumGame::ATTACK] = current + 1.5;
this->_attack = true;
}
}
Bomb* APlayer::isAttack()
{
if (!this->_attack)
return 0;
this->_attack(false);
return (new Bomb(this->_weapon, this->_pos, this->_id));
}
void APlayer::NORTHFunction()
{
glRotatef(90.0f, 0.0f, 1.0f, 0.0f);
}
void APlayer::SOUTHFunction()
{
glRotatef(-90.0f, 0.0f, 1.0f, 0.0f);
}
void APlayer::WESTFunction()
{
glRotatef(180.0f, 0.0f, 1.0f, 0.0f);
}
void APlayer::EASTFunction()
{
}
<commit_msg>Correction des fautes tek1 a busina<commit_after>/*
* Fiahil
* 12.05.2012
*/
#include <iostream>
#include <vector>
#include "APlayer.hpp"
APlayer::APlayer(Map & map)
: _map(map),
_pv(100),
_id(0),
_teamId(0),
_color(0),
_attack(false),
_timers(5, -1.0),
_weapon(BombType::NORMAL),
_skin(Skin::NORMAL),
_state(State::STATIC),
_dir(Dir::SOUTH),
_indic(0.5f, 0.5f, 0.8f, _color),
_rotFuncMap(Dir::LAST, 0)
{
this->_rotFuncMap[Dir::NORTH] = &APlayer::NORTHFunction;
this->_rotFuncMap[Dir::SOUTH] = &APlayer::SOUTHFunction;
this->_rotFuncMap[Dir::WEST] = &APlayer::WESTFunction;
this->_rotFuncMap[Dir::EAST] = &APlayer::EASTFunction;
this->_pos._scale = 2.0f;
this->setPos(1, 1);
this->_indic.setScale(2.0f);
this->_indic.setPos(1, 1);
}
APlayer::~APlayer()
{
}
void APlayer::initialize(void)
{
std::vector<std::string> refModel(Skin::LAST, "");
refModel[Skin::NORMAL] = "models/fifi.fbx";
this->_model = gdl::Model::load(refModel[this->_skin]);
this->_model.infos();
}
void APlayer::draw(void)
{
glPushMatrix();
glTranslatef(this->_pos._pos.x, this->_pos._pos.y - 1.0f, this->_pos._pos.z);
(this->*_rotFuncMap[this->_dir])();
// glScalef(0.005f, 0.005f, 0.005f);
glScalef(0.040f, 0.040f, 0.040f);
this->_model.draw();
glPopMatrix();
glPushMatrix();
glTranslatef(0.0f, 3.0f, 0.0f);
this->_indic.draw();
glPopMatrix();
}
void APlayer::update(gdl::GameClock const& clock, gdl::Input& input)
{
this->play(clock, input);
this->_model.update(clock);
this->_indic.setPos(this->_pos._x, this->_pos._y);
}
void APlayer::takeDamage(Pattern const&)
{
}
void APlayer::setPv(int pv)
{
this->_pv = pv;
}
int APlayer::getPv() const
{
return this->_pv;
}
void APlayer::setWeapon(BombType::eBomb weapon)
{
this->_weapon = weapon;
}
BombType::eBomb APlayer::getWeapon() const
{
return this->_weapon;
}
void APlayer::setTeamId(size_t team)
{
this->_teamId = team;
}
size_t APlayer::getTeamId() const
{
return this->_teamId;
}
void APlayer::setId(size_t id)
{
this->_id = id;
}
size_t APlayer::getId() const
{
return this->_id;
}
size_t APlayer::getColor() const
{
return this->_color;
}
void APlayer::setColor(size_t val)
{
this->_color = val;
this->_indic.setColor(val);
}
void APlayer::setState(State::eState state)
{
this->_state = state;
}
State::eState APlayer::getState() const
{
return this->_state;
}
void APlayer::setSkin(Skin::eSkin skin)
{
this->_skin = skin;
}
Skin::eSkin APlayer::getSkin(void) const
{
return this->_skin;
}
void APlayer::setDir(Dir::eDir dir)
{
this->_dir = dir;
}
Dir::eDir APlayer::getDir() const
{
return this->_dir;
}
size_t APlayer::getType() const
{
return this->_type;
}
void APlayer::setType(size_t t)
{
this->_type = t;
}
void APlayer::setName(std::string const& name)
{
this->_name = name;
}
void APlayer::setTeamName(std::string const& name)
{
this->_teamName = name;
}
std::string const& APlayer::getName() const
{
return this->_name;
}
std::string const& APlayer::getTeamName() const
{
return this->_teamName;
}
void APlayer::UPFunction(gdl::GameClock const& clock)
{
double current;
if ((current = static_cast<double>(clock.getTotalGameTime())) >=
this->_timers[HumGame::UP])
{
this->_timers[HumGame::UP] = current + 0.1;
this->_dir = Dir::NORTH;
if (this->_map.canMoveAt(this->_pos._x, this->_pos._y - 1))
this->_pos.setPos(this->_pos._x, this->_pos._y - 1);
}
}
void APlayer::LEFTFunction(gdl::GameClock const& clock)
{
double current;
if ((current = static_cast<double>(clock.getTotalGameTime())) >=
this->_timers[HumGame::LEFT])
{
this->_timers[HumGame::LEFT] = current + 0.1;
this->_dir = Dir::WEST;
if (this->_map.canMoveAt(this->_pos._x - 1, this->_pos._y))
this->_pos.setPos(this->_pos._x - 1, this->_pos._y);
}
}
void APlayer::RIGHTFunction(gdl::GameClock const& clock)
{
double current;
if ((current = static_cast<double>(clock.getTotalGameTime())) >=
this->_timers[HumGame::RIGHT])
{
this->_timers[HumGame::RIGHT] = current + 0.1;
this->_dir = Dir::EAST;
if (this->_map.canMoveAt(this->_pos._x + 1, this->_pos._y))
this->_pos.setPos(this->_pos._x + 1, this->_pos._y);
}
}
void APlayer::DOWNFunction(gdl::GameClock const& clock)
{
double current;
if ((current = static_cast<double>(clock.getTotalGameTime())) >=
this->_timers[HumGame::DOWN])
{
this->_timers[HumGame::DOWN] = current + 0.1;
this->_dir = Dir::SOUTH;
if (this->_map.canMoveAt(this->_pos._x, this->_pos._y + 1))
this->_pos.setPos(this->_pos._x, this->_pos._y + 1);
}
}
void APlayer::ATTACKFunction(gdl::GameClock const& clock)
{
double current;
if ((current = static_cast<double>(clock.getTotalGameTime())) >=
this->_timers[HumGame::ATTACK])
{
this->_timers[HumGame::ATTACK] = current + 1.5;
this->_attack = true;
}
}
Bomb* APlayer::isAttack()
{
if (!this->_attack)
return 0;
this->_attack = false;
return (new Bomb(this->_weapon, this->_pos, this->_id));
}
void APlayer::NORTHFunction()
{
glRotatef(90.0f, 0.0f, 1.0f, 0.0f);
}
void APlayer::SOUTHFunction()
{
glRotatef(-90.0f, 0.0f, 1.0f, 0.0f);
}
void APlayer::WESTFunction()
{
glRotatef(180.0f, 0.0f, 1.0f, 0.0f);
}
void APlayer::EASTFunction()
{
}
<|endoftext|> |
<commit_before>/*
* This file is part of the µOS++ distribution.
* (https://github.com/micro-os-plus)
* Copyright (c) 2016 Liviu Ionescu.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom
* the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* This file is part of the CMSIS++ proposal, intended as a CMSIS
* replacement for C++ applications.
*
* [Partly inspired from the LLVM libcxx sources].
* Copyright (c) 2009-2013 by the contributors listed in
* 'LLVM libcxx Credits.txt'. See 'LLVM libcxx License.txt' for details.
*
* References are to ISO/IEC 14882:2011(E) Third edition (2011-09-01)
*/
/**
* @file
* @brief Global synchronised new/delete definitions.
*/
#include <cmsis-plus/rtos/os.h>
#include <cmsis-plus/estd/memory_resource>
// ----------------------------------------------------------------------------
using namespace os;
// ----------------------------------------------------------------------------
namespace
{
/**
* @brief The current new handler.
* @details
* The initial new_handler is a null pointer, initialised as
* part of the .bss section.
*/
std::new_handler __new_handler;
}
namespace std
{
// Constant to be used as parameter to differentiate
// the `noexcept` functions.
const nothrow_t nothrow = nothrow_t
{ };
/**
* @brief Establishes the function designated by handler
* as the current `new_handler`.
* @param handler Pointer to user function.
* @return The previous handler.
* @details
* The initial `new_handler` is a null pointer.
*/
new_handler
set_new_handler (new_handler handler) noexcept
{
new_handler prev_handler;
prev_handler = __new_handler;
__new_handler = handler;
return prev_handler;
}
new_handler
get_new_handler () noexcept
{
return __new_handler;
}
} /* namespace std */
// ----------------------------------------------------------------------------
/**
* @details
* The allocation function (3.7.4.1) called by a new-expression (5.3.4)
* to allocate size bytes of storage suitably aligned to represent
* any object of that size.
*
* Return a non-null pointer to suitably aligned storage (3.7.4),
* or else throw a `bad-alloc` exception. This requirement is
* binding on a replacement version of this function.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void *
__attribute__((weak))
operator new (std::size_t size)
{
if (size == 0)
{
size = 1;
}
// ----- Begin of critical section ------------------------------------------
rtos::scheduler::critical_section cs;
while (true)
{
void* p = estd::pmr::get_default_resource ()->allocate (size);
if (p != nullptr)
{
return p;
}
// If allocate() fails and there is a new_handler,
// call it to try free up memory.
if (__new_handler)
{
__new_handler ();
}
else
{
estd::__throw_bad_alloc ();
}
}
// ----- End of critical section --------------------------------------------
}
/**
* @details
* Same as new(size), except that it is called by a placement
* version of a new-expression when a C++ program prefers a null
* pointer result as an error indication, instead of a bad_alloc exception.
*
* Return a non-null pointer to suitably aligned storage (3.7.4),
* or else return a null pointer. This nothrow version of operator new
* returns a pointer obtained as if acquired from the (possibly replaced)
* ordinary version. This requirement is binding on a replacement
* version of this function.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void*
__attribute__((weak))
operator new (std::size_t size, const std::nothrow_t&) noexcept
{
if (size == 0)
{
size = 1;
}
// ----- Begin of critical section ------------------------------------------
rtos::scheduler::critical_section cs;
while (true)
{
void* p = estd::pmr::get_default_resource ()->allocate (size);
if (p != nullptr)
{
return p;
}
// If allocate() fails and there is a new_handler,
// call it to try free up memory.
if (__new_handler)
{
__new_handler ();
}
else
{
break; // return nullptr
}
}
// ----- End of critical section --------------------------------------------
return nullptr;
}
/**
* @details
* The allocation function (3.7.4.1) called by the array form of a
* new-expression (5.3.4) to allocate size bytes of storage suitably
* aligned to represent any array object of that size or smaller.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void*
__attribute__((weak))
operator new[] (std::size_t size)
{
return ::operator new (size);
}
/**
* @details
* Same as new[](size), except that it is called by a placement
* version of a new-expression when a C++ program prefers a null
* pointer result as an error indication, instead of a bad_alloc exception.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void*
__attribute__((weak))
operator new[] (std::size_t size, const std::nothrow_t&) noexcept
{
return ::operator new (size, std::nothrow);
}
// ----------------------------------------------------------------------------
/**
* @details
* The deallocation function (3.7.4.2) called by a delete-expression
* to render the value of ptr invalid.
*
* ptr shall be a null pointer or its value shall be a value returned by
* an earlier call to the (possibly replaced) operator new(os::std::size_t)
* or operator new(os::std::size_t,const std::nothrow_t&) which has not
* been invalidated by an intervening call to operator delete(void*).
*
* If ptr is null, does nothing. Otherwise, reclaims the storage
* allocated by the earlier call to operator new.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void
__attribute__((weak))
operator delete (void* ptr) noexcept
{
if (ptr)
{
// ----- Begin of critical section --------------------------------------
rtos::scheduler::critical_section cs;
// The unknown size is passed as 0.
estd::pmr::get_default_resource ()->deallocate (ptr, 0);
// ----- End of critical section ----------------------------------------
}
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wc++14-compat"
void
operator delete (void* ptr, std::size_t size) noexcept;
void
__attribute__((weak))
operator delete (void* ptr, std::size_t size) noexcept
{
if (ptr)
{
// ----- Begin of critical section --------------------------------------
rtos::scheduler::critical_section cs;
estd::pmr::get_default_resource ()->deallocate (ptr, size);
// ----- End of critical section ----------------------------------------
}
}
#pragma GCC diagnostic pop
/**
* @details
* The deallocation function (3.7.4.2) called by the implementation
* to render the value of ptr invalid when the constructor invoked
* from a nothrow placement version of the new-expression throws
* an exception.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void
__attribute__((weak))
operator delete (void* ptr, const std::nothrow_t&) noexcept
{
if (ptr)
{
// ----- Begin of critical section --------------------------------------
rtos::scheduler::critical_section cs;
estd::pmr::get_default_resource ()->deallocate (ptr, 0);
// ----- End of critical section ----------------------------------------
}
}
/**
* @details
* The deallocation function (3.7.4.2) called by the array form of
* a delete-expression to render the value of ptr invalid.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void
__attribute__((weak))
operator delete[] (void* ptr) noexcept
{
::operator delete (ptr);
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wc++14-compat"
void
operator delete[] (void* ptr, std::size_t size) noexcept;
void
__attribute__((weak))
operator delete[] (void* ptr, std::size_t size) noexcept
{
::operator delete (ptr, size);
}
#pragma GCC diagnostic pop
/**
* @details
* The deallocation function (3.7.4.2) called by the implementation to
* render the value of ptr invalid when the constructor invoked
* from a nothrow placement version of the array new-expression
* throws an exception.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void
__attribute__((weak))
operator delete[] (void* ptr, const std::nothrow_t& nothrow) noexcept
{
::operator delete (ptr, nothrow);
}
// ----------------------------------------------------------------------------
<commit_msg>libcpp/new: cosmetics<commit_after>/*
* This file is part of the µOS++ distribution.
* (https://github.com/micro-os-plus)
* Copyright (c) 2016 Liviu Ionescu.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom
* the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* This file is part of the CMSIS++ proposal, intended as a CMSIS
* replacement for C++ applications.
*
* [Partly inspired from the LLVM libcxx sources].
* Copyright (c) 2009-2013 by the contributors listed in
* 'LLVM libcxx Credits.txt'. See 'LLVM libcxx License.txt' for details.
*
* References are to ISO/IEC 14882:2011(E) Third edition (2011-09-01)
*/
/**
* @file
* @brief Global synchronised new/delete definitions.
*/
#include <cmsis-plus/rtos/os.h>
#include <cmsis-plus/estd/memory_resource>
// ----------------------------------------------------------------------------
using namespace os;
// ----------------------------------------------------------------------------
namespace
{
/**
* @brief The current new handler.
* @details
* The initial new_handler is a null pointer, initialised as
* part of the .bss section.
*/
std::new_handler new_handler_;
}
namespace std
{
// Constant to be used as parameter to differentiate
// the `noexcept` functions.
const nothrow_t nothrow = nothrow_t
{ };
/**
* @brief Establishes the function designated by handler
* as the current `new_handler`.
* @param handler Pointer to user function.
* @return The previous handler.
* @details
* The initial `new_handler` is a null pointer.
*/
new_handler
set_new_handler (new_handler handler) noexcept
{
trace::printf ("std::%s(%p) \n", __func__, handler);
new_handler prev_handler;
prev_handler = new_handler_;
new_handler_ = handler;
return prev_handler;
}
new_handler
get_new_handler () noexcept
{
return new_handler_;
}
} /* namespace std */
// ----------------------------------------------------------------------------
/**
* @details
* The allocation function (3.7.4.1) called by a new-expression (5.3.4)
* to allocate size bytes of storage suitably aligned to represent
* any object of that size.
*
* Return a non-null pointer to suitably aligned storage (3.7.4),
* or else throw a `bad-alloc` exception. This requirement is
* binding on a replacement version of this function.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void *
__attribute__((weak))
operator new (std::size_t bytes)
{
if (bytes == 0)
{
bytes = 1;
}
// ----- Begin of critical section ------------------------------------------
rtos::scheduler::critical_section scs;
while (true)
{
void* mem = estd::pmr::get_default_resource ()->allocate (bytes);
if (mem != nullptr)
{
#if defined(OS_TRACE_LIBCPP_OPERATOR_NEW)
trace::printf ("::%s(%d)=%p\n", __func__, bytes, mem);
#endif
return mem;
}
// If allocate() fails and there is a new_handler,
// call it to try free up memory.
if (new_handler_)
{
new_handler_ ();
}
else
{
estd::__throw_bad_alloc ();
}
}
// ----- End of critical section --------------------------------------------
}
/**
* @details
* Same as new(size), except that it is called by a placement
* version of a new-expression when a C++ program prefers a null
* pointer result as an error indication, instead of a bad_alloc exception.
*
* Return a non-null pointer to suitably aligned storage (3.7.4),
* or else return a null pointer. This nothrow version of operator new
* returns a pointer obtained as if acquired from the (possibly replaced)
* ordinary version. This requirement is binding on a replacement
* version of this function.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void*
__attribute__((weak))
operator new (std::size_t bytes, const std::nothrow_t&) noexcept
{
if (bytes == 0)
{
bytes = 1;
}
// ----- Begin of critical section ------------------------------------------
rtos::scheduler::critical_section scs;
while (true)
{
void* mem = estd::pmr::get_default_resource ()->allocate (bytes);
if (mem != nullptr)
{
#if defined(OS_TRACE_LIBCPP_OPERATOR_NEW)
trace::printf ("::%s(%d)=%p\n", __func__, bytes, mem);
#endif
return mem;
}
// If allocate() fails and there is a new_handler,
// call it to try free up memory.
if (new_handler_)
{
new_handler_ ();
}
else
{
break; // return nullptr
}
}
// ----- End of critical section --------------------------------------------
return nullptr;
}
/**
* @details
* The allocation function (3.7.4.1) called by the array form of a
* new-expression (5.3.4) to allocate size bytes of storage suitably
* aligned to represent any array object of that size or smaller.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void*
__attribute__((weak))
operator new[] (std::size_t bytes)
{
return ::operator new (bytes);
}
/**
* @details
* Same as new[](size), except that it is called by a placement
* version of a new-expression when a C++ program prefers a null
* pointer result as an error indication, instead of a bad_alloc exception.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void*
__attribute__((weak))
operator new[] (std::size_t bytes, const std::nothrow_t&) noexcept
{
return ::operator new (bytes, std::nothrow);
}
// ----------------------------------------------------------------------------
/**
* @details
* The deallocation function (3.7.4.2) called by a delete-expression
* to render the value of ptr invalid.
*
* ptr shall be a null pointer or its value shall be a value returned by
* an earlier call to the (possibly replaced) operator new(os::std::size_t)
* or operator new(os::std::size_t,const std::nothrow_t&) which has not
* been invalidated by an intervening call to operator delete(void*).
*
* If ptr is null, does nothing. Otherwise, reclaims the storage
* allocated by the earlier call to operator new.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void
__attribute__((weak))
operator delete (void* ptr) noexcept
{
#if defined(OS_TRACE_LIBCPP_OPERATOR_NEW)
trace::printf ("::%s(%p)\n", __func__, ptr);
#endif
if (ptr)
{
// ----- Begin of critical section --------------------------------------
rtos::scheduler::critical_section scs;
// The unknown size is passed as 0.
estd::pmr::get_default_resource ()->deallocate (ptr, 0);
// ----- End of critical section ----------------------------------------
}
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wc++14-compat"
void
operator delete (void* ptr, std::size_t bytes) noexcept;
void
__attribute__((weak))
operator delete (void* ptr, std::size_t bytes) noexcept
{
#if defined(OS_TRACE_LIBCPP_OPERATOR_NEW)
trace::printf ("::%s(%p,%u)\n", __func__, ptr, bytes);
#endif
if (ptr)
{
// ----- Begin of critical section --------------------------------------
rtos::scheduler::critical_section scs;
estd::pmr::get_default_resource ()->deallocate (ptr, bytes);
// ----- End of critical section ----------------------------------------
}
}
#pragma GCC diagnostic pop
/**
* @details
* The deallocation function (3.7.4.2) called by the implementation
* to render the value of ptr invalid when the constructor invoked
* from a nothrow placement version of the new-expression throws
* an exception.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void
__attribute__((weak))
operator delete (void* ptr, const std::nothrow_t&) noexcept
{
#if defined(OS_TRACE_LIBCPP_OPERATOR_NEW)
trace::printf ("::%s(%p)\n", __func__, ptr);
#endif
if (ptr)
{
// ----- Begin of critical section --------------------------------------
rtos::scheduler::critical_section scs;
estd::pmr::get_default_resource ()->deallocate (ptr, 0);
// ----- End of critical section ----------------------------------------
}
}
/**
* @details
* The deallocation function (3.7.4.2) called by the array form of
* a delete-expression to render the value of ptr invalid.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void
__attribute__((weak))
operator delete[] (void* ptr) noexcept
{
::operator delete (ptr);
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wc++14-compat"
void
operator delete[] (void* ptr, std::size_t bytes) noexcept;
void
__attribute__((weak))
operator delete[] (void* ptr, std::size_t bytes) noexcept
{
::operator delete (ptr, bytes);
}
#pragma GCC diagnostic pop
/**
* @details
* The deallocation function (3.7.4.2) called by the implementation to
* render the value of ptr invalid when the constructor invoked
* from a nothrow placement version of the array new-expression
* throws an exception.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void
__attribute__((weak))
operator delete[] (void* ptr, const std::nothrow_t& nothrow) noexcept
{
::operator delete (ptr, nothrow);
}
// ----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/* Copyright (c) 2012 QtHttpServer Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the QtHttpServer 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 QTHTTPSERVER 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 "qhttpreply.h"
#include <QtNetwork/QNetworkCookie>
#include "qhttpconnection_p.h"
#include "qhttprequest.h"
#include <zlib.h>
class QHttpReply::Private : public QObject
{
Q_OBJECT
public:
Private(QHttpConnection *c, QHttpReply *parent);
public slots:
void close();
private:
QHttpReply *q;
static QHash<int, QByteArray> statusCodes;
public:
QHttpConnection *connection;
int status;
QHash<QByteArray, QByteArray> rawHeaders;
QList<QNetworkCookie> cookies;
QByteArray data;
};
QHash<int, QByteArray> QHttpReply::Private::statusCodes;
QHttpReply::Private::Private(QHttpConnection *c, QHttpReply *parent)
: QObject(parent)
, q(parent)
, connection(c)
, status(200)
{
if (statusCodes.isEmpty()) {
statusCodes.insert(100, "Continue");
statusCodes.insert(101, "Switching Protocols");
statusCodes.insert(200, "OK");
statusCodes.insert(201, "Created");
statusCodes.insert(202, "Accepted");
statusCodes.insert(203, "Non-Authoritative Information");
statusCodes.insert(204, "No Content");
statusCodes.insert(205, "Reset Content");
statusCodes.insert(206, "Partial Content");
statusCodes.insert(300, "Multiple Choices");
statusCodes.insert(301, "Moved Permanently");
statusCodes.insert(302, "Found");
statusCodes.insert(303, "See Other");
statusCodes.insert(304, "Not Modified");
statusCodes.insert(305, "Use Proxy");
statusCodes.insert(307, "Temporary Redirect");
statusCodes.insert(400, "Bad Request");
statusCodes.insert(401, "Unauthorized");
statusCodes.insert(402, "Payment Required");
statusCodes.insert(403, "Forbidden");
statusCodes.insert(404, "Not Found");
statusCodes.insert(405, "Method Not Allowed");
statusCodes.insert(406, "Not Acceptable");
statusCodes.insert(407, "Proxy Authentication Required");
statusCodes.insert(408, "Request Time-out");
statusCodes.insert(409, "Conflict");
statusCodes.insert(410, "Gone");
statusCodes.insert(411, "Length Required");
statusCodes.insert(412, "Precondition Failed");
statusCodes.insert(413, "Request Entity Too Large");
statusCodes.insert(414, "Request-URI Too Large");
statusCodes.insert(415, "Unsupported Media Type");
statusCodes.insert(416, "Requested range not satisfiable");
statusCodes.insert(417, "Expectation Failed");
statusCodes.insert(500, "Internal Server Error");
statusCodes.insert(501, "Not Implemented");
statusCodes.insert(502, "Bad Gateway");
statusCodes.insert(503, "Service Unavailable");
statusCodes.insert(504, "Gateway Time-out");
statusCodes.insert(505, "HTTP Version not supported");
}
q->setBuffer(&data);
q->open(QIODevice::WriteOnly);
}
void QHttpReply::Private::close()
{
connection->write("HTTP/1.1 ");
connection->write(QByteArray::number(status));
connection->write(" ");
connection->write(statusCodes.value(status));
connection->write("\r\n");
const QHttpRequest *request = connection->requestFor(q);
if (request && request->hasRawHeader("Accept-Encoding")) {
QList<QByteArray> acceptEncodings = request->rawHeader("Accept-Encoding").split(',');
if (acceptEncodings.contains("deflate")) {
z_stream z;
z.zalloc = NULL;
z.zfree = NULL;
z.opaque = NULL;
if (deflateInit(&z, Z_DEFAULT_COMPRESSION) == Z_OK) {
// qDebug() << Q_FUNC_INFO << __LINE__ << data.length();
QByteArray newData;
unsigned char buf[1024];
z.avail_in = data.size();
z.next_in = reinterpret_cast<Bytef*>(data.data());
z.avail_out = 1024;
z.next_out = buf;
int ret = Z_OK;
while (ret == Z_OK) {
// qDebug() << Q_FUNC_INFO << __LINE__ << z.avail_in << z.avail_out;
ret = deflate(&z, Z_FINISH);
// qDebug() << Q_FUNC_INFO << __LINE__ << z.avail_in << z.avail_out << ret;
if (ret == Z_STREAM_END) {
newData.append((const char*)buf, 1024 - z.avail_out);
connection->write("Content-Encoding: deflate\r\n");
data = newData;
// qDebug() << "END";
break;
} else if (ret != Z_OK) {
// qDebug() << Q_FUNC_INFO << __LINE__ << ret << z.msg;
}
if (z.avail_out == 0) {
newData.append((const char*)buf, 1024);
z.avail_out = 1024;
z.next_out = buf;
}
}
// qDebug() << Q_FUNC_INFO << __LINE__ << newData.length();
}
}
}
foreach (const QByteArray &rawHeader, rawHeaders.keys()) {
connection->write(rawHeader);
connection->write(": ");
connection->write(rawHeaders.value(rawHeader));
connection->write("\r\n");
}
foreach (const QNetworkCookie &cookie, cookies) {
connection->write("Set-Cookie: ");
connection->write(cookie.toRawForm());
connection->write(";\r\n");
}
connection->write(QString::fromUtf8("Content-Length: %1\r\n").arg(data.length()).toLatin1());
connection->write("\r\n");
connection->write(data);
q->deleteLater();
}
QHttpReply::QHttpReply(QHttpConnection *parent)
: QBuffer(parent)
, d(new Private(parent, this))
{
}
QHttpReply::~QHttpReply()
{
delete d;
}
int QHttpReply::status() const
{
return d->status;
}
void QHttpReply::setStatus(int status)
{
d->status = status;
}
bool QHttpReply::hasRawHeader(const QByteArray &headerName) const
{
return d->rawHeaders.contains(headerName);
}
//QVariant QHttpReply::header(KnownHeaders header) const
//{
// return QVariant();
//}
QByteArray QHttpReply::rawHeader(const QByteArray &headerName) const
{
return d->rawHeaders.value(headerName);
}
void QHttpReply::setRawHeader(const QByteArray &headerName, const QByteArray &value)
{
d->rawHeaders.insert(headerName, value);
}
QList<QByteArray> QHttpReply::rawHeaderList() const
{
return d->rawHeaders.keys();
}
const QList<QNetworkCookie> &QHttpReply::cookies() const
{
return d->cookies;
}
void QHttpReply::setCookies(const QList<QNetworkCookie> &cookies)
{
if (d->cookies == cookies) return;
d->cookies = cookies;
}
void QHttpReply::close()
{
QBuffer::close();
// QMetaObject::invokeMethod(d, "close", Qt::QueuedConnection);
d->close();
}
#include "qhttpreply.moc"
<commit_msg>fix header duplication issue<commit_after>/* Copyright (c) 2012 QtHttpServer Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the QtHttpServer 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 QTHTTPSERVER 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 "qhttpreply.h"
#include <QtNetwork/QNetworkCookie>
#include "qhttpconnection_p.h"
#include "qhttprequest.h"
#include <zlib.h>
class QHttpReply::Private : public QObject
{
Q_OBJECT
public:
Private(QHttpConnection *c, QHttpReply *parent);
public slots:
void close();
private:
QHttpReply *q;
static QHash<int, QByteArray> statusCodes;
public:
QHttpConnection *connection;
int status;
QHash<QByteArray, QByteArray> rawHeaders;
QList<QNetworkCookie> cookies;
QByteArray data;
};
QHash<int, QByteArray> QHttpReply::Private::statusCodes;
QHttpReply::Private::Private(QHttpConnection *c, QHttpReply *parent)
: QObject(parent)
, q(parent)
, connection(c)
, status(200)
{
if (statusCodes.isEmpty()) {
statusCodes.insert(100, "Continue");
statusCodes.insert(101, "Switching Protocols");
statusCodes.insert(200, "OK");
statusCodes.insert(201, "Created");
statusCodes.insert(202, "Accepted");
statusCodes.insert(203, "Non-Authoritative Information");
statusCodes.insert(204, "No Content");
statusCodes.insert(205, "Reset Content");
statusCodes.insert(206, "Partial Content");
statusCodes.insert(300, "Multiple Choices");
statusCodes.insert(301, "Moved Permanently");
statusCodes.insert(302, "Found");
statusCodes.insert(303, "See Other");
statusCodes.insert(304, "Not Modified");
statusCodes.insert(305, "Use Proxy");
statusCodes.insert(307, "Temporary Redirect");
statusCodes.insert(400, "Bad Request");
statusCodes.insert(401, "Unauthorized");
statusCodes.insert(402, "Payment Required");
statusCodes.insert(403, "Forbidden");
statusCodes.insert(404, "Not Found");
statusCodes.insert(405, "Method Not Allowed");
statusCodes.insert(406, "Not Acceptable");
statusCodes.insert(407, "Proxy Authentication Required");
statusCodes.insert(408, "Request Time-out");
statusCodes.insert(409, "Conflict");
statusCodes.insert(410, "Gone");
statusCodes.insert(411, "Length Required");
statusCodes.insert(412, "Precondition Failed");
statusCodes.insert(413, "Request Entity Too Large");
statusCodes.insert(414, "Request-URI Too Large");
statusCodes.insert(415, "Unsupported Media Type");
statusCodes.insert(416, "Requested range not satisfiable");
statusCodes.insert(417, "Expectation Failed");
statusCodes.insert(500, "Internal Server Error");
statusCodes.insert(501, "Not Implemented");
statusCodes.insert(502, "Bad Gateway");
statusCodes.insert(503, "Service Unavailable");
statusCodes.insert(504, "Gateway Time-out");
statusCodes.insert(505, "HTTP Version not supported");
}
q->setBuffer(&data);
q->open(QIODevice::WriteOnly);
}
void QHttpReply::Private::close()
{
connection->write("HTTP/1.1 ");
connection->write(QByteArray::number(status));
connection->write(" ");
connection->write(statusCodes.value(status));
connection->write("\r\n");
const QHttpRequest *request = connection->requestFor(q);
if (request && request->hasRawHeader("Accept-Encoding") && !rawHeaders.contains("Content-Encoding")) {
QList<QByteArray> acceptEncodings = request->rawHeader("Accept-Encoding").split(',');
if (acceptEncodings.contains("deflate")) {
z_stream z;
z.zalloc = NULL;
z.zfree = NULL;
z.opaque = NULL;
if (deflateInit(&z, Z_DEFAULT_COMPRESSION) == Z_OK) {
// qDebug() << Q_FUNC_INFO << __LINE__ << data.length();
QByteArray newData;
unsigned char buf[1024];
z.avail_in = data.size();
z.next_in = reinterpret_cast<Bytef*>(data.data());
z.avail_out = 1024;
z.next_out = buf;
int ret = Z_OK;
while (ret == Z_OK) {
// qDebug() << Q_FUNC_INFO << __LINE__ << z.avail_in << z.avail_out;
ret = deflate(&z, Z_FINISH);
// qDebug() << Q_FUNC_INFO << __LINE__ << z.avail_in << z.avail_out << ret;
if (ret == Z_STREAM_END) {
newData.append((const char*)buf, 1024 - z.avail_out);
connection->write("Content-Encoding: deflate\r\n");
data = newData;
// qDebug() << "END";
break;
} else if (ret != Z_OK) {
// qDebug() << Q_FUNC_INFO << __LINE__ << ret << z.msg;
}
if (z.avail_out == 0) {
newData.append((const char*)buf, 1024);
z.avail_out = 1024;
z.next_out = buf;
}
}
// qDebug() << Q_FUNC_INFO << __LINE__ << newData.length();
}
}
}
if (!rawHeaders.contains("Content-Length")) {
rawHeaders.insert("Content-Length", QString::number(data.length()).toUtf8());
}
foreach (const QByteArray &rawHeader, rawHeaders.keys()) {
connection->write(rawHeader);
connection->write(": ");
connection->write(rawHeaders.value(rawHeader));
connection->write("\r\n");
}
foreach (const QNetworkCookie &cookie, cookies) {
connection->write("Set-Cookie: ");
connection->write(cookie.toRawForm());
connection->write(";\r\n");
}
connection->write("\r\n");
connection->write(data);
q->deleteLater();
}
QHttpReply::QHttpReply(QHttpConnection *parent)
: QBuffer(parent)
, d(new Private(parent, this))
{
}
QHttpReply::~QHttpReply()
{
delete d;
}
int QHttpReply::status() const
{
return d->status;
}
void QHttpReply::setStatus(int status)
{
d->status = status;
}
bool QHttpReply::hasRawHeader(const QByteArray &headerName) const
{
return d->rawHeaders.contains(headerName);
}
//QVariant QHttpReply::header(KnownHeaders header) const
//{
// return QVariant();
//}
QByteArray QHttpReply::rawHeader(const QByteArray &headerName) const
{
return d->rawHeaders.value(headerName);
}
void QHttpReply::setRawHeader(const QByteArray &headerName, const QByteArray &value)
{
d->rawHeaders.insert(headerName, value);
}
QList<QByteArray> QHttpReply::rawHeaderList() const
{
return d->rawHeaders.keys();
}
const QList<QNetworkCookie> &QHttpReply::cookies() const
{
return d->cookies;
}
void QHttpReply::setCookies(const QList<QNetworkCookie> &cookies)
{
if (d->cookies == cookies) return;
d->cookies = cookies;
}
void QHttpReply::close()
{
QBuffer::close();
// QMetaObject::invokeMethod(d, "close", Qt::QueuedConnection);
d->close();
}
#include "qhttpreply.moc"
<|endoftext|> |
<commit_before>#include "ff_klm.h"
#include <cstring>
#include "hg.h"
#include "tdict.h"
#include "lm/enumerate_vocab.hh"
using namespace std;
static const unsigned char HAS_FULL_CONTEXT = 1;
static const unsigned char HAS_EOS_ON_RIGHT = 2;
static const unsigned char MASK = 7;
template <class Model>
string KLanguageModel<Model>::usage(bool /*param*/,bool /*verbose*/) {
return "KLanguageModel";
}
struct VMapper : public lm::ngram::EnumerateVocab {
VMapper(vector<lm::WordIndex>* out) : out_(out), kLM_UNKNOWN_TOKEN(0) { out_->clear(); }
void Add(lm::WordIndex index, const StringPiece &str) {
const WordID cdec_id = TD::Convert(str.as_string());
if (cdec_id >= out_->size())
out_->resize(cdec_id + 1, kLM_UNKNOWN_TOKEN);
(*out_)[cdec_id] = index;
}
vector<lm::WordIndex>* out_;
const lm::WordIndex kLM_UNKNOWN_TOKEN;
};
template <class Model>
class KLanguageModelImpl {
// returns the number of unscored words at the left edge of a span
inline int UnscoredSize(const void* state) const {
return *(static_cast<const char*>(state) + unscored_size_offset_);
}
inline void SetUnscoredSize(int size, void* state) const {
*(static_cast<char*>(state) + unscored_size_offset_) = size;
}
static inline const lm::ngram::State& RemnantLMState(const void* state) {
return *static_cast<const lm::ngram::State*>(state);
}
inline void SetRemnantLMState(const lm::ngram::State& lmstate, void* state) const {
// if we were clever, we could use the memory pointed to by state to do all
// the work, avoiding this copy
memcpy(state, &lmstate, ngram_->StateSize());
}
lm::WordIndex IthUnscoredWord(int i, const void* state) const {
const lm::WordIndex* const mem = reinterpret_cast<const lm::WordIndex*>(static_cast<const char*>(state) + unscored_words_offset_);
return mem[i];
}
void SetIthUnscoredWord(int i, lm::WordIndex index, void *state) const {
lm::WordIndex* mem = reinterpret_cast<lm::WordIndex*>(static_cast<char*>(state) + unscored_words_offset_);
mem[i] = index;
}
inline bool GetFlag(const void *state, unsigned char flag) const {
return (*(static_cast<const char*>(state) + is_complete_offset_) & flag);
}
inline void SetFlag(bool on, unsigned char flag, void *state) const {
if (on) {
*(static_cast<char*>(state) + is_complete_offset_) |= flag;
} else {
*(static_cast<char*>(state) + is_complete_offset_) &= (MASK ^ flag);
}
}
inline bool HasFullContext(const void *state) const {
return GetFlag(state, HAS_FULL_CONTEXT);
}
inline void SetHasFullContext(bool flag, void *state) const {
SetFlag(flag, HAS_FULL_CONTEXT, state);
}
public:
double LookupWords(const TRule& rule, const vector<const void*>& ant_states, double* pest_sum, void* remnant) {
double sum = 0.0;
double est_sum = 0.0;
int num_scored = 0;
int num_estimated = 0;
bool saw_eos = false;
bool has_some_history = false;
lm::ngram::State state = ngram_->NullContextState();
const vector<WordID>& e = rule.e();
bool context_complete = false;
for (int j = 0; j < e.size(); ++j) {
if (e[j] < 1) { // handle non-terminal substitution
const void* astate = (ant_states[-e[j]]);
int unscored_ant_len = UnscoredSize(astate);
for (int k = 0; k < unscored_ant_len; ++k) {
const lm::WordIndex cur_word = IthUnscoredWord(k, astate);
double p = 0;
if (cur_word == kSOS_) {
state = ngram_->BeginSentenceState();
if (has_some_history) { // this is immediately fully scored, and bad
p = -100;
context_complete = true;
} else { // this might be a real <s>
num_scored = max(0, order_ - 2);
}
} else {
const lm::ngram::State scopy(state);
p = ngram_->Score(scopy, cur_word, state);
if (saw_eos) { p = -100; }
saw_eos = (cur_word == kEOS_);
}
has_some_history = true;
++num_scored;
if (!context_complete) {
if (num_scored >= order_) context_complete = true;
}
if (context_complete) {
sum += p;
} else {
if (remnant)
SetIthUnscoredWord(num_estimated, cur_word, remnant);
++num_estimated;
est_sum += p;
}
}
saw_eos = GetFlag(astate, HAS_EOS_ON_RIGHT);
if (HasFullContext(astate)) { // this is equivalent to the "star" in Chiang 2007
state = RemnantLMState(astate);
context_complete = true;
}
} else { // handle terminal
const lm::WordIndex cur_word = MapWord(e[j]);
double p = 0;
if (cur_word == kSOS_) {
state = ngram_->BeginSentenceState();
if (has_some_history) { // this is immediately fully scored, and bad
p = -100;
context_complete = true;
} else { // this might be a real <s>
num_scored = max(0, order_ - 2);
}
} else {
const lm::ngram::State scopy(state);
p = ngram_->Score(scopy, cur_word, state);
if (saw_eos) { p = -100; }
saw_eos = (cur_word == kEOS_);
}
has_some_history = true;
++num_scored;
if (!context_complete) {
if (num_scored >= order_) context_complete = true;
}
if (context_complete) {
sum += p;
} else {
if (remnant)
SetIthUnscoredWord(num_estimated, cur_word, remnant);
++num_estimated;
est_sum += p;
}
}
}
if (pest_sum) *pest_sum = est_sum;
if (remnant) {
state.ZeroRemaining();
SetFlag(saw_eos, HAS_EOS_ON_RIGHT, remnant);
SetRemnantLMState(state, remnant);
SetUnscoredSize(num_estimated, remnant);
SetHasFullContext(context_complete || (num_scored >= order_), remnant);
}
return sum;
}
//FIXME: this assumes no target words on final unary -> goal rule. is that ok?
// for <s> (n-1 left words) and (n-1 right words) </s>
double FinalTraversalCost(const void* state) {
if (add_sos_eos_) {
SetRemnantLMState(ngram_->BeginSentenceState(), dummy_state_);
SetHasFullContext(1, dummy_state_);
SetUnscoredSize(0, dummy_state_);
dummy_ants_[1] = state;
return LookupWords(*dummy_rule_, dummy_ants_, NULL, NULL);
} else {
// TODO, figure out whether spans are correct
return 0;
}
}
lm::WordIndex MapWord(WordID w) const {
if (w >= map_.size())
return 0;
else
return map_[w];
}
public:
KLanguageModelImpl(const std::string& param) {
add_sos_eos_ = true;
string fname = param;
if (param.find("-x ") == 0) {
add_sos_eos_ = false;
fname = param.substr(3);
}
lm::ngram::Config conf;
VMapper vm(&map_);
conf.enumerate_vocab = &vm;
ngram_ = new Model(fname.c_str(), conf);
order_ = ngram_->Order();
cerr << "Loaded " << order_ << "-gram KLM from " << fname << " (MapSize=" << map_.size() << ")\n";
state_size_ = ngram_->StateSize() + 2 + (order_ - 1) * sizeof(lm::WordIndex);
unscored_size_offset_ = ngram_->StateSize();
is_complete_offset_ = unscored_size_offset_ + 1;
unscored_words_offset_ = is_complete_offset_ + 1;
// special handling of beginning / ending sentence markers
dummy_state_ = new char[state_size_];
dummy_ants_.push_back(dummy_state_);
dummy_ants_.push_back(NULL);
dummy_rule_.reset(new TRule("[DUMMY] ||| [BOS] [DUMMY] ||| [1] [2] </s> ||| X=0"));
kSOS_ = MapWord(TD::Convert("<s>"));
assert(kSOS_ > 0);
kEOS_ = MapWord(TD::Convert("</s>"));
assert(kEOS_ > 0);
}
~KLanguageModelImpl() {
delete ngram_;
delete[] dummy_state_;
}
int ReserveStateSize() const { return state_size_; }
private:
lm::WordIndex kSOS_; // <s> - requires special handling.
lm::WordIndex kEOS_; // </s>
Model* ngram_;
bool add_sos_eos_; // flag indicating whether the hypergraph produces <s> and </s>
// if this is true, FinalTransitionFeatures will "add" <s> and </s>
// if false, FinalTransitionFeatures will score anything with the
// markers in the right place (i.e., the beginning and end of
// the sentence) with 0, and anything else with -100
int order_;
int state_size_;
int unscored_size_offset_;
int is_complete_offset_;
int unscored_words_offset_;
char* dummy_state_;
vector<const void*> dummy_ants_;
vector<lm::WordIndex> map_;
TRulePtr dummy_rule_;
};
template <class Model>
KLanguageModel<Model>::KLanguageModel(const string& param) {
pimpl_ = new KLanguageModelImpl<Model>(param);
fid_ = FD::Convert("LanguageModel");
SetStateSize(pimpl_->ReserveStateSize());
}
template <class Model>
Features KLanguageModel<Model>::features() const {
return single_feature(fid_);
}
template <class Model>
KLanguageModel<Model>::~KLanguageModel() {
delete pimpl_;
}
template <class Model>
void KLanguageModel<Model>::TraversalFeaturesImpl(const SentenceMetadata& /* smeta */,
const Hypergraph::Edge& edge,
const vector<const void*>& ant_states,
SparseVector<double>* features,
SparseVector<double>* estimated_features,
void* state) const {
double est = 0;
features->set_value(fid_, pimpl_->LookupWords(*edge.rule_, ant_states, &est, state));
estimated_features->set_value(fid_, est);
}
template <class Model>
void KLanguageModel<Model>::FinalTraversalFeatures(const void* ant_state,
SparseVector<double>* features) const {
features->set_value(fid_, pimpl_->FinalTraversalCost(ant_state));
}
// instantiate templates
template class KLanguageModel<lm::ngram::ProbingModel>;
template class KLanguageModel<lm::ngram::SortedModel>;
template class KLanguageModel<lm::ngram::TrieModel>;
<commit_msg>final version of SOS EOS handling, i think<commit_after>#include "ff_klm.h"
#include <cstring>
#include "hg.h"
#include "tdict.h"
#include "lm/enumerate_vocab.hh"
using namespace std;
static const unsigned char HAS_FULL_CONTEXT = 1;
static const unsigned char HAS_EOS_ON_RIGHT = 2;
static const unsigned char MASK = 7;
template <class Model>
string KLanguageModel<Model>::usage(bool /*param*/,bool /*verbose*/) {
return "KLanguageModel";
}
struct VMapper : public lm::ngram::EnumerateVocab {
VMapper(vector<lm::WordIndex>* out) : out_(out), kLM_UNKNOWN_TOKEN(0) { out_->clear(); }
void Add(lm::WordIndex index, const StringPiece &str) {
const WordID cdec_id = TD::Convert(str.as_string());
if (cdec_id >= out_->size())
out_->resize(cdec_id + 1, kLM_UNKNOWN_TOKEN);
(*out_)[cdec_id] = index;
}
vector<lm::WordIndex>* out_;
const lm::WordIndex kLM_UNKNOWN_TOKEN;
};
template <class Model>
class KLanguageModelImpl {
// returns the number of unscored words at the left edge of a span
inline int UnscoredSize(const void* state) const {
return *(static_cast<const char*>(state) + unscored_size_offset_);
}
inline void SetUnscoredSize(int size, void* state) const {
*(static_cast<char*>(state) + unscored_size_offset_) = size;
}
static inline const lm::ngram::State& RemnantLMState(const void* state) {
return *static_cast<const lm::ngram::State*>(state);
}
inline void SetRemnantLMState(const lm::ngram::State& lmstate, void* state) const {
// if we were clever, we could use the memory pointed to by state to do all
// the work, avoiding this copy
memcpy(state, &lmstate, ngram_->StateSize());
}
lm::WordIndex IthUnscoredWord(int i, const void* state) const {
const lm::WordIndex* const mem = reinterpret_cast<const lm::WordIndex*>(static_cast<const char*>(state) + unscored_words_offset_);
return mem[i];
}
void SetIthUnscoredWord(int i, lm::WordIndex index, void *state) const {
lm::WordIndex* mem = reinterpret_cast<lm::WordIndex*>(static_cast<char*>(state) + unscored_words_offset_);
mem[i] = index;
}
inline bool GetFlag(const void *state, unsigned char flag) const {
return (*(static_cast<const char*>(state) + is_complete_offset_) & flag);
}
inline void SetFlag(bool on, unsigned char flag, void *state) const {
if (on) {
*(static_cast<char*>(state) + is_complete_offset_) |= flag;
} else {
*(static_cast<char*>(state) + is_complete_offset_) &= (MASK ^ flag);
}
}
inline bool HasFullContext(const void *state) const {
return GetFlag(state, HAS_FULL_CONTEXT);
}
inline void SetHasFullContext(bool flag, void *state) const {
SetFlag(flag, HAS_FULL_CONTEXT, state);
}
public:
double LookupWords(const TRule& rule, const vector<const void*>& ant_states, double* pest_sum, void* remnant) {
double sum = 0.0;
double est_sum = 0.0;
int num_scored = 0;
int num_estimated = 0;
bool saw_eos = false;
bool has_some_history = false;
lm::ngram::State state = ngram_->NullContextState();
const vector<WordID>& e = rule.e();
bool context_complete = false;
for (int j = 0; j < e.size(); ++j) {
if (e[j] < 1) { // handle non-terminal substitution
const void* astate = (ant_states[-e[j]]);
int unscored_ant_len = UnscoredSize(astate);
for (int k = 0; k < unscored_ant_len; ++k) {
const lm::WordIndex cur_word = IthUnscoredWord(k, astate);
double p = 0;
if (cur_word == kSOS_) {
state = ngram_->BeginSentenceState();
if (has_some_history) { // this is immediately fully scored, and bad
p = -100;
context_complete = true;
} else { // this might be a real <s>
num_scored = max(0, order_ - 2);
}
} else {
const lm::ngram::State scopy(state);
p = ngram_->Score(scopy, cur_word, state);
if (saw_eos) { p = -100; }
saw_eos = (cur_word == kEOS_);
}
has_some_history = true;
++num_scored;
if (!context_complete) {
if (num_scored >= order_) context_complete = true;
}
if (context_complete) {
sum += p;
} else {
if (remnant)
SetIthUnscoredWord(num_estimated, cur_word, remnant);
++num_estimated;
est_sum += p;
}
}
saw_eos = GetFlag(astate, HAS_EOS_ON_RIGHT);
if (HasFullContext(astate)) { // this is equivalent to the "star" in Chiang 2007
state = RemnantLMState(astate);
context_complete = true;
}
} else { // handle terminal
const lm::WordIndex cur_word = MapWord(e[j]);
double p = 0;
if (cur_word == kSOS_) {
state = ngram_->BeginSentenceState();
if (has_some_history) { // this is immediately fully scored, and bad
p = -100;
context_complete = true;
} else { // this might be a real <s>
num_scored = max(0, order_ - 2);
}
} else {
const lm::ngram::State scopy(state);
p = ngram_->Score(scopy, cur_word, state);
if (saw_eos) { p = -100; }
saw_eos = (cur_word == kEOS_);
}
has_some_history = true;
++num_scored;
if (!context_complete) {
if (num_scored >= order_) context_complete = true;
}
if (context_complete) {
sum += p;
} else {
if (remnant)
SetIthUnscoredWord(num_estimated, cur_word, remnant);
++num_estimated;
est_sum += p;
}
}
}
if (pest_sum) *pest_sum = est_sum;
if (remnant) {
state.ZeroRemaining();
SetFlag(saw_eos, HAS_EOS_ON_RIGHT, remnant);
SetRemnantLMState(state, remnant);
SetUnscoredSize(num_estimated, remnant);
SetHasFullContext(context_complete || (num_scored >= order_), remnant);
}
return sum;
}
// this assumes no target words on final unary -> goal rule. is that ok?
// for <s> (n-1 left words) and (n-1 right words) </s>
double FinalTraversalCost(const void* state) {
if (add_sos_eos_) { // rules do not produce <s> </s>, so do it here
SetRemnantLMState(ngram_->BeginSentenceState(), dummy_state_);
SetHasFullContext(1, dummy_state_);
SetUnscoredSize(0, dummy_state_);
dummy_ants_[1] = state;
return LookupWords(*dummy_rule_, dummy_ants_, NULL, NULL);
} else { // rules DO produce <s> ... </s>
double p = 0;
if (!GetFlag(state, HAS_EOS_ON_RIGHT)) { p -= 100; }
if (UnscoredSize(state) > 0) { // are there unscored words
if (kSOS_ != IthUnscoredWord(0, state)) {
p -= 100 * UnscoredSize(state);
}
}
return p;
}
}
lm::WordIndex MapWord(WordID w) const {
if (w >= map_.size())
return 0;
else
return map_[w];
}
public:
KLanguageModelImpl(const std::string& param) {
add_sos_eos_ = true;
string fname = param;
if (param.find("-x ") == 0) {
add_sos_eos_ = false;
fname = param.substr(3);
}
lm::ngram::Config conf;
VMapper vm(&map_);
conf.enumerate_vocab = &vm;
ngram_ = new Model(fname.c_str(), conf);
order_ = ngram_->Order();
cerr << "Loaded " << order_ << "-gram KLM from " << fname << " (MapSize=" << map_.size() << ")\n";
state_size_ = ngram_->StateSize() + 2 + (order_ - 1) * sizeof(lm::WordIndex);
unscored_size_offset_ = ngram_->StateSize();
is_complete_offset_ = unscored_size_offset_ + 1;
unscored_words_offset_ = is_complete_offset_ + 1;
// special handling of beginning / ending sentence markers
dummy_state_ = new char[state_size_];
dummy_ants_.push_back(dummy_state_);
dummy_ants_.push_back(NULL);
dummy_rule_.reset(new TRule("[DUMMY] ||| [BOS] [DUMMY] ||| [1] [2] </s> ||| X=0"));
kSOS_ = MapWord(TD::Convert("<s>"));
assert(kSOS_ > 0);
kEOS_ = MapWord(TD::Convert("</s>"));
assert(kEOS_ > 0);
}
~KLanguageModelImpl() {
delete ngram_;
delete[] dummy_state_;
}
int ReserveStateSize() const { return state_size_; }
private:
lm::WordIndex kSOS_; // <s> - requires special handling.
lm::WordIndex kEOS_; // </s>
Model* ngram_;
bool add_sos_eos_; // flag indicating whether the hypergraph produces <s> and </s>
// if this is true, FinalTransitionFeatures will "add" <s> and </s>
// if false, FinalTransitionFeatures will score anything with the
// markers in the right place (i.e., the beginning and end of
// the sentence) with 0, and anything else with -100
int order_;
int state_size_;
int unscored_size_offset_;
int is_complete_offset_;
int unscored_words_offset_;
char* dummy_state_;
vector<const void*> dummy_ants_;
vector<lm::WordIndex> map_;
TRulePtr dummy_rule_;
};
template <class Model>
KLanguageModel<Model>::KLanguageModel(const string& param) {
pimpl_ = new KLanguageModelImpl<Model>(param);
fid_ = FD::Convert("LanguageModel");
SetStateSize(pimpl_->ReserveStateSize());
}
template <class Model>
Features KLanguageModel<Model>::features() const {
return single_feature(fid_);
}
template <class Model>
KLanguageModel<Model>::~KLanguageModel() {
delete pimpl_;
}
template <class Model>
void KLanguageModel<Model>::TraversalFeaturesImpl(const SentenceMetadata& /* smeta */,
const Hypergraph::Edge& edge,
const vector<const void*>& ant_states,
SparseVector<double>* features,
SparseVector<double>* estimated_features,
void* state) const {
double est = 0;
features->set_value(fid_, pimpl_->LookupWords(*edge.rule_, ant_states, &est, state));
estimated_features->set_value(fid_, est);
}
template <class Model>
void KLanguageModel<Model>::FinalTraversalFeatures(const void* ant_state,
SparseVector<double>* features) const {
features->set_value(fid_, pimpl_->FinalTraversalCost(ant_state));
}
// instantiate templates
template class KLanguageModel<lm::ngram::ProbingModel>;
template class KLanguageModel<lm::ngram::SortedModel>;
template class KLanguageModel<lm::ngram::TrieModel>;
<|endoftext|> |
<commit_before>#include "notepad.h"
#include "ui_notepad.h"
#include <QFileDialog>
#include <QFile>
#include <QMessageBox>
#include <QTextStream>
#include <iostream>
Notepad::Notepad(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Notepad)
{
// TODO, not sure where to organize instantiating methods
// Temporarily changing to a directory
QDir working_dir("/Users/pybae/Documents");
file_list = working_dir.entryList();
QStringListIterator it(file_list);
while (it.hasNext()) {
std::cout << it.next().toStdString() << std::endl;
}
ui->setupUi(this);
}
Notepad::~Notepad()
{
delete ui;
}
// Called when the "New" option is triggered by C-n or menu
void Notepad::on_actionNew_triggered()
{
// TODO
}
// Called when the "Open" option is triggered by C-o or menu
void Notepad::on_actionOpen_triggered()
{
// QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QString(),
// tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
// if (!fileName.isEmpty()) {
// QFile file(fileName);
// if (!file.open(QIODevice::ReadOnly)) {
// QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
// return;
// }
// QTextStream in(&file);
// ui->mainTextEdit->setText(in.readAll());
// file.close();
// }
}
// Called when the "Save" option is triggered by C-s or menu
void Notepad::on_actionSave_triggered()
{
// TODO
}
// Called when the "Save As" option is triggered by C-S (Ctrl shift s) or menu
void Notepad::on_actionSaveAs_triggered()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), QString(),
tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
if (!fileName.isEmpty()) {
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly)) {
// error message
return;
} else {
QTextStream stream(&file);
stream << ui->mainTextEdit->toPlainText();
stream.flush();
file.close();
}
}
}
// Called when the "Print" option is triggered by C-p or menu
void Notepad::on_actionPrint_triggered()
{
// TODO
}
// Called when the "Exit" option is triggered by C-q or menu
void Notepad::on_actionExit_triggered()
{
// TODO need to check if there are any unsaved buffers
qApp->quit();
}
// Triggered when the mainTextEdit region has its text changed
// TODO figure out how frequently this method is called
void Notepad::on_mainTextEdit_textChanged()
{
// Save the current buffer
Notepad::on_actionSave_triggered();
}
<commit_msg>Working dir is not being updated correctly<commit_after>#include "notepad.h"
#include "ui_notepad.h"
#include <QFileDialog>
#include <QFile>
#include <QMessageBox>
#include <QTextStream>
#include <iostream>
Notepad::Notepad(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Notepad)
{
// TODO, not sure where to organize instantiating methods
// Temporarily changing to a directory
QDir working_dir("/Users/pybae/Documents");
printf("What is the working dir: %s\n", working_dir.absolutePath().toStdString().c_str());
file_list = working_dir.entryList();
QStringListIterator it(file_list);
while (it.hasNext()) {
std::cout << it.next().toStdString() << std::endl;
}
ui->setupUi(this);
}
Notepad::~Notepad()
{
delete ui;
}
// Called when the "New" option is triggered by C-n or menu
void Notepad::on_actionNew_triggered()
{
// TODO
}
// Called when the "Open" option is triggered by C-o or menu
void Notepad::on_actionOpen_triggered()
{
printf("What is the working dir: %s\n", working_dir.absolutePath().toStdString().c_str());
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), working_dir.absolutePath(),
tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
if (!fileName.isEmpty()) {
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly)) {
QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
return;
}
QTextStream in(&file);
ui->mainTextEdit->setText(in.readAll());
file.close();
}
}
// Called when the "Save" option is triggered by C-s or menu
void Notepad::on_actionSave_triggered()
{
// TODO
}
// Called when the "Save As" option is triggered by C-S (Ctrl shift s) or menu
void Notepad::on_actionSaveAs_triggered()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), QString(),
tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
if (!fileName.isEmpty()) {
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly)) {
// error message
return;
} else {
QTextStream stream(&file);
stream << ui->mainTextEdit->toPlainText();
stream.flush();
file.close();
}
}
}
// Called when the "Print" option is triggered by C-p or menu
void Notepad::on_actionPrint_triggered()
{
// TODO
}
// Called when the "Exit" option is triggered by C-q or menu
void Notepad::on_actionExit_triggered()
{
// TODO need to check if there are any unsaved buffers
qApp->quit();
}
// Triggered when the mainTextEdit region has its text changed
// TODO figure out how frequently this method is called
void Notepad::on_mainTextEdit_textChanged()
{
// Save the current buffer
Notepad::on_actionSave_triggered();
}
<|endoftext|> |
<commit_before>
/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mutation_partition_serializer.hh"
#include "mutation_partition.hh"
#include "counters.hh"
#include "utils/UUID.hh"
#include "serializer.hh"
#include "idl/uuid.dist.hh"
#include "idl/keys.dist.hh"
#include "idl/mutation.dist.hh"
#include "serializer_impl.hh"
#include "serialization_visitors.hh"
#include "idl/uuid.dist.impl.hh"
#include "idl/keys.dist.impl.hh"
#include "idl/mutation.dist.impl.hh"
#include "range_tombstone_to_prefix_tombstone_converter.hh"
#include "service/storage_service.hh"
using namespace db;
namespace {
template<typename Writer>
auto write_live_cell(Writer&& writer, const atomic_cell& c)
{
return std::move(writer).write_created_at(c.timestamp())
.write_value(c.value())
.end_live_cell();
}
template<typename Writer>
auto write_counter_cell(Writer&& writer, const atomic_cell& c)
{
auto value = std::move(writer).write_created_at(c.timestamp());
return [&c, value = std::move(value)] () mutable {
if (c.is_counter_update()) {
auto delta = value_cast<int64_t>(long_type->deserialize_value(c.value()));
return std::move(value).start_value_counter_cell_update()
.write_delta(delta)
.end_counter_cell_update();
} else {
counter_cell_view ccv(c);
auto shards = std::move(value).start_value_counter_cell_full()
.start_shards();
for (auto csv : ccv.shards()) {
shards.add_shards(counter_shard(csv));
}
return std::move(shards).end_shards().end_counter_cell_full();
}
}().end_counter_cell();
}
template<typename Writer>
auto write_expiring_cell(Writer&& writer, const atomic_cell& c)
{
return std::move(writer).write_ttl(c.ttl())
.write_expiry(c.expiry())
.start_c()
.write_created_at(c.timestamp())
.write_value(c.value())
.end_c()
.end_expiring_cell();
}
template<typename Writer>
auto write_dead_cell(Writer&& writer, const atomic_cell& c)
{
return std::move(writer).start_tomb()
.write_timestamp(c.timestamp())
.write_deletion_time(c.deletion_time())
.end_tomb()
.end_dead_cell();
}
template<typename Writer>
auto write_collection_cell(Writer&& collection_writer, collection_mutation_view cmv, const column_definition& def)
{
auto&& ctype = static_pointer_cast<const collection_type_impl>(def.type);
auto m_view = ctype->deserialize_mutation_form(cmv);
auto cells_writer = std::move(collection_writer).write_tomb(m_view.tomb).start_elements();
for (auto&& c : m_view.cells) {
auto cell_writer = cells_writer.add().write_key(c.first);
if (!c.second.is_live()) {
write_dead_cell(std::move(cell_writer).start_value_dead_cell(), c.second).end_collection_element();
} else if (c.second.is_live_and_has_ttl()) {
write_expiring_cell(std::move(cell_writer).start_value_expiring_cell(), c.second).end_collection_element();
} else {
write_live_cell(std::move(cell_writer).start_value_live_cell(), c.second).end_collection_element();
}
}
return std::move(cells_writer).end_elements().end_collection_cell();
}
template<typename Writer>
auto write_row_cells(Writer&& writer, const row& r, const schema& s, column_kind kind)
{
auto column_writer = std::move(writer).start_columns();
r.for_each_cell([&] (column_id id, const atomic_cell_or_collection& cell) {
auto& def = s.column_at(kind, id);
auto cell_or_collection_writer = column_writer.add().write_id(id);
if (def.is_atomic()) {
auto&& c = cell.as_atomic_cell();
auto cell_writer = std::move(cell_or_collection_writer).start_c_variant();
if (!c.is_live()) {
write_dead_cell(std::move(cell_writer).start_variant_dead_cell(), c).end_variant().end_column();
} else if (def.is_counter()) {
write_counter_cell(std::move(cell_writer).start_variant_counter_cell(), c).end_variant().end_column();
} else if (c.is_live_and_has_ttl()) {
write_expiring_cell(std::move(cell_writer).start_variant_expiring_cell(), c).end_variant().end_column();
} else {
write_live_cell(std::move(cell_writer).start_variant_live_cell(), c).end_variant().end_column();
}
} else {
write_collection_cell(std::move(cell_or_collection_writer).start_c_collection_cell(), cell.as_collection_mutation(), def).end_column();
}
});
return std::move(column_writer).end_columns();
}
template<typename Writer>
auto write_row_marker(Writer&& writer, const row_marker& marker)
{
if (marker.is_missing()) {
return std::move(writer).start_marker_no_marker().end_no_marker();
} else if (!marker.is_live()) {
return std::move(writer).start_marker_dead_marker()
.start_tomb()
.write_timestamp(marker.timestamp())
.write_deletion_time(marker.deletion_time())
.end_tomb()
.end_dead_marker();
} else if (marker.is_expiring()) {
return std::move(writer).start_marker_expiring_marker()
.start_lm()
.write_created_at(marker.timestamp())
.end_lm()
.write_ttl(marker.ttl())
.write_expiry(marker.expiry())
.end_expiring_marker();
} else {
return std::move(writer).start_marker_live_marker()
.write_created_at(marker.timestamp())
.end_live_marker();
}
}
}
static void write_tombstones(const schema& s, auto& row_tombstones, const range_tombstone_list& rt_list)
{
if (service::get_local_storage_service().cluster_supports_range_tombstones()) {
for (auto&& rt : rt_list) {
row_tombstones.add().write_start(rt.start).write_tomb(rt.tomb).write_start_kind(rt.start_kind)
.write_end(rt.end).write_end_kind(rt.end_kind).end_range_tombstone();
}
} else {
range_tombstone_to_prefix_tombstone_converter m;
for (auto&& rt : rt_list) {
auto prefix = m.convert(s, rt);
if (prefix) {
row_tombstones.add().write_start(*prefix).write_tomb(rt.tomb).write_start_kind(bound_kind::incl_start)
.write_end(*prefix).write_end_kind(bound_kind::incl_end).end_range_tombstone();
}
}
m.verify_no_open_tombstones();
}
}
template<typename Writer>
void mutation_partition_serializer::write_serialized(Writer&& writer, const schema& s, const mutation_partition& mp)
{
auto srow_writer = std::move(writer).write_tomb(mp.partition_tombstone()).start_static_row();
auto row_tombstones = write_row_cells(std::move(srow_writer), mp.static_row(), s, column_kind::static_column).end_static_row().start_range_tombstones();
write_tombstones(s, row_tombstones, mp.row_tombstones());
auto clustering_rows = std::move(row_tombstones).end_range_tombstones().start_rows();
for (auto&& cr : mp.clustered_rows()) {
auto marker_writer = clustering_rows.add().write_key(cr.key());
auto deleted_at_writer = write_row_marker(std::move(marker_writer), cr.row().marker());
auto&& dt = cr.row().deleted_at();
auto row_writer = std::move(deleted_at_writer).start_deleted_at()
.write_timestamp(dt.timestamp)
.write_deletion_time(dt.deletion_time)
.end_deleted_at()
.start_cells();
write_row_cells(std::move(row_writer), cr.row().cells(), s, column_kind::regular_column).end_cells().end_deletable_row();
}
std::move(clustering_rows).end_rows().end_mutation_partition();
}
mutation_partition_serializer::mutation_partition_serializer(const schema& schema, const mutation_partition& p)
: _schema(schema), _p(p)
{ }
void
mutation_partition_serializer::write(bytes_ostream& out) const {
write(ser::writer_of_mutation_partition<bytes_ostream>(out));
}
void mutation_partition_serializer::write(ser::writer_of_mutation_partition<bytes_ostream>&& wr) const
{
write_serialized(std::move(wr), _schema, _p);
}
void serialize_mutation_fragments(const schema& s, tombstone partition_tombstone,
stdx::optional<static_row> sr, range_tombstone_list rts,
std::deque<clustering_row> crs, ser::writer_of_mutation_partition<bytes_ostream>&& wr)
{
auto srow_writer = std::move(wr).write_tomb(partition_tombstone).start_static_row();
auto row_tombstones = [&] {
if (sr) {
return write_row_cells(std::move(srow_writer), sr->cells(), s, column_kind::static_column).end_static_row().start_range_tombstones();
} else {
return std::move(srow_writer).start_columns().end_columns().end_static_row().start_range_tombstones();
}
}();
sr = { };
write_tombstones(s, row_tombstones, rts);
rts.clear();
auto clustering_rows = std::move(row_tombstones).end_range_tombstones().start_rows();
while (!crs.empty()) {
auto& cr = crs.front();
auto marker_writer = clustering_rows.add().write_key(cr.key());
auto deleted_at_writer = write_row_marker(std::move(marker_writer), cr.marker());
auto&& dt = cr.tomb();
auto row_writer = std::move(deleted_at_writer).start_deleted_at()
.write_timestamp(dt.timestamp)
.write_deletion_time(dt.deletion_time)
.end_deleted_at()
.start_cells();
write_row_cells(std::move(row_writer), cr.cells(), s, column_kind::regular_column).end_cells().end_deletable_row();
crs.pop_front();
}
std::move(clustering_rows).end_rows().end_mutation_partition();
}
<commit_msg>mutation_partition_serializer: avoid creating atomic_cell object<commit_after>
/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mutation_partition_serializer.hh"
#include "mutation_partition.hh"
#include "counters.hh"
#include "utils/UUID.hh"
#include "serializer.hh"
#include "idl/uuid.dist.hh"
#include "idl/keys.dist.hh"
#include "idl/mutation.dist.hh"
#include "serializer_impl.hh"
#include "serialization_visitors.hh"
#include "idl/uuid.dist.impl.hh"
#include "idl/keys.dist.impl.hh"
#include "idl/mutation.dist.impl.hh"
#include "range_tombstone_to_prefix_tombstone_converter.hh"
#include "service/storage_service.hh"
using namespace db;
namespace {
template<typename Writer>
auto write_live_cell(Writer&& writer, atomic_cell_view c)
{
return std::move(writer).write_created_at(c.timestamp())
.write_value(c.value())
.end_live_cell();
}
template<typename Writer>
auto write_counter_cell(Writer&& writer, atomic_cell_view c)
{
auto value = std::move(writer).write_created_at(c.timestamp());
return [&c, value = std::move(value)] () mutable {
if (c.is_counter_update()) {
auto delta = value_cast<int64_t>(long_type->deserialize_value(c.value()));
return std::move(value).start_value_counter_cell_update()
.write_delta(delta)
.end_counter_cell_update();
} else {
counter_cell_view ccv(c);
auto shards = std::move(value).start_value_counter_cell_full()
.start_shards();
for (auto csv : ccv.shards()) {
shards.add_shards(counter_shard(csv));
}
return std::move(shards).end_shards().end_counter_cell_full();
}
}().end_counter_cell();
}
template<typename Writer>
auto write_expiring_cell(Writer&& writer, atomic_cell_view c)
{
return std::move(writer).write_ttl(c.ttl())
.write_expiry(c.expiry())
.start_c()
.write_created_at(c.timestamp())
.write_value(c.value())
.end_c()
.end_expiring_cell();
}
template<typename Writer>
auto write_dead_cell(Writer&& writer, atomic_cell_view c)
{
return std::move(writer).start_tomb()
.write_timestamp(c.timestamp())
.write_deletion_time(c.deletion_time())
.end_tomb()
.end_dead_cell();
}
template<typename Writer>
auto write_collection_cell(Writer&& collection_writer, collection_mutation_view cmv, const column_definition& def)
{
auto&& ctype = static_pointer_cast<const collection_type_impl>(def.type);
auto m_view = ctype->deserialize_mutation_form(cmv);
auto cells_writer = std::move(collection_writer).write_tomb(m_view.tomb).start_elements();
for (auto&& c : m_view.cells) {
auto cell_writer = cells_writer.add().write_key(c.first);
if (!c.second.is_live()) {
write_dead_cell(std::move(cell_writer).start_value_dead_cell(), c.second).end_collection_element();
} else if (c.second.is_live_and_has_ttl()) {
write_expiring_cell(std::move(cell_writer).start_value_expiring_cell(), c.second).end_collection_element();
} else {
write_live_cell(std::move(cell_writer).start_value_live_cell(), c.second).end_collection_element();
}
}
return std::move(cells_writer).end_elements().end_collection_cell();
}
template<typename Writer>
auto write_row_cells(Writer&& writer, const row& r, const schema& s, column_kind kind)
{
auto column_writer = std::move(writer).start_columns();
r.for_each_cell([&] (column_id id, const atomic_cell_or_collection& cell) {
auto& def = s.column_at(kind, id);
auto cell_or_collection_writer = column_writer.add().write_id(id);
if (def.is_atomic()) {
auto&& c = cell.as_atomic_cell();
auto cell_writer = std::move(cell_or_collection_writer).start_c_variant();
if (!c.is_live()) {
write_dead_cell(std::move(cell_writer).start_variant_dead_cell(), c).end_variant().end_column();
} else if (def.is_counter()) {
write_counter_cell(std::move(cell_writer).start_variant_counter_cell(), c).end_variant().end_column();
} else if (c.is_live_and_has_ttl()) {
write_expiring_cell(std::move(cell_writer).start_variant_expiring_cell(), c).end_variant().end_column();
} else {
write_live_cell(std::move(cell_writer).start_variant_live_cell(), c).end_variant().end_column();
}
} else {
write_collection_cell(std::move(cell_or_collection_writer).start_c_collection_cell(), cell.as_collection_mutation(), def).end_column();
}
});
return std::move(column_writer).end_columns();
}
template<typename Writer>
auto write_row_marker(Writer&& writer, const row_marker& marker)
{
if (marker.is_missing()) {
return std::move(writer).start_marker_no_marker().end_no_marker();
} else if (!marker.is_live()) {
return std::move(writer).start_marker_dead_marker()
.start_tomb()
.write_timestamp(marker.timestamp())
.write_deletion_time(marker.deletion_time())
.end_tomb()
.end_dead_marker();
} else if (marker.is_expiring()) {
return std::move(writer).start_marker_expiring_marker()
.start_lm()
.write_created_at(marker.timestamp())
.end_lm()
.write_ttl(marker.ttl())
.write_expiry(marker.expiry())
.end_expiring_marker();
} else {
return std::move(writer).start_marker_live_marker()
.write_created_at(marker.timestamp())
.end_live_marker();
}
}
}
static void write_tombstones(const schema& s, auto& row_tombstones, const range_tombstone_list& rt_list)
{
if (service::get_local_storage_service().cluster_supports_range_tombstones()) {
for (auto&& rt : rt_list) {
row_tombstones.add().write_start(rt.start).write_tomb(rt.tomb).write_start_kind(rt.start_kind)
.write_end(rt.end).write_end_kind(rt.end_kind).end_range_tombstone();
}
} else {
range_tombstone_to_prefix_tombstone_converter m;
for (auto&& rt : rt_list) {
auto prefix = m.convert(s, rt);
if (prefix) {
row_tombstones.add().write_start(*prefix).write_tomb(rt.tomb).write_start_kind(bound_kind::incl_start)
.write_end(*prefix).write_end_kind(bound_kind::incl_end).end_range_tombstone();
}
}
m.verify_no_open_tombstones();
}
}
template<typename Writer>
void mutation_partition_serializer::write_serialized(Writer&& writer, const schema& s, const mutation_partition& mp)
{
auto srow_writer = std::move(writer).write_tomb(mp.partition_tombstone()).start_static_row();
auto row_tombstones = write_row_cells(std::move(srow_writer), mp.static_row(), s, column_kind::static_column).end_static_row().start_range_tombstones();
write_tombstones(s, row_tombstones, mp.row_tombstones());
auto clustering_rows = std::move(row_tombstones).end_range_tombstones().start_rows();
for (auto&& cr : mp.clustered_rows()) {
auto marker_writer = clustering_rows.add().write_key(cr.key());
auto deleted_at_writer = write_row_marker(std::move(marker_writer), cr.row().marker());
auto&& dt = cr.row().deleted_at();
auto row_writer = std::move(deleted_at_writer).start_deleted_at()
.write_timestamp(dt.timestamp)
.write_deletion_time(dt.deletion_time)
.end_deleted_at()
.start_cells();
write_row_cells(std::move(row_writer), cr.row().cells(), s, column_kind::regular_column).end_cells().end_deletable_row();
}
std::move(clustering_rows).end_rows().end_mutation_partition();
}
mutation_partition_serializer::mutation_partition_serializer(const schema& schema, const mutation_partition& p)
: _schema(schema), _p(p)
{ }
void
mutation_partition_serializer::write(bytes_ostream& out) const {
write(ser::writer_of_mutation_partition<bytes_ostream>(out));
}
void mutation_partition_serializer::write(ser::writer_of_mutation_partition<bytes_ostream>&& wr) const
{
write_serialized(std::move(wr), _schema, _p);
}
void serialize_mutation_fragments(const schema& s, tombstone partition_tombstone,
stdx::optional<static_row> sr, range_tombstone_list rts,
std::deque<clustering_row> crs, ser::writer_of_mutation_partition<bytes_ostream>&& wr)
{
auto srow_writer = std::move(wr).write_tomb(partition_tombstone).start_static_row();
auto row_tombstones = [&] {
if (sr) {
return write_row_cells(std::move(srow_writer), sr->cells(), s, column_kind::static_column).end_static_row().start_range_tombstones();
} else {
return std::move(srow_writer).start_columns().end_columns().end_static_row().start_range_tombstones();
}
}();
sr = { };
write_tombstones(s, row_tombstones, rts);
rts.clear();
auto clustering_rows = std::move(row_tombstones).end_range_tombstones().start_rows();
while (!crs.empty()) {
auto& cr = crs.front();
auto marker_writer = clustering_rows.add().write_key(cr.key());
auto deleted_at_writer = write_row_marker(std::move(marker_writer), cr.marker());
auto&& dt = cr.tomb();
auto row_writer = std::move(deleted_at_writer).start_deleted_at()
.write_timestamp(dt.timestamp)
.write_deletion_time(dt.deletion_time)
.end_deleted_at()
.start_cells();
write_row_cells(std::move(row_writer), cr.cells(), s, column_kind::regular_column).end_cells().end_deletable_row();
crs.pop_front();
}
std::move(clustering_rows).end_rows().end_mutation_partition();
}
<|endoftext|> |
<commit_before>/*
* W.J. van der Laan 2011-2012
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "qtipcserver.h"
#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#include "init.h"
#include "ui_interface.h"
#if defined(QT_STATICPLUGIN)
#include <QtPlugin>
#if QT_VERSION < 0x050000
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#else
Q_IMPORT_PLUGIN(AccessibleFactory)
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
#endif
#endif
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;
static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
}
static bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignVCenter|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
static void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. VERGE can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
// Do this early as we don't want to bother initializing if we are just calling IPC
ipcScanRelay(argc, argv);
#if QT_VERSION < 0x050000
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
#endif
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
QMessageBox::critical(0, "VERGE",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName(QAPP_ORG_NAME);
app.setOrganizationDomain(QAPP_ORG_DOMAIN);
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName(QAPP_APP_NAME_TESTNET);
else
app.setApplicationName(QAPP_APP_NAME_DEFAULT);
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.QueueShutdown.connect(QueueShutdown);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
QSplashScreen splash(QPixmap(GetBoolArg("-testnet") ? ":/images/splash_testnet" : ":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
// Regenerate startup link, to fix links to old versions
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
BitcoinGUI window;
guiref = &window;
if(AppInit2())
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Place this here as guiref has to be defined if we don't want to lose URIs
ipcInit(argc, argv);
app.exec();
window.hide();
window.setClientModel(0);
window.setWalletModel(0);
guiref = 0;
}
// Shutdown the core and its threads, but don't exit Bitcoin-Qt here
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
<commit_msg>updated for upnp<commit_after>/*
* W.J. van der Laan 2011-2012
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "qtipcserver.h"
#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#include "init.h"
#include "ui_interface.h"
#if defined(QT_STATICPLUGIN)
#include <QtPlugin>
#if QT_VERSION < 0x050000
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#else
Q_IMPORT_PLUGIN(AccessibleFactory)
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
#endif
#endif
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;
static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
}
static bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignVCenter|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
static void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. VERGE can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
// Do this early as we don't want to bother initializing if we are just calling IPC
ipcScanRelay(argc, argv);
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
QMessageBox::critical(0, "VERGE",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName(QAPP_ORG_NAME);
app.setOrganizationDomain(QAPP_ORG_DOMAIN);
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName(QAPP_APP_NAME_TESTNET);
else
app.setApplicationName(QAPP_APP_NAME_DEFAULT);
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.QueueShutdown.connect(QueueShutdown);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
QSplashScreen splash(QPixmap(GetBoolArg("-testnet") ? ":/images/splash_testnet" : ":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
// Regenerate startup link, to fix links to old versions
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
BitcoinGUI window;
guiref = &window;
if(AppInit2())
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Place this here as guiref has to be defined if we don't want to lose URIs
ipcInit(argc, argv);
app.exec();
window.hide();
window.setClientModel(0);
window.setWalletModel(0);
guiref = 0;
}
// Shutdown the core and its threads, but don't exit Bitcoin-Qt here
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
<|endoftext|> |
<commit_before>#include <cmath>
#include <Eigen/Dense>
#include <gtest/gtest.h>
class ReferenceFilter
{
public:
ReferenceFilter( unsigned inputCount )
: mW( Eigen::VectorXf::Random( inputCount ) )
{}
float operator()( Eigen::VectorXf inputs )
{
return mW.dot( inputs );
}
Eigen::VectorXf mW;
};
class Model
{
const unsigned kInputCount = 100;
const float kMaxAmplitude = 1.0f;
const float kMaxFrequency = 10.0f;
const float kStep = 0.1f * 1.0f / kMaxFrequency;
public:
Model()
: mAmplitude( kMaxAmplitude / 2.0f *
( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f ) )
, mOmega( kMaxFrequency / 2.0f *
( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f ) )
, mInput( kInputCount )
, mW( Eigen::VectorXf::Random( kInputCount ) )
, mOutput( 0.0f )
, mReferenceFilter( kInputCount )
, mReferenceOutput( 0.0f )
, mTime( 0.0f )
{}
void Update()
{
mTime += kStep;
mInput = mAmplitude.array() * ( mOmega.array() * mTime ).unaryExpr(
std::ptr_fun< float, float >( std::sin ) );
mOutput = mW.dot( mInput );
mReferenceOutput = mReferenceFilter( mInput );
}
Eigen::VectorXf mAmplitude;
Eigen::VectorXf mOmega;
Eigen::VectorXf mInput;
Eigen::VectorXf mW;
float mOutput;
ReferenceFilter mReferenceFilter;
float mReferenceOutput;
float mTime;
};
TEST( AdaptiveFilter, NLMS )
{
const unsigned kStepCount = 10000;
const float kTrainStep = 0.1f;
Model model;
for ( int i = 0; i < kStepCount; ++ i )
{
model.Update();
float error = model.mReferenceOutput - model.mOutput;
model.mW += ( kTrainStep * error * model.mInput.transpose() /
model.mInput.squaredNorm() );
}
}
TEST( AdaptiveFilter, RLS )
{
}
<commit_msg>esn : tests : AdaptiveFilter : RLS : initial implementation of the test<commit_after>#include <cmath>
#include <Eigen/Dense>
#include <gtest/gtest.h>
class ReferenceFilter
{
public:
ReferenceFilter( unsigned inputCount )
: mW( Eigen::VectorXf::Random( inputCount ) )
{}
float operator()( Eigen::VectorXf inputs )
{
return mW.dot( inputs );
}
Eigen::VectorXf mW;
};
class Model
{
const unsigned kInputCount = 100;
const float kMaxAmplitude = 1.0f;
const float kMaxFrequency = 10.0f;
const float kStep = 0.1f * 1.0f / kMaxFrequency;
public:
Model()
: mAmplitude( kMaxAmplitude / 2.0f *
( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f ) )
, mOmega( kMaxFrequency / 2.0f *
( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f ) )
, mInput( kInputCount )
, mW( Eigen::VectorXf::Random( kInputCount ) )
, mOutput( 0.0f )
, mReferenceFilter( kInputCount )
, mReferenceOutput( 0.0f )
, mTime( 0.0f )
{}
void Update()
{
mTime += kStep;
mInput = mAmplitude.array() * ( mOmega.array() * mTime ).unaryExpr(
std::ptr_fun< float, float >( std::sin ) );
mOutput = mW.dot( mInput );
mReferenceOutput = mReferenceFilter( mInput );
}
Eigen::VectorXf mAmplitude;
Eigen::VectorXf mOmega;
Eigen::VectorXf mInput;
Eigen::VectorXf mW;
float mOutput;
ReferenceFilter mReferenceFilter;
float mReferenceOutput;
float mTime;
};
TEST( AdaptiveFilter, NLMS )
{
const unsigned kStepCount = 10000;
const float kTrainStep = 0.1f;
Model model;
for ( int i = 0; i < kStepCount; ++ i )
{
model.Update();
float error = model.mReferenceOutput - model.mOutput;
model.mW += ( kTrainStep * error * model.mInput.transpose() /
model.mInput.squaredNorm() );
}
}
TEST( AdaptiveFilter, RLS )
{
const unsigned kStepCount = 1000;
const float kTrainStep = 0.1f;
const float kDelta = 1000.0f;
const float kGamma = 0.999f;
Model model;
Eigen::MatrixXf P = Eigen::MatrixXf::Identity(
model.mInput.size(), model.mInput.size() ) * kDelta;
for ( int i = 0; i < kStepCount; ++ i )
{
model.Update();
float error = model.mReferenceOutput - model.mOutput;
auto & u = model.mInput;
auto uT_P = u.transpose() * P;
Eigen::VectorXf K = P * u / ( kGamma + uT_P.dot( u ) );
P = 1 / kGamma * ( P - K * uT_P );
model.mW += error * K;
}
}
<|endoftext|> |
<commit_before>#include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include <QString>
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#include <QUrl>
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
if(uri.scheme() != QString("bitcoin"))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
QList<QPair<QString, QString> > items = uri.queryItems();
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert bitcoin:// to bitcoin:
//
// Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
// which will lowercase it (and thus invalidate the address).
if(uri.startsWith("bitcoin://"))
{
uri.replace(0, 10, "bitcoin:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
QString escaped = Qt::escape(str);
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item
QApplication::clipboard()->setText(selection.at(0).data(role).toString());
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
if(!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width()/2, w->height()/2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
#ifdef WIN32
if (boost::filesystem::exists(pathDebug))
/* Open debug.log with the associated application */
ShellExecuteA((HWND)0, (LPCSTR)"open", (LPCSTR)pathDebug.string().c_str(), NULL, NULL, SW_SHOWNORMAL);
#endif
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(!Qt::mightBeRichText(tooltip) && tooltip.size() > size_threshold)
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
} // namespace GUIUtil
<commit_msg>Add missing #include for GetDataDir<commit_after>#include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include <QString>
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#include <QUrl>
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
if(uri.scheme() != QString("bitcoin"))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
QList<QPair<QString, QString> > items = uri.queryItems();
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert bitcoin:// to bitcoin:
//
// Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
// which will lowercase it (and thus invalidate the address).
if(uri.startsWith("bitcoin://"))
{
uri.replace(0, 10, "bitcoin:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
QString escaped = Qt::escape(str);
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item
QApplication::clipboard()->setText(selection.at(0).data(role).toString());
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
if(!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width()/2, w->height()/2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
#ifdef WIN32
if (boost::filesystem::exists(pathDebug))
/* Open debug.log with the associated application */
ShellExecuteA((HWND)0, (LPCSTR)"open", (LPCSTR)pathDebug.string().c_str(), NULL, NULL, SW_SHOWNORMAL);
#endif
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(!Qt::mightBeRichText(tooltip) && tooltip.size() > size_threshold)
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
} // namespace GUIUtil
<|endoftext|> |
<commit_before>#include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include <QString>
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#include <QUrl>
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
if(uri.scheme() != QString("bitcoin"))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
QList<QPair<QString, QString> > items = uri.queryItems();
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert bitcoin:// to bitcoin:
//
// Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
// which will lowercase it (and thus invalidate the address).
if(uri.startsWith("bitcoin://"))
{
uri.replace(0, 10, "bitcoin:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
QString escaped = Qt::escape(str);
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item
QApplication::clipboard()->setText(selection.at(0).data(role).toString());
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
if(!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width()/2, w->height()/2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
#ifdef WIN32
if (boost::filesystem::exists(pathDebug))
/* Open debug.log with the associated application */
ShellExecuteA((HWND)0, (LPCSTR)"open", (LPCSTR)pathDebug.string().c_str(), NULL, NULL, SW_SHOWNORMAL);
#endif
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(!Qt::mightBeRichText(tooltip) && tooltip.size() > size_threshold)
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
} // namespace GUIUtil
<commit_msg>Add missing #include for GetDataDir<commit_after>#include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include <QString>
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#include <QUrl>
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
if(uri.scheme() != QString("bitcoin"))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
QList<QPair<QString, QString> > items = uri.queryItems();
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert bitcoin:// to bitcoin:
//
// Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
// which will lowercase it (and thus invalidate the address).
if(uri.startsWith("bitcoin://"))
{
uri.replace(0, 10, "bitcoin:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
QString escaped = Qt::escape(str);
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item
QApplication::clipboard()->setText(selection.at(0).data(role).toString());
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
if(!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width()/2, w->height()/2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
#ifdef WIN32
if (boost::filesystem::exists(pathDebug))
/* Open debug.log with the associated application */
ShellExecuteA((HWND)0, (LPCSTR)"open", (LPCSTR)pathDebug.string().c_str(), NULL, NULL, SW_SHOWNORMAL);
#endif
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(!Qt::mightBeRichText(tooltip) && tooltip.size() > size_threshold)
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
} // namespace GUIUtil
<|endoftext|> |
<commit_before>
#include <iostream>
#include <list>
class A
{
public:
void fun()
{
std::cout << "A::fun()" << std::endl;
}
};
class B
{
public:
int fun2(double d, int i)
{
std::cout << "B::fun1(" << d << ", " << i << ")" << std::endl;
return i + 1;
}
};
class ICaller
{
public:
virtual void call() = 0;
};
typedef ICaller* LPICaller;
template <class T, class F>
class CallerAdapterBase
{
public:
CallerAdapterBase(T* pObject, F pFunction)
: m_pObject (pObject )
, m_pFunction(pFunction)
{}
protected:
T* m_pObject;
F m_pFunction;
};
template <class T, class F>
class CallerAdapter0: public CallerAdapterBase<T, F>, public ICaller
{
public:
CallerAdapter0(T* pObject, F pFunction)
: CallerAdapterBase(pObject, pFunction)
{}
private:
void call()
{
(m_pObject->*m_pFunction)();
}
};
template <class T, class F, class P1, class P2>
class CallerAdapter2: public CallerAdapterBase<T, F>, public ICaller
{
public:
CallerAdapter2(T* pObject, F pFunction, const P1& p1, const P2& p2)
: CallerAdapterBase(pObject, pFunction)
, m_p1(p1)
, m_p2(p2)
{}
private:
const P1& m_p1;
const P2& m_p2;
void call()
{
(m_pObject->*m_pFunction)(m_p1, m_p2);
}
};
class Sender
{
public:
template <class T, class F>
void dispatch(T* pObject, F pFunction)
{
CallerAdapter0<T, F>* pAdapter = new CallerAdapter0<T, F>(pObject, pFunction);
m_callerList.push_back(pAdapter);
}
template <class T, class F, class P1, class P2>
void dispatch(T* pObject, F pFunction, const P1& p1, const P2& p2)
{
CallerAdapter2<T, F, P1, P2>* pAdapter = new CallerAdapter2<T, F, P1, P2>(pObject, pFunction, p1, p2);
m_callerList.push_back(pAdapter);
}
void call()
{
CallerList::const_iterator it = m_callerList.begin();
while (it != m_callerList.end())
{
(*it)->call();
delete *it;
++it;
}
}
private:
typedef std::list<LPICaller> CallerList;
CallerList m_callerList;
};
void main()
{
A a;
B b;
Sender sender;
sender.dispatch(&a, &A::fun);
sender.dispatch(&b, &B::fun2, 10, 20);
sender.call();
int i = 1;
}
<commit_msg> - добавлены апартаменты<commit_after>
#include <iostream>
#include <list>
class ICaller
{
public:
virtual void call() = 0;
};
typedef ICaller* LPICaller;
class Apartment
{
public:
Apartment()
{}
void call(LPICaller pCall)
{
m_callerList.push_back(pCall);
}
void internal_call()
{
CallerList::const_iterator it = m_callerList.begin();
while (it != m_callerList.end())
{
(*it)->call();
delete *it;
++it;
}
}
private:
typedef std::list<LPICaller> CallerList;
CallerList m_callerList;
};
template <class T>
class ApartmentPointer
{
public:
ApartmentPointer(T* pObject)
: m_pObject(pObject)
{
m_pApartment = m_pObject->getApartment();
}
template <class F>
void dispatch(F pFunction)
{
CallerAdapter0<T, F>* pAdapter = new CallerAdapter0<T, F>(m_pObject, pFunction);
m_pApartment->call(pAdapter);
}
template <class F, class P1, class P2>
void dispatch(F pFunction, const P1& p1, const P2& p2)
{
CallerAdapter2<T, F, P1, P2>* pAdapter = new CallerAdapter2<T, F, P1, P2>(m_pObject, pFunction, p1, p2);
m_pApartment->call(pAdapter);
}
private:
T* m_pObject;
Apartment* m_pApartment;
};
class ApartmentObject
{
public:
ApartmentObject()
: m_pApartment(NULL)
{}
void setApartment(Apartment* pApartment)
{
m_pApartment = pApartment;
}
Apartment* getApartment() const
{
return m_pApartment;
}
private:
Apartment* m_pApartment;
};
template <class T, class F>
class CallerAdapterBase
{
public:
CallerAdapterBase(T* pObject, F pFunction)
: m_pObject (pObject )
, m_pFunction(pFunction)
{}
protected:
T* m_pObject;
F m_pFunction;
};
template <class T, class F>
class CallerAdapter0: public CallerAdapterBase<T, F>, public ICaller
{
public:
CallerAdapter0(T* pObject, F pFunction)
: CallerAdapterBase(pObject, pFunction)
{}
private:
void call()
{
(m_pObject->*m_pFunction)();
}
};
template <class T, class F, class P1, class P2>
class CallerAdapter2: public CallerAdapterBase<T, F>, public ICaller
{
public:
CallerAdapter2(T* pObject, F pFunction, const P1& p1, const P2& p2)
: CallerAdapterBase(pObject, pFunction)
, m_p1(p1)
, m_p2(p2)
{}
private:
const P1& m_p1;
const P2& m_p2;
void call()
{
(m_pObject->*m_pFunction)(m_p1, m_p2);
}
};
class A: public ApartmentObject
{
public:
void fun()
{
std::cout << "A::fun()" << std::endl;
}
};
class B: public ApartmentObject
{
public:
int fun2(double d, int i)
{
std::cout << "B::fun1(" << d << ", " << i << ")" << std::endl;
return i + 1;
}
};
void main()
{
Apartment apartment;
A a;
B b;
a.setApartment(&apartment);
b.setApartment(&apartment);
ApartmentPointer<A> pA(&a);
ApartmentPointer<B> pB(&b);
pA.dispatch(&A::fun);
pB.dispatch(&B::fun2, 10, 20);
apartment.internal_call();
int i = 1;
}
<|endoftext|> |
<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
#include <gecode/driver.hh>
#include <gecode/int.hh>
#include <gecode/minimodel.hh>
using namespace Gecode;
//
// g++ -g simple_dependency.cpp -lgecodesupport -lgecodekernel -lgecodeint -lgecodesearch -lgecodedriver -lpthread -ldl -lstdc++ -o simple_dependency
//
class SimpleDependency : public MinimizeScript {
protected:
static const int PKG_COUNT = 11;
IntVarArray package_versions;
IntArgs disabled_package_weights;
BoolVarArray disabled_package_variables;
IntVar total_disabled;
public:
/// Actual model
SimpleDependency(const Options& opt) :
package_versions(*this, PKG_COUNT, -1, 10),
disabled_package_variables(*this, PKG_COUNT, 0, 1),
total_disabled(*this, 0, 10*PKG_COUNT)
{
Problem2();
branch(*this, package_versions, INT_VAR_SIZE_MIN, INT_VAL_MAX);
branch(*this, disabled_package_variables, INT_VAR_SIZE_MIN, INT_VAL_MIN);
branch(*this, total_disabled, INT_VAL_MIN);
}
void Problem1() {
std::cout << "Setting up " << __FUNCTION__ << std::endl;
// Add version constraints for pkg 0
dom(*this, package_versions[0], -1, 0);
dom(*this, package_versions[1], -1, 0);
dom(*this, package_versions[2], -1, 0);
dom(*this, package_versions[3], -1, 1);
dom(*this, package_versions[4], -1, 0);
dom(*this, package_versions[5], -1, 0);
dom(*this, package_versions[6], -1, 2);
dom(*this, package_versions[7], -1, 0);
dom(*this, package_versions[8], -1, 0);
dom(*this, package_versions[9], -1, -1);
dom(*this, package_versions[10], 0, 0);
AddVersionConstraint(0, 0, 1, 0, 1);
AddVersionConstraint(2, 0, 1, 0, 0);
AddVersionConstraint(1, 0, 3, 0, 1);
AddVersionConstraint(1, 0, 4, 0, 0);
AddVersionConstraint(1, 1, 3, 1, 1);
AddVersionConstraint(1, 1, 5, 0, 0);
AddVersionConstraint(7, 0, 3, -2, -2);
AddVersionConstraint(8, 0, 9, -2, -2);
AddVersionConstraint(10, 0, 7, 0, 0);
IntArgs package_weights(PKG_COUNT, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 );
linear(*this, package_weights, disabled_package_variables, IRT_EQ, total_disabled);
std::cout << "Package versions: " << package_versions << std::endl;
std::cout << "Disabled package variables: " << disabled_package_variables << std::endl;
std::cout << "Package weights " << package_weights << std::endl;
std::cout << "Total disabled: " << total_disabled << std::endl;
}
void Problem2() {
std::cout << "Setting up " << __FUNCTION__ << std::endl;
// Add version constraints for pkg 0
dom(*this, package_versions[0], -1, 0);
dom(*this, package_versions[1], -1, 0);
dom(*this, package_versions[2], -1, 0);
dom(*this, package_versions[3], -1, 1);
dom(*this, package_versions[4], -1, 0);
dom(*this, package_versions[5], -1, 0);
dom(*this, package_versions[6], -1, 2);
dom(*this, package_versions[7], -1, 0);
dom(*this, package_versions[8], -1, 0);
dom(*this, package_versions[9], -1, -1);
dom(*this, package_versions[10], 0, 0);
AddVersionConstraint(0, 0, 1, 0, 1);
AddVersionConstraint(2, 0, 1, 0, 0);
AddVersionConstraint(1, 0, 3, 0, 1);
AddVersionConstraint(1, 0, 4, 0, 0);
AddVersionConstraint(1, 1, 3, 1, 1);
AddVersionConstraint(1, 1, 5, 0, 0);
AddVersionConstraint(7, 0, 3, -2, -2);
AddVersionConstraint(8, 0, 9, -2, -2);
AddVersionConstraint(10, 0, 7, 0, 0);
IntArgs package_weights(PKG_COUNT, 10, 10, 10, 10, 10, 10, 10, 5, 10, 10 );
linear(*this, package_weights, disabled_package_variables, IRT_EQ, total_disabled);
std::cout << "Package versions: " << package_versions << std::endl;
std::cout << "Disabled package variables: " << disabled_package_variables << std::endl;
std::cout << "Package weights " << package_weights << std::endl;
std::cout << "Total disabled: " << total_disabled << std::endl;
}
bool AddVersionConstraint(int packageId, int version,
int dependentPackageId, int minDependentVersion, int maxDependentVersion)
{
BoolVar version_match(*this, 0, 1);
BoolVar depend_match(*this, 0, 1);
BoolVar predicated_depend_match(*this, 0, 1);
std::cout << "Add VC for " << packageId << " @ " << version << " depPkg " << dependentPackageId;
std::cout << " [ " << minDependentVersion << ", " << maxDependentVersion << " ]" << std::endl;
std::cout.flush();
//version_flags << version_match;
// Constrain pred to reify package @ version
rel(*this, package_versions[packageId], IRT_EQ, version, version_match);
// Add the predicated version constraints imposed on dependent package
dom(*this, package_versions[dependentPackageId], minDependentVersion, maxDependentVersion, depend_match);
// disabled_package_variables[dependentPackageId] OR depend_match <=> version_match
rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, predicated_depend_match);
rel(*this, version_match, BOT_IMP, predicated_depend_match, 1);
}
/// Print solution
virtual void
print(std::ostream& os) const {
os << "\t" << package_versions << std::endl;
os << "\t" << disabled_package_variables << std::endl;
os << "\t" << total_disabled << std::endl;
}
virtual IntVar cost() const {
return total_disabled;
}
/// Constructor for cloning \a s
SimpleDependency(bool share, SimpleDependency& s) :
MinimizeScript(share,s),
package_versions(s.package_versions),
disabled_package_variables(s.disabled_package_variables),
total_disabled(s.total_disabled)
{
package_versions.update(*this, share, s.package_versions);
disabled_package_variables.update(*this, share, s.disabled_package_variables);
total_disabled.update(*this, share, s.total_disabled);
}
/// Copy during cloning
virtual Space*
copy(bool share) {
return new SimpleDependency(share,*this);
}
};
/** \brief Main-function
* \relates Money
*/
int
main(int argc, char* argv[]) {
Options opt("Solve dependency");
opt.solutions(0);
opt.iterations(20000);
opt.parse(argc,argv);
for (int i = 0; i < 1; i++)
MinimizeScript::run<SimpleDependency,Restart,Options>(opt);
return 0;
}
// STATISTICS: example-any
<commit_msg>Fix code to actually map to the problem of interest.<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
#include <gecode/driver.hh>
#include <gecode/int.hh>
#include <gecode/minimodel.hh>
using namespace Gecode;
//
// g++ -g simple_dependency.cpp -lgecodesupport -lgecodekernel -lgecodeint -lgecodesearch -lgecodedriver -lpthread -ldl -lstdc++ -o simple_dependency
//
class SimpleDependency : public MinimizeScript {
protected:
static const int PKG_COUNT = 11;
IntVarArray package_versions;
IntArgs disabled_package_weights;
BoolVarArray disabled_package_variables;
IntVar total_disabled;
public:
/// Actual model
SimpleDependency(const Options& opt) :
package_versions(*this, PKG_COUNT, -1, 10),
disabled_package_variables(*this, PKG_COUNT, 0, 1),
total_disabled(*this, 0, 10*PKG_COUNT)
{
Problem2();
branch(*this, disabled_package_variables, INT_VAR_SIZE_MIN, INT_VAL_MIN);
branch(*this, package_versions, INT_VAR_SIZE_MIN, INT_VAL_MAX);
branch(*this, total_disabled, INT_VAL_MIN);
}
void SetupDomain1() {
dom(*this, package_versions[0], -1, 0);
dom(*this, package_versions[1], -1, 1);
dom(*this, package_versions[2], -1, 0);
dom(*this, package_versions[3], -1, 1);
dom(*this, package_versions[4], -1, 0);
dom(*this, package_versions[5], -1, 0);
dom(*this, package_versions[6], -1, 2);
dom(*this, package_versions[7], -1, 0);
dom(*this, package_versions[8], -1, 0);
dom(*this, package_versions[9], -1, -1);
dom(*this, package_versions[10], 0, 0);
}
void SetupDependencies1() {
AddVersionConstraint(0, 0, 1, 0, 1);
AddVersionConstraint(2, 0, 1, 0, 0);
AddVersionConstraint(1, 0, 3, 0, 1);
AddVersionConstraint(1, 0, 4, 0, 0);
AddVersionConstraint(1, 1, 3, 1, 1);
AddVersionConstraint(1, 1, 5, 0, 0);
AddVersionConstraint(7, 0, 3, -2, -2);
AddVersionConstraint(8, 0, 9, -2, -2);
AddVersionConstraint(10, 0, 7, 0, 0);
}
void Problem1() {
std::cout << "Setting up " << __FUNCTION__ << std::endl;
SetupDomain1();
SetupDependencies1();
IntArgs package_weights(PKG_COUNT, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10);
linear(*this, package_weights, disabled_package_variables, IRT_EQ, total_disabled);
std::cout << "Package versions: " << package_versions << std::endl;
std::cout << "Disabled package variables: " << disabled_package_variables << std::endl;
std::cout << "Package weights " << package_weights << std::endl;
std::cout << "Total disabled: " << total_disabled << std::endl;
}
void Problem2() {
std::cout << "Setting up " << __FUNCTION__ << std::endl;
SetupDomain1();
SetupDependencies1();
// IntArgs package_weights(PKG_COUNT, 10, 10, 10, 10, 10, 10, 10, 5, 10, 10 );
// 0 1 2 3 4 5 6 7 8 9 10
IntArgs package_weights(PKG_COUNT, 10, 10, 10, 01, 10, 10, 10, 10, 10, 01, 10 );
linear(*this, package_weights, disabled_package_variables, IRT_EQ, total_disabled);
std::cout << "Package versions: " << package_versions << std::endl;
std::cout << "Disabled package variables: " << disabled_package_variables << std::endl;
std::cout << "Package weights " << package_weights << std::endl;
std::cout << "Total disabled: " << total_disabled << std::endl;
}
bool AddVersionConstraint(int packageId, int version,
int dependentPackageId, int minDependentVersion, int maxDependentVersion)
{
BoolVar version_match(*this, 0, 1);
BoolVar depend_match(*this, 0, 1);
BoolVar predicated_depend_match(*this, 0, 1);
std::cout << "Add VC for " << packageId << " @ " << version << " depPkg " << dependentPackageId;
std::cout << " [ " << minDependentVersion << ", " << maxDependentVersion << " ]" << std::endl;
std::cout.flush();
//version_flags << version_match;
// Constrain pred to reify package @ version
rel(*this, package_versions[packageId], IRT_EQ, version, version_match);
// Add the predicated version constraints imposed on dependent package
dom(*this, package_versions[dependentPackageId], minDependentVersion, maxDependentVersion, depend_match);
// disabled_package_variables[dependentPackageId] OR depend_match <=> version_match
rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, predicated_depend_match);
rel(*this, version_match, BOT_IMP, predicated_depend_match, 1);
}
/// Print solution
virtual void
print(std::ostream& os) const {
os << "\t" << package_versions << std::endl;
os << "\t" << disabled_package_variables << std::endl;
os << "\t" << total_disabled << std::endl;
}
virtual IntVar cost() const {
return total_disabled;
}
/// Constructor for cloning \a s
SimpleDependency(bool share, SimpleDependency& s) :
MinimizeScript(share,s),
package_versions(s.package_versions),
disabled_package_variables(s.disabled_package_variables),
total_disabled(s.total_disabled)
{
package_versions.update(*this, share, s.package_versions);
disabled_package_variables.update(*this, share, s.disabled_package_variables);
total_disabled.update(*this, share, s.total_disabled);
}
/// Copy during cloning
virtual Space*
copy(bool share) {
return new SimpleDependency(share,*this);
}
};
/** \brief Main-function
* \relates Money
*/
int
main(int argc, char* argv[]) {
Options opt("Solve dependency");
opt.solutions(0);
opt.iterations(20000);
opt.parse(argc,argv);
for (int i = 0; i < 1; i++)
// MinimizeScript::run<SimpleDependency,Restart,Options>(opt);
MinimizeScript::run<SimpleDependency,BAB,Options>(opt);
return 0;
}
// STATISTICS: example-any
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrGLVertexShaderBuilder.h"
#include "GrGLProgramBuilder.h"
#include "../GrGLGpu.h"
#define GL_CALL(X) GR_GL_CALL(fProgramBuilder->gpu()->glInterface(), X)
#define GL_CALL_RET(R, X) GR_GL_CALL_RET(fProgramBuilder->gpu()->glInterface(), R, X)
GrGLVertexBuilder::GrGLVertexBuilder(GrGLProgramBuilder* program)
: INHERITED(program)
, fRtAdjustName(NULL) {
}
void GrGLVertexBuilder::addVarying(const char* name, GrGLVarying* v) {
fOutputs.push_back();
fOutputs.back().setType(v->fType);
fOutputs.back().setTypeModifier(GrGLShaderVar::kVaryingOut_TypeModifier);
fProgramBuilder->nameVariable(fOutputs.back().accessName(), 'v', name);
v->fVsOut = fOutputs.back().getName().c_str();
}
void GrGLVertexBuilder::emitAttributes(const GrGeometryProcessor& gp) {
int vaCount = gp.numAttribs();
for (int i = 0; i < vaCount; i++) {
this->addAttribute(&gp.getAttrib(i));
}
return;
}
void GrGLVertexBuilder::transformToNormalizedDeviceSpace(const GrShaderVar& posVar) {
SkASSERT(!fRtAdjustName);
// setup RT Uniform
fProgramBuilder->fUniformHandles.fRTAdjustmentUni =
fProgramBuilder->addUniform(GrGLProgramBuilder::kVertex_Visibility,
kVec4f_GrSLType, kDefault_GrSLPrecision,
fProgramBuilder->rtAdjustment(),
&fRtAdjustName);
if (this->getProgramBuilder()->desc().header().fSnapVerticesToPixelCenters) {
if (kVec3f_GrSLType == posVar.getType()) {
const char* p = posVar.c_str();
this->codeAppendf("{vec2 _posTmp = vec2(%s.x/%s.z, %s.y/%s.z);", p, p, p, p);
} else {
SkASSERT(kVec2f_GrSLType == posVar.getType());
this->codeAppendf("{vec2 _posTmp = %s;", posVar.c_str());
}
this->codeAppendf("_posTmp = floor(_posTmp) + vec2(0.5, 0.5);"
"gl_Position = vec4(_posTmp.x * %s.x + %s.y, _posTmp.y * %s.z + %s.w, 0, 1);}",
fRtAdjustName, fRtAdjustName, fRtAdjustName, fRtAdjustName);
} else if (kVec3f_GrSLType == posVar.getType()) {
this->codeAppendf("gl_Position = vec4(dot(%s.xz, %s.xy)/%s.z, dot(%s.yz, %s.zw)/%s.z, 0, 1);",
posVar.c_str(), fRtAdjustName, posVar.c_str(),
posVar.c_str(), fRtAdjustName, posVar.c_str());
} else {
SkASSERT(kVec2f_GrSLType == posVar.getType());
this->codeAppendf("gl_Position = vec4(%s.x * %s.x + %s.y, %s.y * %s.z + %s.w, 0, 1);",
posVar.c_str(), fRtAdjustName, fRtAdjustName,
posVar.c_str(), fRtAdjustName, fRtAdjustName);
}
// We could have the GrGeometryProcessor do this, but its just easier to have it performed
// here. If we ever need to set variable pointsize, then we can reinvestigate
this->codeAppend("gl_PointSize = 1.0;");
}
void GrGLVertexBuilder::bindVertexAttributes(GrGLuint programID) {
const GrPrimitiveProcessor& primProc = fProgramBuilder->primitiveProcessor();
int vaCount = primProc.numAttribs();
for (int i = 0; i < vaCount; i++) {
GL_CALL(BindAttribLocation(programID, i, primProc.getAttrib(i).fName));
}
return;
}
bool
GrGLVertexBuilder::compileAndAttachShaders(GrGLuint programId, SkTDArray<GrGLuint>* shaderIds) {
this->versionDecl() = GrGetGLSLVersionDecl(fProgramBuilder->ctxInfo());
this->compileAndAppendLayoutQualifiers();
fProgramBuilder->appendUniformDecls(GrGLProgramBuilder::kVertex_Visibility, &this->uniforms());
this->appendDecls(fInputs, &this->inputs());
this->appendDecls(fOutputs, &this->outputs());
return this->finalize(programId, GR_GL_VERTEX_SHADER, shaderIds);
}
bool GrGLVertexBuilder::addAttribute(const GrShaderVar& var) {
SkASSERT(GrShaderVar::kAttribute_TypeModifier == var.getTypeModifier());
for (int i = 0; i < fInputs.count(); ++i) {
const GrGLShaderVar& attr = fInputs[i];
// if attribute already added, don't add it again
if (attr.getName().equals(var.getName())) {
return false;
}
}
fInputs.push_back(var);
return true;
}
<commit_msg>Fix edge-line artifacts issue on Mali<commit_after>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrGLVertexShaderBuilder.h"
#include "GrGLProgramBuilder.h"
#include "../GrGLGpu.h"
#define GL_CALL(X) GR_GL_CALL(fProgramBuilder->gpu()->glInterface(), X)
#define GL_CALL_RET(R, X) GR_GL_CALL_RET(fProgramBuilder->gpu()->glInterface(), R, X)
GrGLVertexBuilder::GrGLVertexBuilder(GrGLProgramBuilder* program)
: INHERITED(program)
, fRtAdjustName(NULL) {
}
void GrGLVertexBuilder::addVarying(const char* name, GrGLVarying* v) {
fOutputs.push_back();
fOutputs.back().setType(v->fType);
fOutputs.back().setTypeModifier(GrGLShaderVar::kVaryingOut_TypeModifier);
fProgramBuilder->nameVariable(fOutputs.back().accessName(), 'v', name);
v->fVsOut = fOutputs.back().getName().c_str();
}
void GrGLVertexBuilder::emitAttributes(const GrGeometryProcessor& gp) {
int vaCount = gp.numAttribs();
for (int i = 0; i < vaCount; i++) {
this->addAttribute(&gp.getAttrib(i));
}
return;
}
void GrGLVertexBuilder::transformToNormalizedDeviceSpace(const GrShaderVar& posVar) {
SkASSERT(!fRtAdjustName);
GrSLPrecision precision = kDefault_GrSLPrecision;
if (fProgramBuilder->ctxInfo().vendor() == kARM_GrGLVendor) {
precision = kHigh_GrSLPrecision;
}
// setup RT Uniform
fProgramBuilder->fUniformHandles.fRTAdjustmentUni =
fProgramBuilder->addUniform(GrGLProgramBuilder::kVertex_Visibility,
kVec4f_GrSLType, precision,
fProgramBuilder->rtAdjustment(),
&fRtAdjustName);
if (this->getProgramBuilder()->desc().header().fSnapVerticesToPixelCenters) {
if (kVec3f_GrSLType == posVar.getType()) {
const char* p = posVar.c_str();
this->codeAppendf("{vec2 _posTmp = vec2(%s.x/%s.z, %s.y/%s.z);", p, p, p, p);
} else {
SkASSERT(kVec2f_GrSLType == posVar.getType());
this->codeAppendf("{vec2 _posTmp = %s;", posVar.c_str());
}
this->codeAppendf("_posTmp = floor(_posTmp) + vec2(0.5, 0.5);"
"gl_Position = vec4(_posTmp.x * %s.x + %s.y, _posTmp.y * %s.z + %s.w, 0, 1);}",
fRtAdjustName, fRtAdjustName, fRtAdjustName, fRtAdjustName);
} else if (kVec3f_GrSLType == posVar.getType()) {
this->codeAppendf("gl_Position = vec4(dot(%s.xz, %s.xy)/%s.z, dot(%s.yz, %s.zw)/%s.z, 0, 1);",
posVar.c_str(), fRtAdjustName, posVar.c_str(),
posVar.c_str(), fRtAdjustName, posVar.c_str());
} else {
SkASSERT(kVec2f_GrSLType == posVar.getType());
this->codeAppendf("gl_Position = vec4(%s.x * %s.x + %s.y, %s.y * %s.z + %s.w, 0, 1);",
posVar.c_str(), fRtAdjustName, fRtAdjustName,
posVar.c_str(), fRtAdjustName, fRtAdjustName);
}
// We could have the GrGeometryProcessor do this, but its just easier to have it performed
// here. If we ever need to set variable pointsize, then we can reinvestigate
this->codeAppend("gl_PointSize = 1.0;");
}
void GrGLVertexBuilder::bindVertexAttributes(GrGLuint programID) {
const GrPrimitiveProcessor& primProc = fProgramBuilder->primitiveProcessor();
int vaCount = primProc.numAttribs();
for (int i = 0; i < vaCount; i++) {
GL_CALL(BindAttribLocation(programID, i, primProc.getAttrib(i).fName));
}
return;
}
bool
GrGLVertexBuilder::compileAndAttachShaders(GrGLuint programId, SkTDArray<GrGLuint>* shaderIds) {
this->versionDecl() = GrGetGLSLVersionDecl(fProgramBuilder->ctxInfo());
this->compileAndAppendLayoutQualifiers();
fProgramBuilder->appendUniformDecls(GrGLProgramBuilder::kVertex_Visibility, &this->uniforms());
this->appendDecls(fInputs, &this->inputs());
this->appendDecls(fOutputs, &this->outputs());
return this->finalize(programId, GR_GL_VERTEX_SHADER, shaderIds);
}
bool GrGLVertexBuilder::addAttribute(const GrShaderVar& var) {
SkASSERT(GrShaderVar::kAttribute_TypeModifier == var.getTypeModifier());
for (int i = 0; i < fInputs.count(); ++i) {
const GrGLShaderVar& attr = fInputs[i];
// if attribute already added, don't add it again
if (attr.getName().equals(var.getName())) {
return false;
}
}
fInputs.push_back(var);
return true;
}
<|endoftext|> |
<commit_before>/*
Copyright 2008 Brain Research Institute, Melbourne, Australia
Written by David Raffelt, 06/07/11.
This file is part of MRtrix.
MRtrix 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.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "memory.h"
#include "progressbar.h"
#include "algo/threaded_loop.h"
#include "image.h"
#include "math/SH.h"
using namespace MR;
using namespace App;
void usage ()
{
AUTHOR = "David Raffelt ([email protected])";
DESCRIPTION
+ "perform a spherical convolution";
ARGUMENTS
+ Argument ("SH", "the input spherical harmonics coefficients image.").type_image_in ()
+ Argument ("response", "the convolution kernel (response function)").type_file_in ()
+ Argument ("SH", "the output spherical harmonics coefficients image.").type_image_out ();
OPTIONS
+ Option ("mask", "only perform computation within the specified binary brain mask image.")
+ Argument ("image", "the mask image to use.").type_image_in ()
+ Stride::Options;
}
typedef float value_type;
class SConvFunctor {
public:
SConvFunctor (const size_t n, Image<bool>& mask,
const Eigen::Matrix<value_type, Eigen::Dynamic, 1>& response) :
image_mask (mask),
response (response),
SH_out (n){ }
void operator() (Image<value_type>& in, Image<value_type>& out) {
if (image_mask.valid()) {
assign_pos_of(in).to(image_mask);
if (!image_mask.value()) {
out.row(3) = Eigen::Matrix<value_type, Eigen::Dynamic, 1>::Zero (in.size(3));
return;
}
}
out.row(3) = Math::SH::sconv (SH_out, response, in.row(3));
}
protected:
Image<bool> image_mask;
Eigen::Matrix<value_type, Eigen::Dynamic, 1> response;
Eigen::Matrix<value_type, Eigen::Dynamic, 1> SH_out;
};
void run() {
auto image_in = Image<value_type>::open (argument[0]).with_direct_io (Stride::contiguous_along_axis(3));
Math::SH::check (image_in);
auto responseSH = load_vector<value_type>(argument[1]);
Eigen::Matrix<value_type, Eigen::Dynamic, 1> responseRH;
Math::SH::SH2RH (responseRH, responseSH);
auto mask = Image<bool>();
auto opt = get_options ("mask");
if (opt.size()) {
mask = Header::open (opt[0][0]).get_image<bool>();
check_dimensions (image_in, mask, 0, 3);
}
auto header = Header(image_in);
Stride::set_from_command_line (header);
auto image_out = Image<value_type>::create (argument[2], header);
SConvFunctor sconv (image_in.size(3), mask, responseRH);
ThreadedLoop ("performing convolution...", image_in, 0, 3, 2).run (sconv, image_in, image_out);
}
<commit_msg>sh2peaks: simplifying the fix for zero image data outside mask<commit_after>/*
Copyright 2008 Brain Research Institute, Melbourne, Australia
Written by David Raffelt, 06/07/11.
This file is part of MRtrix.
MRtrix 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.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "memory.h"
#include "progressbar.h"
#include "algo/threaded_loop.h"
#include "image.h"
#include "math/SH.h"
using namespace MR;
using namespace App;
void usage ()
{
AUTHOR = "David Raffelt ([email protected])";
DESCRIPTION
+ "perform a spherical convolution";
ARGUMENTS
+ Argument ("SH", "the input spherical harmonics coefficients image.").type_image_in ()
+ Argument ("response", "the convolution kernel (response function)").type_file_in ()
+ Argument ("SH", "the output spherical harmonics coefficients image.").type_image_out ();
OPTIONS
+ Option ("mask", "only perform computation within the specified binary brain mask image.")
+ Argument ("image", "the mask image to use.").type_image_in ()
+ Stride::Options;
}
typedef float value_type;
class SConvFunctor {
public:
SConvFunctor (const size_t n, Image<bool>& mask,
const Eigen::Matrix<value_type, Eigen::Dynamic, 1>& response) :
image_mask (mask),
response (response),
SH_out (n){ }
void operator() (Image<value_type>& in, Image<value_type>& out) {
if (image_mask.valid()) {
assign_pos_of(in).to(image_mask);
if (!image_mask.value()) {
out.row(3).setZero();
return;
}
}
out.row(3) = Math::SH::sconv (SH_out, response, in.row(3));
}
protected:
Image<bool> image_mask;
Eigen::Matrix<value_type, Eigen::Dynamic, 1> response;
Eigen::Matrix<value_type, Eigen::Dynamic, 1> SH_out;
};
void run() {
auto image_in = Image<value_type>::open (argument[0]).with_direct_io (Stride::contiguous_along_axis(3));
Math::SH::check (image_in);
auto responseSH = load_vector<value_type>(argument[1]);
Eigen::Matrix<value_type, Eigen::Dynamic, 1> responseRH;
Math::SH::SH2RH (responseRH, responseSH);
auto mask = Image<bool>();
auto opt = get_options ("mask");
if (opt.size()) {
mask = Header::open (opt[0][0]).get_image<bool>();
check_dimensions (image_in, mask, 0, 3);
}
auto header = Header(image_in);
Stride::set_from_command_line (header);
auto image_out = Image<value_type>::create (argument[2], header);
SConvFunctor sconv (image_in.size(3), mask, responseRH);
ThreadedLoop ("performing convolution...", image_in, 0, 3, 2).run (sconv, image_in, image_out);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 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 "net/http/http_network_session.h"
#include <utility>
#include "base/compiler_specific.h"
#include "base/debug/stack_trace.h"
#include "base/logging.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_response_body_drainer.h"
#include "net/http/http_stream_factory_impl.h"
#include "net/http/url_security_manager.h"
#include "net/proxy/proxy_service.h"
#include "net/quic/crypto/quic_random.h"
#include "net/quic/quic_clock.h"
#include "net/quic/quic_crypto_client_stream_factory.h"
#include "net/quic/quic_stream_factory.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/client_socket_pool_manager_impl.h"
#include "net/socket/next_proto.h"
#include "net/spdy/hpack_huffman_aggregator.h"
#include "net/spdy/spdy_session_pool.h"
namespace {
net::ClientSocketPoolManager* CreateSocketPoolManager(
net::HttpNetworkSession::SocketPoolType pool_type,
const net::HttpNetworkSession::Params& params) {
// TODO(yutak): Differentiate WebSocket pool manager and allow more
// simultaneous connections for WebSockets.
return new net::ClientSocketPoolManagerImpl(
params.net_log,
params.client_socket_factory
? params.client_socket_factory
: net::ClientSocketFactory::GetDefaultFactory(),
params.host_resolver,
params.cert_verifier,
params.channel_id_service,
params.transport_security_state,
params.cert_transparency_verifier,
params.ssl_session_cache_shard,
params.proxy_service,
params.ssl_config_service,
params.enable_ssl_connect_job_waiting,
pool_type);
}
} // unnamed namespace
namespace net {
HttpNetworkSession::Params::Params()
: client_socket_factory(NULL),
host_resolver(NULL),
cert_verifier(NULL),
channel_id_service(NULL),
transport_security_state(NULL),
cert_transparency_verifier(NULL),
proxy_service(NULL),
ssl_config_service(NULL),
http_auth_handler_factory(NULL),
network_delegate(NULL),
net_log(NULL),
host_mapping_rules(NULL),
enable_ssl_connect_job_waiting(false),
ignore_certificate_errors(false),
testing_fixed_http_port(0),
testing_fixed_https_port(0),
force_spdy_single_domain(false),
enable_spdy_compression(true),
enable_spdy_ping_based_connection_checking(true),
spdy_default_protocol(kProtoUnknown),
spdy_stream_initial_recv_window_size(0),
spdy_initial_max_concurrent_streams(0),
spdy_max_concurrent_streams_limit(0),
time_func(&base::TimeTicks::Now),
force_spdy_over_ssl(true),
force_spdy_always(false),
use_alternate_protocols(false),
alternate_protocol_probability_threshold(1),
enable_websocket_over_spdy(false),
enable_quic(false),
enable_quic_port_selection(true),
enable_quic_pacing(false),
enable_quic_time_based_loss_detection(false),
quic_clock(NULL),
quic_random(NULL),
quic_max_packet_length(kDefaultMaxPacketSize),
enable_user_alternate_protocol_ports(false),
quic_crypto_client_stream_factory(NULL) {
quic_supported_versions.push_back(QUIC_VERSION_19);
}
HttpNetworkSession::Params::~Params() {}
// TODO(mbelshe): Move the socket factories into HttpStreamFactory.
HttpNetworkSession::HttpNetworkSession(const Params& params)
: net_log_(params.net_log),
network_delegate_(params.network_delegate),
http_server_properties_(params.http_server_properties),
cert_verifier_(params.cert_verifier),
http_auth_handler_factory_(params.http_auth_handler_factory),
proxy_service_(params.proxy_service),
ssl_config_service_(params.ssl_config_service),
normal_socket_pool_manager_(
CreateSocketPoolManager(NORMAL_SOCKET_POOL, params)),
websocket_socket_pool_manager_(
CreateSocketPoolManager(WEBSOCKET_SOCKET_POOL, params)),
quic_stream_factory_(params.host_resolver,
params.client_socket_factory ?
params.client_socket_factory :
net::ClientSocketFactory::GetDefaultFactory(),
params.http_server_properties,
params.cert_verifier,
params.channel_id_service,
params.transport_security_state,
params.quic_crypto_client_stream_factory,
params.quic_random ? params.quic_random :
QuicRandom::GetInstance(),
params.quic_clock ? params. quic_clock :
new QuicClock(),
params.quic_max_packet_length,
params.quic_user_agent_id,
params.quic_supported_versions,
params.enable_quic_port_selection,
params.enable_quic_pacing,
params.enable_quic_time_based_loss_detection,
params.quic_connection_options),
spdy_session_pool_(params.host_resolver,
params.ssl_config_service,
params.http_server_properties,
params.force_spdy_single_domain,
params.enable_spdy_compression,
params.enable_spdy_ping_based_connection_checking,
params.spdy_default_protocol,
params.spdy_stream_initial_recv_window_size,
params.spdy_initial_max_concurrent_streams,
params.spdy_max_concurrent_streams_limit,
params.time_func,
params.trusted_spdy_proxy),
http_stream_factory_(new HttpStreamFactoryImpl(this, false)),
http_stream_factory_for_websocket_(
new HttpStreamFactoryImpl(this, true)),
params_(params) {
DCHECK(proxy_service_);
DCHECK(ssl_config_service_.get());
CHECK(http_server_properties_);
for (int i = ALTERNATE_PROTOCOL_MINIMUM_VALID_VERSION;
i <= ALTERNATE_PROTOCOL_MAXIMUM_VALID_VERSION; ++i) {
enabled_protocols_[i - ALTERNATE_PROTOCOL_MINIMUM_VALID_VERSION] = false;
}
// TODO(rtenneti): bug 116575 - consider combining the NextProto and
// AlternateProtocol.
for (std::vector<NextProto>::const_iterator it = params_.next_protos.begin();
it != params_.next_protos.end(); ++it) {
NextProto proto = *it;
// Add the protocol to the TLS next protocol list, except for QUIC
// since it uses UDP.
if (proto != kProtoQUIC1SPDY3) {
next_protos_.push_back(SSLClientSocket::NextProtoToString(proto));
}
// Enable the corresponding alternate protocol, except for HTTP
// which has not corresponding alternative.
if (proto != kProtoHTTP11) {
AlternateProtocol alternate = AlternateProtocolFromNextProto(proto);
if (!IsAlternateProtocolValid(alternate)) {
NOTREACHED() << "Invalid next proto: " << proto;
continue;
}
enabled_protocols_[alternate - ALTERNATE_PROTOCOL_MINIMUM_VALID_VERSION] =
true;
}
}
if (HpackHuffmanAggregator::UseAggregator()) {
huffman_aggregator_.reset(new HpackHuffmanAggregator());
}
http_server_properties_->SetAlternateProtocolProbabilityThreshold(
params.alternate_protocol_probability_threshold);
}
HttpNetworkSession::~HttpNetworkSession() {
STLDeleteElements(&response_drainers_);
spdy_session_pool_.CloseAllSessions();
}
void HttpNetworkSession::AddResponseDrainer(HttpResponseBodyDrainer* drainer) {
DCHECK(!ContainsKey(response_drainers_, drainer));
response_drainers_.insert(drainer);
}
void HttpNetworkSession::RemoveResponseDrainer(
HttpResponseBodyDrainer* drainer) {
DCHECK(ContainsKey(response_drainers_, drainer));
response_drainers_.erase(drainer);
}
TransportClientSocketPool* HttpNetworkSession::GetTransportSocketPool(
SocketPoolType pool_type) {
return GetSocketPoolManager(pool_type)->GetTransportSocketPool();
}
SSLClientSocketPool* HttpNetworkSession::GetSSLSocketPool(
SocketPoolType pool_type) {
return GetSocketPoolManager(pool_type)->GetSSLSocketPool();
}
SOCKSClientSocketPool* HttpNetworkSession::GetSocketPoolForSOCKSProxy(
SocketPoolType pool_type,
const HostPortPair& socks_proxy) {
return GetSocketPoolManager(pool_type)->GetSocketPoolForSOCKSProxy(
socks_proxy);
}
HttpProxyClientSocketPool* HttpNetworkSession::GetSocketPoolForHTTPProxy(
SocketPoolType pool_type,
const HostPortPair& http_proxy) {
return GetSocketPoolManager(pool_type)->GetSocketPoolForHTTPProxy(http_proxy);
}
SSLClientSocketPool* HttpNetworkSession::GetSocketPoolForSSLWithProxy(
SocketPoolType pool_type,
const HostPortPair& proxy_server) {
return GetSocketPoolManager(pool_type)->GetSocketPoolForSSLWithProxy(
proxy_server);
}
base::Value* HttpNetworkSession::SocketPoolInfoToValue() const {
// TODO(yutak): Should merge values from normal pools and WebSocket pools.
return normal_socket_pool_manager_->SocketPoolInfoToValue();
}
base::Value* HttpNetworkSession::SpdySessionPoolInfoToValue() const {
return spdy_session_pool_.SpdySessionPoolInfoToValue();
}
base::Value* HttpNetworkSession::QuicInfoToValue() const {
base::DictionaryValue* dict = new base::DictionaryValue();
dict->Set("sessions", quic_stream_factory_.QuicStreamFactoryInfoToValue());
dict->SetBoolean("quic_enabled", params_.enable_quic);
dict->SetBoolean("enable_quic_port_selection",
params_.enable_quic_port_selection);
dict->SetBoolean("enable_quic_pacing",
params_.enable_quic_pacing);
dict->SetBoolean("enable_quic_time_based_loss_detection",
params_.enable_quic_time_based_loss_detection);
dict->SetString("origin_to_force_quic_on",
params_.origin_to_force_quic_on.ToString());
return dict;
}
void HttpNetworkSession::CloseAllConnections() {
normal_socket_pool_manager_->FlushSocketPoolsWithError(ERR_ABORTED);
websocket_socket_pool_manager_->FlushSocketPoolsWithError(ERR_ABORTED);
spdy_session_pool_.CloseCurrentSessions(ERR_ABORTED);
quic_stream_factory_.CloseAllSessions(ERR_ABORTED);
}
void HttpNetworkSession::CloseIdleConnections() {
normal_socket_pool_manager_->CloseIdleSockets();
websocket_socket_pool_manager_->CloseIdleSockets();
spdy_session_pool_.CloseCurrentIdleSessions();
}
bool HttpNetworkSession::IsProtocolEnabled(AlternateProtocol protocol) const {
DCHECK(IsAlternateProtocolValid(protocol));
return enabled_protocols_[
protocol - ALTERNATE_PROTOCOL_MINIMUM_VALID_VERSION];
}
void HttpNetworkSession::GetNextProtos(
std::vector<std::string>* next_protos) const {
if (HttpStreamFactory::spdy_enabled()) {
*next_protos = next_protos_;
} else {
next_protos->clear();
}
}
bool HttpNetworkSession::HasSpdyExclusion(
HostPortPair host_port_pair) const {
return params_.forced_spdy_exclusions.find(host_port_pair) !=
params_.forced_spdy_exclusions.end();
}
ClientSocketPoolManager* HttpNetworkSession::GetSocketPoolManager(
SocketPoolType pool_type) {
switch (pool_type) {
case NORMAL_SOCKET_POOL:
return normal_socket_pool_manager_.get();
case WEBSOCKET_SOCKET_POOL:
return websocket_socket_pool_manager_.get();
default:
NOTREACHED();
break;
}
return NULL;
}
} // namespace net
<commit_msg>Enable QUIC_VERSION_21.<commit_after>// Copyright (c) 2012 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 "net/http/http_network_session.h"
#include <utility>
#include "base/compiler_specific.h"
#include "base/debug/stack_trace.h"
#include "base/logging.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_response_body_drainer.h"
#include "net/http/http_stream_factory_impl.h"
#include "net/http/url_security_manager.h"
#include "net/proxy/proxy_service.h"
#include "net/quic/crypto/quic_random.h"
#include "net/quic/quic_clock.h"
#include "net/quic/quic_crypto_client_stream_factory.h"
#include "net/quic/quic_stream_factory.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/client_socket_pool_manager_impl.h"
#include "net/socket/next_proto.h"
#include "net/spdy/hpack_huffman_aggregator.h"
#include "net/spdy/spdy_session_pool.h"
namespace {
net::ClientSocketPoolManager* CreateSocketPoolManager(
net::HttpNetworkSession::SocketPoolType pool_type,
const net::HttpNetworkSession::Params& params) {
// TODO(yutak): Differentiate WebSocket pool manager and allow more
// simultaneous connections for WebSockets.
return new net::ClientSocketPoolManagerImpl(
params.net_log,
params.client_socket_factory
? params.client_socket_factory
: net::ClientSocketFactory::GetDefaultFactory(),
params.host_resolver,
params.cert_verifier,
params.channel_id_service,
params.transport_security_state,
params.cert_transparency_verifier,
params.ssl_session_cache_shard,
params.proxy_service,
params.ssl_config_service,
params.enable_ssl_connect_job_waiting,
pool_type);
}
} // unnamed namespace
namespace net {
HttpNetworkSession::Params::Params()
: client_socket_factory(NULL),
host_resolver(NULL),
cert_verifier(NULL),
channel_id_service(NULL),
transport_security_state(NULL),
cert_transparency_verifier(NULL),
proxy_service(NULL),
ssl_config_service(NULL),
http_auth_handler_factory(NULL),
network_delegate(NULL),
net_log(NULL),
host_mapping_rules(NULL),
enable_ssl_connect_job_waiting(false),
ignore_certificate_errors(false),
testing_fixed_http_port(0),
testing_fixed_https_port(0),
force_spdy_single_domain(false),
enable_spdy_compression(true),
enable_spdy_ping_based_connection_checking(true),
spdy_default_protocol(kProtoUnknown),
spdy_stream_initial_recv_window_size(0),
spdy_initial_max_concurrent_streams(0),
spdy_max_concurrent_streams_limit(0),
time_func(&base::TimeTicks::Now),
force_spdy_over_ssl(true),
force_spdy_always(false),
use_alternate_protocols(false),
alternate_protocol_probability_threshold(1),
enable_websocket_over_spdy(false),
enable_quic(false),
enable_quic_port_selection(true),
enable_quic_pacing(false),
enable_quic_time_based_loss_detection(false),
quic_clock(NULL),
quic_random(NULL),
quic_max_packet_length(kDefaultMaxPacketSize),
enable_user_alternate_protocol_ports(false),
quic_crypto_client_stream_factory(NULL) {
quic_supported_versions.push_back(QUIC_VERSION_21);
}
HttpNetworkSession::Params::~Params() {}
// TODO(mbelshe): Move the socket factories into HttpStreamFactory.
HttpNetworkSession::HttpNetworkSession(const Params& params)
: net_log_(params.net_log),
network_delegate_(params.network_delegate),
http_server_properties_(params.http_server_properties),
cert_verifier_(params.cert_verifier),
http_auth_handler_factory_(params.http_auth_handler_factory),
proxy_service_(params.proxy_service),
ssl_config_service_(params.ssl_config_service),
normal_socket_pool_manager_(
CreateSocketPoolManager(NORMAL_SOCKET_POOL, params)),
websocket_socket_pool_manager_(
CreateSocketPoolManager(WEBSOCKET_SOCKET_POOL, params)),
quic_stream_factory_(params.host_resolver,
params.client_socket_factory ?
params.client_socket_factory :
net::ClientSocketFactory::GetDefaultFactory(),
params.http_server_properties,
params.cert_verifier,
params.channel_id_service,
params.transport_security_state,
params.quic_crypto_client_stream_factory,
params.quic_random ? params.quic_random :
QuicRandom::GetInstance(),
params.quic_clock ? params. quic_clock :
new QuicClock(),
params.quic_max_packet_length,
params.quic_user_agent_id,
params.quic_supported_versions,
params.enable_quic_port_selection,
params.enable_quic_pacing,
params.enable_quic_time_based_loss_detection,
params.quic_connection_options),
spdy_session_pool_(params.host_resolver,
params.ssl_config_service,
params.http_server_properties,
params.force_spdy_single_domain,
params.enable_spdy_compression,
params.enable_spdy_ping_based_connection_checking,
params.spdy_default_protocol,
params.spdy_stream_initial_recv_window_size,
params.spdy_initial_max_concurrent_streams,
params.spdy_max_concurrent_streams_limit,
params.time_func,
params.trusted_spdy_proxy),
http_stream_factory_(new HttpStreamFactoryImpl(this, false)),
http_stream_factory_for_websocket_(
new HttpStreamFactoryImpl(this, true)),
params_(params) {
DCHECK(proxy_service_);
DCHECK(ssl_config_service_.get());
CHECK(http_server_properties_);
for (int i = ALTERNATE_PROTOCOL_MINIMUM_VALID_VERSION;
i <= ALTERNATE_PROTOCOL_MAXIMUM_VALID_VERSION; ++i) {
enabled_protocols_[i - ALTERNATE_PROTOCOL_MINIMUM_VALID_VERSION] = false;
}
// TODO(rtenneti): bug 116575 - consider combining the NextProto and
// AlternateProtocol.
for (std::vector<NextProto>::const_iterator it = params_.next_protos.begin();
it != params_.next_protos.end(); ++it) {
NextProto proto = *it;
// Add the protocol to the TLS next protocol list, except for QUIC
// since it uses UDP.
if (proto != kProtoQUIC1SPDY3) {
next_protos_.push_back(SSLClientSocket::NextProtoToString(proto));
}
// Enable the corresponding alternate protocol, except for HTTP
// which has not corresponding alternative.
if (proto != kProtoHTTP11) {
AlternateProtocol alternate = AlternateProtocolFromNextProto(proto);
if (!IsAlternateProtocolValid(alternate)) {
NOTREACHED() << "Invalid next proto: " << proto;
continue;
}
enabled_protocols_[alternate - ALTERNATE_PROTOCOL_MINIMUM_VALID_VERSION] =
true;
}
}
if (HpackHuffmanAggregator::UseAggregator()) {
huffman_aggregator_.reset(new HpackHuffmanAggregator());
}
http_server_properties_->SetAlternateProtocolProbabilityThreshold(
params.alternate_protocol_probability_threshold);
}
HttpNetworkSession::~HttpNetworkSession() {
STLDeleteElements(&response_drainers_);
spdy_session_pool_.CloseAllSessions();
}
void HttpNetworkSession::AddResponseDrainer(HttpResponseBodyDrainer* drainer) {
DCHECK(!ContainsKey(response_drainers_, drainer));
response_drainers_.insert(drainer);
}
void HttpNetworkSession::RemoveResponseDrainer(
HttpResponseBodyDrainer* drainer) {
DCHECK(ContainsKey(response_drainers_, drainer));
response_drainers_.erase(drainer);
}
TransportClientSocketPool* HttpNetworkSession::GetTransportSocketPool(
SocketPoolType pool_type) {
return GetSocketPoolManager(pool_type)->GetTransportSocketPool();
}
SSLClientSocketPool* HttpNetworkSession::GetSSLSocketPool(
SocketPoolType pool_type) {
return GetSocketPoolManager(pool_type)->GetSSLSocketPool();
}
SOCKSClientSocketPool* HttpNetworkSession::GetSocketPoolForSOCKSProxy(
SocketPoolType pool_type,
const HostPortPair& socks_proxy) {
return GetSocketPoolManager(pool_type)->GetSocketPoolForSOCKSProxy(
socks_proxy);
}
HttpProxyClientSocketPool* HttpNetworkSession::GetSocketPoolForHTTPProxy(
SocketPoolType pool_type,
const HostPortPair& http_proxy) {
return GetSocketPoolManager(pool_type)->GetSocketPoolForHTTPProxy(http_proxy);
}
SSLClientSocketPool* HttpNetworkSession::GetSocketPoolForSSLWithProxy(
SocketPoolType pool_type,
const HostPortPair& proxy_server) {
return GetSocketPoolManager(pool_type)->GetSocketPoolForSSLWithProxy(
proxy_server);
}
base::Value* HttpNetworkSession::SocketPoolInfoToValue() const {
// TODO(yutak): Should merge values from normal pools and WebSocket pools.
return normal_socket_pool_manager_->SocketPoolInfoToValue();
}
base::Value* HttpNetworkSession::SpdySessionPoolInfoToValue() const {
return spdy_session_pool_.SpdySessionPoolInfoToValue();
}
base::Value* HttpNetworkSession::QuicInfoToValue() const {
base::DictionaryValue* dict = new base::DictionaryValue();
dict->Set("sessions", quic_stream_factory_.QuicStreamFactoryInfoToValue());
dict->SetBoolean("quic_enabled", params_.enable_quic);
dict->SetBoolean("enable_quic_port_selection",
params_.enable_quic_port_selection);
dict->SetBoolean("enable_quic_pacing",
params_.enable_quic_pacing);
dict->SetBoolean("enable_quic_time_based_loss_detection",
params_.enable_quic_time_based_loss_detection);
dict->SetString("origin_to_force_quic_on",
params_.origin_to_force_quic_on.ToString());
return dict;
}
void HttpNetworkSession::CloseAllConnections() {
normal_socket_pool_manager_->FlushSocketPoolsWithError(ERR_ABORTED);
websocket_socket_pool_manager_->FlushSocketPoolsWithError(ERR_ABORTED);
spdy_session_pool_.CloseCurrentSessions(ERR_ABORTED);
quic_stream_factory_.CloseAllSessions(ERR_ABORTED);
}
void HttpNetworkSession::CloseIdleConnections() {
normal_socket_pool_manager_->CloseIdleSockets();
websocket_socket_pool_manager_->CloseIdleSockets();
spdy_session_pool_.CloseCurrentIdleSessions();
}
bool HttpNetworkSession::IsProtocolEnabled(AlternateProtocol protocol) const {
DCHECK(IsAlternateProtocolValid(protocol));
return enabled_protocols_[
protocol - ALTERNATE_PROTOCOL_MINIMUM_VALID_VERSION];
}
void HttpNetworkSession::GetNextProtos(
std::vector<std::string>* next_protos) const {
if (HttpStreamFactory::spdy_enabled()) {
*next_protos = next_protos_;
} else {
next_protos->clear();
}
}
bool HttpNetworkSession::HasSpdyExclusion(
HostPortPair host_port_pair) const {
return params_.forced_spdy_exclusions.find(host_port_pair) !=
params_.forced_spdy_exclusions.end();
}
ClientSocketPoolManager* HttpNetworkSession::GetSocketPoolManager(
SocketPoolType pool_type) {
switch (pool_type) {
case NORMAL_SOCKET_POOL:
return normal_socket_pool_manager_.get();
case WEBSOCKET_SOCKET_POOL:
return websocket_socket_pool_manager_.get();
default:
NOTREACHED();
break;
}
return NULL;
}
} // namespace net
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include <ydsh/ydsh.h>
#include <misc/files.h>
#include <directive.h>
#include "../test_common.h"
#ifndef EXEC_TEST_DIR
#error require EXEC_TEST_DIR
#endif
#ifndef BIN_PATH
#error require BIN_PATH
#endif
using namespace ydsh;
using namespace ydsh::directive;
// parse config(key = value)
template <typename ...T>
int parse(const std::string &src, T&& ...args) {
return Extractor(src.c_str())(std::forward<T>(args)...);
}
template <typename ...T>
int parse(const char *src, T&& ...args) {
return Extractor(src)(std::forward<T>(args)...);
}
static std::vector<std::string> getSortedFileList(const char *dir) {
auto ret = getFileList(dir, true);
assert(!ret.empty());
std::sort(ret.begin(), ret.end());
ret.erase(std::unique(ret.begin(), ret.end()), ret.end());
return ret;
}
class ExecTest : public ::testing::TestWithParam<std::string>, public TempFileFactory {
protected:
std::string targetName;
public:
ExecTest() {
this->targetName = this->GetParam();
}
virtual const std::string &getSourceName() {
return this->targetName;
}
virtual void doTest() {
// create directive
Directive d;
bool s = Directive::init(this->getSourceName().c_str(), d);
ASSERT_TRUE(s);
if(d.isIgnoredPlatform()) {
fprintf(stderr, "ignore execution: %s\n", this->getSourceName().c_str());
return;
}
const char *scriptName = this->getSourceName().c_str();
ProcBuilder builder(BIN_PATH);
builder.addArg("--status-log").addArg(this->getTempFileName());
// set argument
builder.addArg(scriptName);
builder.addArgs(d.getParams());
// set IO config
if(!d.getIn().empty()) {
builder.setIn(IOConfig::PIPE);
}
if(d.getOut()) {
builder.setOut(IOConfig::PIPE);
}
if(d.getErr()) {
builder.setErr(IOConfig::PIPE);
}
// set working dir
builder.setWorkingDir(EXEC_TEST_DIR);
// set env
for(auto &env : d.getEnvs()) {
builder.addEnv(env.first.c_str(), env.second.c_str());
}
// execute
auto handle = builder();
if(!d.getIn().empty()) {
if(write(handle.in(), d.getIn().c_str(), d.getIn().size()) < 0) {
fatal_perror("");
}
close(handle.in());
}
auto output = handle.waitAndGetResult(false);
int ret = output.status.toShellStatus();
// get internal status
std::ifstream input(this->getTempFileName());
ASSERT_FALSE(!input);
std::string line;
std::getline(input, line);
ASSERT_FALSE(line.empty());
unsigned int kind;
unsigned int lineNum;
std::string name;
std::string fileName;
int r = parse(line, "kind", "=", kind, "lineNum", "=", lineNum, "name", "=", name, "fileName", "=", fileName);
ASSERT_EQ(0, r);
// check status
ASSERT_EQ(d.getResult(), kind);
ASSERT_EQ(d.getLineNum(), lineNum);
ASSERT_EQ(d.getStatus(), static_cast<unsigned int>(ret));
ASSERT_EQ(d.getErrorKind(), name);
if(!d.getFileName().empty()) {
ASSERT_EQ(d.getFileName(), fileName);
}
if(d.getOut()) {
ASSERT_STREQ(d.getOut(), output.out.c_str());
}
if(d.getErr()) {
ASSERT_STREQ(d.getErr(), output.err.c_str());
}
}
};
TEST_P(ExecTest, baseTest) {
printf("@@ test script %s\n", this->targetName.c_str());
ASSERT_NO_FATAL_FAILURE(this->doTest());
}
INSTANTIATE_TEST_CASE_P(ExecTest, ExecTest, ::testing::ValuesIn(getSortedFileList(EXEC_TEST_DIR)));
TEST(Base, case1) {
std::string line(R"(type=3 lineNum=1 kind="SystemError" fileName="../hoge.ds")");
unsigned int type;
unsigned int lineNum;
std::string kind;
std::string fileName;
int ret = parse(line, "type", "=", type, "lineNum", "=", lineNum, "kind", "=", kind, "fileName", "=", fileName);
ASSERT_EQ(0, ret);
ASSERT_EQ(3u, type);
ASSERT_EQ(1u, lineNum);
ASSERT_EQ("SystemError", kind);
ASSERT_EQ("../hoge.ds", fileName);
}
TEST(Base, case2) {
std::string line("type=0 lineNum=0 kind=\"\"");
unsigned int type;
unsigned int lineNum;
std::string kind;
int ret = parse(line, "type", "=", type, "lineNum", "=", lineNum, "kind", "=", kind);
ASSERT_EQ(0, ret);
ASSERT_EQ(0u, type);
ASSERT_EQ(0u, lineNum);
ASSERT_EQ("", kind);
}
TEST(Base, case3) {
std::string line(R"(type=0 lineNum=0 kind="" fileName="" )");
unsigned int type;
unsigned int lineNum;
std::string kind;
std::string fileName;
int ret = parse(line, "type", "=", type, "lineNum", "=", lineNum, "kind", "=", kind, "fileName", "=", fileName);
ASSERT_EQ(0, ret);
ASSERT_EQ(0u, type);
ASSERT_EQ(0u, lineNum);
ASSERT_EQ("", kind);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
if(chdir(EXEC_TEST_DIR) != 0) {
fatal("broken test directory: %s\n", EXEC_TEST_DIR);
}
return RUN_ALL_TESTS();
}<commit_msg>add missing header<commit_after>#include "gtest/gtest.h"
#include <fstream>
#include <ydsh/ydsh.h>
#include <misc/files.h>
#include <directive.h>
#include "../test_common.h"
#ifndef EXEC_TEST_DIR
#error require EXEC_TEST_DIR
#endif
#ifndef BIN_PATH
#error require BIN_PATH
#endif
using namespace ydsh;
using namespace ydsh::directive;
// parse config(key = value)
template <typename ...T>
int parse(const std::string &src, T&& ...args) {
return Extractor(src.c_str())(std::forward<T>(args)...);
}
template <typename ...T>
int parse(const char *src, T&& ...args) {
return Extractor(src)(std::forward<T>(args)...);
}
static std::vector<std::string> getSortedFileList(const char *dir) {
auto ret = getFileList(dir, true);
assert(!ret.empty());
std::sort(ret.begin(), ret.end());
ret.erase(std::unique(ret.begin(), ret.end()), ret.end());
return ret;
}
class ExecTest : public ::testing::TestWithParam<std::string>, public TempFileFactory {
protected:
std::string targetName;
public:
ExecTest() {
this->targetName = this->GetParam();
}
virtual const std::string &getSourceName() {
return this->targetName;
}
virtual void doTest() {
// create directive
Directive d;
bool s = Directive::init(this->getSourceName().c_str(), d);
ASSERT_TRUE(s);
if(d.isIgnoredPlatform()) {
fprintf(stderr, "ignore execution: %s\n", this->getSourceName().c_str());
return;
}
const char *scriptName = this->getSourceName().c_str();
ProcBuilder builder(BIN_PATH);
builder.addArg("--status-log").addArg(this->getTempFileName());
// set argument
builder.addArg(scriptName);
builder.addArgs(d.getParams());
// set IO config
if(!d.getIn().empty()) {
builder.setIn(IOConfig::PIPE);
}
if(d.getOut()) {
builder.setOut(IOConfig::PIPE);
}
if(d.getErr()) {
builder.setErr(IOConfig::PIPE);
}
// set working dir
builder.setWorkingDir(EXEC_TEST_DIR);
// set env
for(auto &env : d.getEnvs()) {
builder.addEnv(env.first.c_str(), env.second.c_str());
}
// execute
auto handle = builder();
if(!d.getIn().empty()) {
if(write(handle.in(), d.getIn().c_str(), d.getIn().size()) < 0) {
fatal_perror("");
}
close(handle.in());
}
auto output = handle.waitAndGetResult(false);
int ret = output.status.toShellStatus();
// get internal status
std::ifstream input(this->getTempFileName());
ASSERT_FALSE(!input);
std::string line;
std::getline(input, line);
ASSERT_FALSE(line.empty());
unsigned int kind;
unsigned int lineNum;
std::string name;
std::string fileName;
int r = parse(line, "kind", "=", kind, "lineNum", "=", lineNum, "name", "=", name, "fileName", "=", fileName);
ASSERT_EQ(0, r);
// check status
ASSERT_EQ(d.getResult(), kind);
ASSERT_EQ(d.getLineNum(), lineNum);
ASSERT_EQ(d.getStatus(), static_cast<unsigned int>(ret));
ASSERT_EQ(d.getErrorKind(), name);
if(!d.getFileName().empty()) {
ASSERT_EQ(d.getFileName(), fileName);
}
if(d.getOut()) {
ASSERT_STREQ(d.getOut(), output.out.c_str());
}
if(d.getErr()) {
ASSERT_STREQ(d.getErr(), output.err.c_str());
}
}
};
TEST_P(ExecTest, baseTest) {
printf("@@ test script %s\n", this->targetName.c_str());
ASSERT_NO_FATAL_FAILURE(this->doTest());
}
INSTANTIATE_TEST_CASE_P(ExecTest, ExecTest, ::testing::ValuesIn(getSortedFileList(EXEC_TEST_DIR)));
TEST(Base, case1) {
std::string line(R"(type=3 lineNum=1 kind="SystemError" fileName="../hoge.ds")");
unsigned int type;
unsigned int lineNum;
std::string kind;
std::string fileName;
int ret = parse(line, "type", "=", type, "lineNum", "=", lineNum, "kind", "=", kind, "fileName", "=", fileName);
ASSERT_EQ(0, ret);
ASSERT_EQ(3u, type);
ASSERT_EQ(1u, lineNum);
ASSERT_EQ("SystemError", kind);
ASSERT_EQ("../hoge.ds", fileName);
}
TEST(Base, case2) {
std::string line("type=0 lineNum=0 kind=\"\"");
unsigned int type;
unsigned int lineNum;
std::string kind;
int ret = parse(line, "type", "=", type, "lineNum", "=", lineNum, "kind", "=", kind);
ASSERT_EQ(0, ret);
ASSERT_EQ(0u, type);
ASSERT_EQ(0u, lineNum);
ASSERT_EQ("", kind);
}
TEST(Base, case3) {
std::string line(R"(type=0 lineNum=0 kind="" fileName="" )");
unsigned int type;
unsigned int lineNum;
std::string kind;
std::string fileName;
int ret = parse(line, "type", "=", type, "lineNum", "=", lineNum, "kind", "=", kind, "fileName", "=", fileName);
ASSERT_EQ(0, ret);
ASSERT_EQ(0u, type);
ASSERT_EQ(0u, lineNum);
ASSERT_EQ("", kind);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
if(chdir(EXEC_TEST_DIR) != 0) {
fatal("broken test directory: %s\n", EXEC_TEST_DIR);
}
return RUN_ALL_TESTS();
}<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/hwpf/fapi2/include/error_info_defs.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2011,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file error_info_defs.H
/// @brief Defines to support the Error Information class
///
#ifndef FAPI2_ERRORINFO_DEFS_H_
#define FAPI2_ERRORINFO_DEFS_H_
#include <stdint.h>
#include <target.H>
#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)
#include <variable_buffer.H>
#include <utility>
#endif
namespace fapi2
{
///
/// @brief Type to hold the ffdc data to be sent to hostboot
///
/// Note: Typical data sent seems to be register/addresss info
/// rather than use extra space converting stuff just
/// send a uint64 always
///
struct sbeFfdc_t
{
uint32_t size;
uint64_t data;
} __attribute__((packed));
// 10 entries limits the size of SbeFfdcData_t to 128 bytes
enum
{
MAX_SBE_FFDC_ENTRIES = 10
};
// Data type for SBE ffdc buffer sent through fifo
typedef struct
{
uint32_t fapiRc; // Return code from failure
uint32_t ffdcLength; // length of Fapi FFDC data (in bytes)
struct sbeFfdc_t ffdcData[MAX_SBE_FFDC_ENTRIES]; // fapi FFDC data
} SbeFfdcData_t; // 128 bytes
///
/// @brief Type to hold the ffdc element in the ffdc class
/// Needed so that the size can be squirled away before the
/// macro is called.
///
struct ffdc_struct
{
const void* ptr;
size_t size;
};
class ffdc_t
{
public:
ffdc_t(void)
{}
void operator=(const ffdc_t& i )
{
iv_value.ptr = i.ptr();
iv_value.size = i.size();
}
operator const void* () const
{
return iv_value.ptr;
}
operator uint8_t() const
{
return *(reinterpret_cast<const uint8_t*>(iv_value.ptr));
}
size_t size(void) const
{
return iv_value.size;
}
size_t& size(void)
{
return iv_value.size;
}
const void* ptr(void) const
{
return iv_value.ptr;
}
const void*& ptr(void)
{
return iv_value.ptr;
}
private:
struct ffdc_struct iv_value = {}; //init to zero
};
///
/// @brief Enumeration of ErrorInfo FFDC sizes that are used to indicate a
/// special type that cannot simply be memcopied
enum ErrorInfoFfdcSize
{
EI_FFDC_SIZE_BUF = 0xffff, // fapi2::buffer<T>
EI_FFDC_SIZE_TARGET = 0xfffe, // fapi2::Target
EI_FFDC_SIZE_VBUF = 0xfffd, // fapi2::variable_buffer
EI_FFDC_MAX_SIZE = 0x1000, // Limit regular FFDC capture to 4kb
};
///
/// @brief Enumeration of error log severity.
///
enum errlSeverity_t
{
FAPI2_ERRL_SEV_UNDEFINED = 0x00, /// Used internally by ffdc mechanism
FAPI2_ERRL_SEV_RECOVERED = 0x10, /// Not seen by customer
FAPI2_ERRL_SEV_PREDICTIVE = 0x20, /// Error recovered but customer will see
FAPI2_ERRL_SEV_UNRECOVERABLE = 0x40 /// Unrecoverable, general
};
///
/// @brief Enumeration of ErrorInfo types
///
enum ErrorInfoType
{
EI_TYPE_FFDC = 0,
EI_TYPE_HW_CALLOUT = 1,
EI_TYPE_PROCEDURE_CALLOUT = 2,
EI_TYPE_BUS_CALLOUT = 3,
EI_TYPE_CDG = 4, // Target Callout/Deconfig/GARD
EI_TYPE_CHILDREN_CDG = 5, // Children Callout/Deconfig/GARD
EI_TYPE_COLLECT_TRACE = 6,
EI_LAST_TYPE = EI_TYPE_COLLECT_TRACE + 1,
};
#ifndef MINIMUM_FFDC
///
/// @enum HwCallout
///
/// This enumeration defines the possible Hardware Callouts that are not
/// represented by fapi2::Targets
///
/// Note that platform code may depend on the enum values starting at 0 and
/// incrementing in order to efficiently convert to a platform callout value
/// so do not reorder without consulting all platforms
///
namespace HwCallouts
{
enum HwCallout
{
// Where indicated, a HW Callout in FAPI Error XML must include a
// reference target that is used to identify the HW. e.g. for
// TOD_CLOCK, the proc chip that the clock is attached to must be
// specified
TOD_CLOCK = 0, // Include proc-chip ref (or child chiplet)
MEM_REF_CLOCK = 1, // Include membuf-chip ref (or child chiplet)
PROC_REF_CLOCK = 2, // Include proc-chip ref (or child chiplet)
PCI_REF_CLOCK = 3, // Include proc-chip ref (or child chiplet)
FLASH_CONTROLLER_PART = 4,
PNOR_PART = 5,
SBE_SEEPROM_PART = 6,
VPD_PART = 7,
LPC_SLAVE_PART = 8,
GPIO_EXPANDER_PART = 9,
SPIVID_SLAVE_PART = 10,
};
}
///
/// @enum ProcedureCallout
///
/// This enumeration defines the possible Procedure Callouts
/// These instruct the customer/customer-engineer what to do
///
/// Note that platform code may depend on the enum values starting at 0 and
/// incrementing in order to efficiently convert to a platform callout value
/// so do not reorder without consulting all platforms
///
namespace ProcedureCallouts
{
enum ProcedureCallout
{
CODE = 0, // Code problem
LVL_SUPPORT = 1, // Call next level of support
MEMORY_PLUGGING_ERROR = 2, // DIMM Plugging error
BUS_CALLOUT = 3, // Bus Called Out
};
}
///
/// @enum CalloutPriority
///
/// This enumeration defines the possible Procedure and Target callout priorities
///
/// Note that platform code may depend on the enum values starting at 0 and
/// incrementing in order to efficiently convert to a platform priority value
/// so do not reorder without consulting all platforms
///
namespace CalloutPriorities
{
enum CalloutPriority
{
LOW = 0,
MEDIUM = 1,
HIGH = 2,
};
}
///
/// @enum CollectTrace
///
/// This enumeration defines the possible firmware traces to collect
///
namespace CollectTraces
{
const uint32_t TRACE_SIZE = 256; // limit collected trace size
enum CollectTrace
{
FSI = 1,
SCOM = 2,
SCAN = 3,
MBOX = 4,
};
}
// NOTE - this assumes no buffer_t or variable_buffers are passed
// data is converted to a uint64_t when placed into the sbe ffdc
// buffer
inline fapi2::ffdc_t getFfdcData( sbeFfdc_t& i_sbeFfdc )
{
fapi2::ffdc_t temp;
temp.size() = static_cast<size_t>(i_sbeFfdc.size);
if(temp.size() == EI_FFDC_SIZE_TARGET)
{
#ifdef FAPI2_ENABLE_PLATFORM_GET_TARGET
uint64_t targetData = i_sbeFfdc.data;
fapi2::TargetType type = static_cast<fapi2::TargetType>(targetData >> 32);
uint8_t instance = static_cast<uint8_t>(targetData & 0xFFFFFFFF);
// call hostboot to get the fapi2 target reference
temp.ptr() = static_cast<void*>(getTarget<TARGET_TYPE_ALL>(type, instance));
#endif
}
else
{
// adjust the pointer based on the data size.
temp.ptr() = static_cast<void*>(reinterpret_cast<uint8_t*>(&i_sbeFfdc.data) +
(sizeof(uint64_t) - i_sbeFfdc.size));
}
return temp;
}
#endif
///
/// @brief Get FFDC Size
///
/// This is called by the FAPI_SET_HWP_ERROR macro to find out the size of
/// FFDC data. If the data is of a special type that is handled differently
/// than types that are simply memcopied then it is handled by a template
/// specialization.
/// If this function template is instantiated with a pointer, the compile
/// will fail.
///
/// @return uint16_t. Size of the FFDC data
///
template<typename T>
inline uint16_t getErrorInfoFfdcSize(const T&)
{
static_assert(sizeof(T) <= EI_FFDC_MAX_SIZE,
"FFDC too large to capture");
return sizeof(T);
}
#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)
///
/// @brief Compile error if caller tries to get the FFDC size of a pointer
///
template<typename T>
inline uint16_t getErrorInfoFfdcSize(const T*)
{
static_assert(std::is_pointer<T>::value,
"pointer passed to getErrorInfoFfdcSize");
return 0;
}
#endif
///
/// @brief Get FFDC Size specialization for fapi2::Target
///
template<fapi2::TargetType T, typename V>
inline uint16_t getErrorInfoFfdcSize(const fapi2::Target<T, V>&)
{
return EI_FFDC_SIZE_TARGET;
}
#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)
///
/// @brief Get FFDC Size specialization for variable buffers
///
template<>
inline uint16_t getErrorInfoFfdcSize(const fapi2::variable_buffer& i_thing)
{
// Limit a variable buffer to 4kb bytes, and we can memcpy the storage.
return std::min(static_cast<uint32_t>(EI_FFDC_MAX_SIZE),
i_thing.getLength<uint8_t>());
}
#endif
///
/// @brief Get FFDC Size specialization for ffdc_t
///
template<>
inline uint16_t getErrorInfoFfdcSize(const fapi2::ffdc_t& i_ffdc)
{
return static_cast<uint16_t>(i_ffdc.size());
}
};
#endif // FAPI2_ERRORINFO_DEFS_H_
<commit_msg>Allow HWP to deconfigure parts without a callout<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/hwpf/fapi2/include/error_info_defs.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2011,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file error_info_defs.H
/// @brief Defines to support the Error Information class
///
#ifndef FAPI2_ERRORINFO_DEFS_H_
#define FAPI2_ERRORINFO_DEFS_H_
#include <stdint.h>
#include <target.H>
#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)
#include <variable_buffer.H>
#include <utility>
#endif
namespace fapi2
{
///
/// @brief Type to hold the ffdc data to be sent to hostboot
///
/// Note: Typical data sent seems to be register/addresss info
/// rather than use extra space converting stuff just
/// send a uint64 always
///
struct sbeFfdc_t
{
uint32_t size;
uint64_t data;
} __attribute__((packed));
// 10 entries limits the size of SbeFfdcData_t to 128 bytes
enum
{
MAX_SBE_FFDC_ENTRIES = 10
};
// Data type for SBE ffdc buffer sent through fifo
typedef struct
{
uint32_t fapiRc; // Return code from failure
uint32_t ffdcLength; // length of Fapi FFDC data (in bytes)
struct sbeFfdc_t ffdcData[MAX_SBE_FFDC_ENTRIES]; // fapi FFDC data
} SbeFfdcData_t; // 128 bytes
///
/// @brief Type to hold the ffdc element in the ffdc class
/// Needed so that the size can be squirled away before the
/// macro is called.
///
struct ffdc_struct
{
const void* ptr;
size_t size;
};
class ffdc_t
{
public:
ffdc_t(void)
{}
void operator=(const ffdc_t& i )
{
iv_value.ptr = i.ptr();
iv_value.size = i.size();
}
operator const void* () const
{
return iv_value.ptr;
}
operator uint8_t() const
{
return *(reinterpret_cast<const uint8_t*>(iv_value.ptr));
}
size_t size(void) const
{
return iv_value.size;
}
size_t& size(void)
{
return iv_value.size;
}
const void* ptr(void) const
{
return iv_value.ptr;
}
const void*& ptr(void)
{
return iv_value.ptr;
}
private:
struct ffdc_struct iv_value = {}; //init to zero
};
///
/// @brief Enumeration of ErrorInfo FFDC sizes that are used to indicate a
/// special type that cannot simply be memcopied
enum ErrorInfoFfdcSize
{
EI_FFDC_SIZE_BUF = 0xffff, // fapi2::buffer<T>
EI_FFDC_SIZE_TARGET = 0xfffe, // fapi2::Target
EI_FFDC_SIZE_VBUF = 0xfffd, // fapi2::variable_buffer
EI_FFDC_MAX_SIZE = 0x1000, // Limit regular FFDC capture to 4kb
};
///
/// @brief Enumeration of error log severity.
///
enum errlSeverity_t
{
FAPI2_ERRL_SEV_UNDEFINED = 0x00, /// Used internally by ffdc mechanism
FAPI2_ERRL_SEV_RECOVERED = 0x10, /// Not seen by customer
FAPI2_ERRL_SEV_PREDICTIVE = 0x20, /// Error recovered but customer will see
FAPI2_ERRL_SEV_UNRECOVERABLE = 0x40 /// Unrecoverable, general
};
///
/// @brief Enumeration of ErrorInfo types
///
enum ErrorInfoType
{
EI_TYPE_FFDC = 0,
EI_TYPE_HW_CALLOUT = 1,
EI_TYPE_PROCEDURE_CALLOUT = 2,
EI_TYPE_BUS_CALLOUT = 3,
EI_TYPE_CDG = 4, // Target Callout/Deconfig/GARD
EI_TYPE_CHILDREN_CDG = 5, // Children Callout/Deconfig/GARD
EI_TYPE_COLLECT_TRACE = 6,
EI_LAST_TYPE = EI_TYPE_COLLECT_TRACE + 1,
};
#ifndef MINIMUM_FFDC
///
/// @enum HwCallout
///
/// This enumeration defines the possible Hardware Callouts that are not
/// represented by fapi2::Targets
///
/// Note that platform code may depend on the enum values starting at 0 and
/// incrementing in order to efficiently convert to a platform callout value
/// so do not reorder without consulting all platforms
///
namespace HwCallouts
{
enum HwCallout
{
// Where indicated, a HW Callout in FAPI Error XML must include a
// reference target that is used to identify the HW. e.g. for
// TOD_CLOCK, the proc chip that the clock is attached to must be
// specified
TOD_CLOCK = 0, // Include proc-chip ref (or child chiplet)
MEM_REF_CLOCK = 1, // Include membuf-chip ref (or child chiplet)
PROC_REF_CLOCK = 2, // Include proc-chip ref (or child chiplet)
PCI_REF_CLOCK = 3, // Include proc-chip ref (or child chiplet)
FLASH_CONTROLLER_PART = 4,
PNOR_PART = 5,
SBE_SEEPROM_PART = 6,
VPD_PART = 7,
LPC_SLAVE_PART = 8,
GPIO_EXPANDER_PART = 9,
SPIVID_SLAVE_PART = 10,
};
}
///
/// @enum ProcedureCallout
///
/// This enumeration defines the possible Procedure Callouts
/// These instruct the customer/customer-engineer what to do
///
/// Note that platform code may depend on the enum values starting at 0 and
/// incrementing in order to efficiently convert to a platform callout value
/// so do not reorder without consulting all platforms
///
namespace ProcedureCallouts
{
enum ProcedureCallout
{
CODE = 0, // Code problem
LVL_SUPPORT = 1, // Call next level of support
MEMORY_PLUGGING_ERROR = 2, // DIMM Plugging error
BUS_CALLOUT = 3, // Bus Called Out
};
}
///
/// @enum CalloutPriority
///
/// This enumeration defines the possible Procedure and Target callout priorities
///
/// Note that platform code may depend on the enum values starting at 0 and
/// incrementing in order to efficiently convert to a platform priority value
/// so do not reorder without consulting all platforms
///
namespace CalloutPriorities
{
enum CalloutPriority
{
LOW = 0,
MEDIUM = 1,
HIGH = 2,
NONE = 3,
};
}
///
/// @enum CollectTrace
///
/// This enumeration defines the possible firmware traces to collect
///
namespace CollectTraces
{
const uint32_t TRACE_SIZE = 256; // limit collected trace size
enum CollectTrace
{
FSI = 1,
SCOM = 2,
SCAN = 3,
MBOX = 4,
};
}
// NOTE - this assumes no buffer_t or variable_buffers are passed
// data is converted to a uint64_t when placed into the sbe ffdc
// buffer
inline fapi2::ffdc_t getFfdcData( sbeFfdc_t& i_sbeFfdc )
{
fapi2::ffdc_t temp;
temp.size() = static_cast<size_t>(i_sbeFfdc.size);
if(temp.size() == EI_FFDC_SIZE_TARGET)
{
#ifdef FAPI2_ENABLE_PLATFORM_GET_TARGET
uint64_t targetData = i_sbeFfdc.data;
fapi2::TargetType type = static_cast<fapi2::TargetType>(targetData >> 32);
uint8_t instance = static_cast<uint8_t>(targetData & 0xFFFFFFFF);
// call hostboot to get the fapi2 target reference
temp.ptr() = static_cast<void*>(getTarget<TARGET_TYPE_ALL>(type, instance));
#endif
}
else
{
// adjust the pointer based on the data size.
temp.ptr() = static_cast<void*>(reinterpret_cast<uint8_t*>(&i_sbeFfdc.data) +
(sizeof(uint64_t) - i_sbeFfdc.size));
}
return temp;
}
#endif
///
/// @brief Get FFDC Size
///
/// This is called by the FAPI_SET_HWP_ERROR macro to find out the size of
/// FFDC data. If the data is of a special type that is handled differently
/// than types that are simply memcopied then it is handled by a template
/// specialization.
/// If this function template is instantiated with a pointer, the compile
/// will fail.
///
/// @return uint16_t. Size of the FFDC data
///
template<typename T>
inline uint16_t getErrorInfoFfdcSize(const T&)
{
static_assert(sizeof(T) <= EI_FFDC_MAX_SIZE,
"FFDC too large to capture");
return sizeof(T);
}
#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)
///
/// @brief Compile error if caller tries to get the FFDC size of a pointer
///
template<typename T>
inline uint16_t getErrorInfoFfdcSize(const T*)
{
static_assert(std::is_pointer<T>::value,
"pointer passed to getErrorInfoFfdcSize");
return 0;
}
#endif
///
/// @brief Get FFDC Size specialization for fapi2::Target
///
template<fapi2::TargetType T, typename V>
inline uint16_t getErrorInfoFfdcSize(const fapi2::Target<T, V>&)
{
return EI_FFDC_SIZE_TARGET;
}
#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)
///
/// @brief Get FFDC Size specialization for variable buffers
///
template<>
inline uint16_t getErrorInfoFfdcSize(const fapi2::variable_buffer& i_thing)
{
// Limit a variable buffer to 4kb bytes, and we can memcpy the storage.
return std::min(static_cast<uint32_t>(EI_FFDC_MAX_SIZE),
i_thing.getLength<uint8_t>());
}
#endif
///
/// @brief Get FFDC Size specialization for ffdc_t
///
template<>
inline uint16_t getErrorInfoFfdcSize(const fapi2::ffdc_t& i_ffdc)
{
return static_cast<uint16_t>(i_ffdc.size());
}
};
#endif // FAPI2_ERRORINFO_DEFS_H_
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.