text
stringlengths
54
60.6k
<commit_before>#include "SkBitmapProcShader.h" #include "SkColorPriv.h" #include "SkPixelRef.h" bool SkBitmapProcShader::CanDo(const SkBitmap& bm, TileMode tx, TileMode ty) { switch (bm.config()) { case SkBitmap::kA8_Config: case SkBitmap::kRGB_565_Config: case SkBitmap::kIndex8_Config: case SkBitmap::kARGB_8888_Config: // if (tx == ty && (kClamp_TileMode == tx || kRepeat_TileMode == tx)) return true; default: break; } return false; } SkBitmapProcShader::SkBitmapProcShader(const SkBitmap& src, TileMode tmx, TileMode tmy) { fRawBitmap = src; fState.fTileModeX = (uint8_t)tmx; fState.fTileModeY = (uint8_t)tmy; fFlags = 0; // computed in setContext } SkBitmapProcShader::SkBitmapProcShader(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) { fRawBitmap.unflatten(buffer); fState.fTileModeX = buffer.readU8(); fState.fTileModeY = buffer.readU8(); fFlags = 0; // computed in setContext } void SkBitmapProcShader::beginSession() { this->INHERITED::beginSession(); fRawBitmap.lockPixels(); } void SkBitmapProcShader::endSession() { fRawBitmap.unlockPixels(); this->INHERITED::endSession(); } bool SkBitmapProcShader::asABitmap(SkBitmap* texture, SkMatrix* texM, TileMode xy[]) { if (texture) { *texture = fRawBitmap; } if (texM) { texM->reset(); } if (xy) { xy[0] = (TileMode)fState.fTileModeX; xy[1] = (TileMode)fState.fTileModeY; } return true; } void SkBitmapProcShader::flatten(SkFlattenableWriteBuffer& buffer) { this->INHERITED::flatten(buffer); fRawBitmap.flatten(buffer); buffer.write8(fState.fTileModeX); buffer.write8(fState.fTileModeY); } static bool only_scale_and_translate(const SkMatrix& matrix) { unsigned mask = SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask; return (matrix.getType() & ~mask) == 0; } bool SkBitmapProcShader::setContext(const SkBitmap& device, const SkPaint& paint, const SkMatrix& matrix) { // do this first, so we have a correct inverse matrix if (!this->INHERITED::setContext(device, paint, matrix)) { return false; } fState.fOrigBitmap = fRawBitmap; fState.fOrigBitmap.lockPixels(); if (fState.fOrigBitmap.getPixels() == NULL) { fState.fOrigBitmap.unlockPixels(); return false; } if (!fState.chooseProcs(this->getTotalInverse(), paint)) { return false; } bool bitmapIsOpaque = fState.fBitmap->isOpaque(); // filtering doesn't guarantee that opaque stays opaque (finite precision) // so pretend we're not opaque if we're being asked to filter. If we had // more blit-procs, we could specialize on opaque src, and just OR in 0xFF // after the filter to be sure... if (paint.isFilterBitmap()) { bitmapIsOpaque = false; } // update fFlags uint32_t flags = 0; if (bitmapIsOpaque && (255 == this->getPaintAlpha())) { flags |= kOpaqueAlpha_Flag; } switch (fState.fBitmap->config()) { case SkBitmap::kRGB_565_Config: flags |= (kHasSpan16_Flag | kIntrinsicly16_Flag); break; case SkBitmap::kIndex8_Config: case SkBitmap::kARGB_8888_Config: if (bitmapIsOpaque) { flags |= kHasSpan16_Flag; } break; case SkBitmap::kA8_Config: break; // never set kHasSpan16_Flag default: break; } if (paint.isDither()) { // gradients can auto-dither in their 16bit sampler, but we don't so // we clear the flag here flags &= ~kHasSpan16_Flag; } // if we're only 1-pixel heigh, and we don't rotate, then we can claim this if (1 == fState.fBitmap->height() && only_scale_and_translate(this->getTotalInverse())) { flags |= kConstInY32_Flag; if (flags & kHasSpan16_Flag) { flags |= kConstInY16_Flag; } } fFlags = flags; return true; } #define BUF_MAX 128 void SkBitmapProcShader::shadeSpan(int x, int y, SkPMColor dstC[], int count) { const SkBitmapProcState& state = fState; if (state.fShaderProc32) { state.fShaderProc32(state, x, y, dstC, count); return; } uint32_t buffer[BUF_MAX]; SkBitmapProcState::MatrixProc mproc = state.fMatrixProc; SkBitmapProcState::SampleProc32 sproc = state.fSampleProc32; int max = fState.maxCountForBufferSize(sizeof(buffer)); SkASSERT(state.fBitmap->getPixels()); SkASSERT(state.fBitmap->pixelRef() == NULL || state.fBitmap->pixelRef()->getLockCount()); for (;;) { int n = count; if (n > max) { n = max; } mproc(state, buffer, n, x, y); sproc(state, buffer, n, dstC); if ((count -= n) == 0) { break; } x += n; dstC += n; } } void SkBitmapProcShader::shadeSpan16(int x, int y, uint16_t dstC[], int count) { const SkBitmapProcState& state = fState; if (state.fShaderProc16) { state.fShaderProc16(state, x, y, dstC, count); return; } uint32_t buffer[BUF_MAX]; SkBitmapProcState::MatrixProc mproc = state.fMatrixProc; SkBitmapProcState::SampleProc16 sproc = state.fSampleProc16; int max = fState.maxCountForBufferSize(sizeof(buffer)); SkASSERT(state.fBitmap->getPixels()); SkASSERT(state.fBitmap->pixelRef() == NULL || state.fBitmap->pixelRef()->getLockCount()); for (;;) { int n = count; if (n > max) { n = max; } mproc(state, buffer, n, x, y); sproc(state, buffer, n, dstC); if ((count -= n) == 0) { break; } x += n; dstC += n; } } /////////////////////////////////////////////////////////////////////////////// #include "SkUnPreMultiply.h" #include "SkColorShader.h" // returns true and set color if the bitmap can be drawn as a single color // (for efficiency) static bool canUseColorShader(const SkBitmap& bm, SkColor* color) { if (1 != bm.width() || 1 != bm.height()) { return false; } SkAutoLockPixels alp(bm); if (!bm.readyToDraw()) { return false; } switch (bm.config()) { case SkBitmap::kARGB_8888_Config: *color = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(0, 0)); return true; case SkBitmap::kRGB_565_Config: *color = SkPixel16ToColor(*bm.getAddr16(0, 0)); return true; case SkBitmap::kIndex8_Config: *color = SkUnPreMultiply::PMColorToColor(bm.getIndex8Color(0, 0)); return true; default: // just skip the other configs for now break; } return false; } #include "SkTemplatesPriv.h" SkShader* SkShader::CreateBitmapShader(const SkBitmap& src, TileMode tmx, TileMode tmy, void* storage, size_t storageSize) { SkShader* shader; SkColor color; if (canUseColorShader(src, &color)) { SK_PLACEMENT_NEW_ARGS(shader, SkColorShader, storage, storageSize, (color)); } else { SK_PLACEMENT_NEW_ARGS(shader, SkBitmapProcShader, storage, storageSize, (src, tmx, tmy)); } return shader; } static SkFlattenable::Registrar gBitmapProcShaderReg("SkBitmapProcShader", SkBitmapProcShader::CreateProc); /////////////////////////////////////////////////////////////////////////////// static const char* gTileModeName[] = { "clamp", "repeat", "mirror" }; bool SkBitmapProcShader::toDumpString(SkString* str) const { str->printf("BitmapShader: [%d %d %d", fRawBitmap.width(), fRawBitmap.height(), fRawBitmap.bytesPerPixel()); // add the pixelref SkPixelRef* pr = fRawBitmap.pixelRef(); if (pr) { const char* uri = pr->getURI(); if (uri) { str->appendf(" \"%s\"", uri); } } // add the (optional) matrix { SkMatrix m; if (this->getLocalMatrix(&m)) { SkString info; m.toDumpString(&info); str->appendf(" %s", info.c_str()); } } str->appendf(" [%s %s]]", gTileModeName[fState.fTileModeX], gTileModeName[fState.fTileModeY]); return true; } <commit_msg>don't force bitmapIsOpaque to false if we're instrinsically 16bit<commit_after>#include "SkBitmapProcShader.h" #include "SkColorPriv.h" #include "SkPixelRef.h" bool SkBitmapProcShader::CanDo(const SkBitmap& bm, TileMode tx, TileMode ty) { switch (bm.config()) { case SkBitmap::kA8_Config: case SkBitmap::kRGB_565_Config: case SkBitmap::kIndex8_Config: case SkBitmap::kARGB_8888_Config: // if (tx == ty && (kClamp_TileMode == tx || kRepeat_TileMode == tx)) return true; default: break; } return false; } SkBitmapProcShader::SkBitmapProcShader(const SkBitmap& src, TileMode tmx, TileMode tmy) { fRawBitmap = src; fState.fTileModeX = (uint8_t)tmx; fState.fTileModeY = (uint8_t)tmy; fFlags = 0; // computed in setContext } SkBitmapProcShader::SkBitmapProcShader(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) { fRawBitmap.unflatten(buffer); fState.fTileModeX = buffer.readU8(); fState.fTileModeY = buffer.readU8(); fFlags = 0; // computed in setContext } void SkBitmapProcShader::beginSession() { this->INHERITED::beginSession(); fRawBitmap.lockPixels(); } void SkBitmapProcShader::endSession() { fRawBitmap.unlockPixels(); this->INHERITED::endSession(); } bool SkBitmapProcShader::asABitmap(SkBitmap* texture, SkMatrix* texM, TileMode xy[]) { if (texture) { *texture = fRawBitmap; } if (texM) { texM->reset(); } if (xy) { xy[0] = (TileMode)fState.fTileModeX; xy[1] = (TileMode)fState.fTileModeY; } return true; } void SkBitmapProcShader::flatten(SkFlattenableWriteBuffer& buffer) { this->INHERITED::flatten(buffer); fRawBitmap.flatten(buffer); buffer.write8(fState.fTileModeX); buffer.write8(fState.fTileModeY); } static bool only_scale_and_translate(const SkMatrix& matrix) { unsigned mask = SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask; return (matrix.getType() & ~mask) == 0; } // return true if the config can possibly have per-pixel alpha, ignoring the // current setting of isOpaque. static bool canSupportPerPixelAlpha(const SkBitmap& bm) { // return true unless we're guaranteed to be opaque return bm.config() != SkBitmap::kRGB_565_Config; } bool SkBitmapProcShader::setContext(const SkBitmap& device, const SkPaint& paint, const SkMatrix& matrix) { // do this first, so we have a correct inverse matrix if (!this->INHERITED::setContext(device, paint, matrix)) { return false; } fState.fOrigBitmap = fRawBitmap; fState.fOrigBitmap.lockPixels(); if (fState.fOrigBitmap.getPixels() == NULL) { fState.fOrigBitmap.unlockPixels(); return false; } if (!fState.chooseProcs(this->getTotalInverse(), paint)) { return false; } const SkBitmap& bitmap = *fState.fBitmap; bool bitmapIsOpaque = bitmap.isOpaque(); // filtering doesn't guarantee that opaque stays opaque (finite precision) // so pretend we're not opaque if we're being asked to filter. If we had // more blit-procs, we could specialize on opaque src, and just OR in 0xFF // after the filter to be sure... /* (some time later) Adding check for canSupportPerPixelAlpha, since bitmaps that are 565 (for example) will *always* be opaque, even after filtering. Would be really nice to never do this, if we could ensure that filtering didn't introduct non-opaqueness accidentally. */ if (paint.isFilterBitmap() && canSupportPerPixelAlpha(bitmap)) { bitmapIsOpaque = false; } // update fFlags uint32_t flags = 0; if (bitmapIsOpaque && (255 == this->getPaintAlpha())) { flags |= kOpaqueAlpha_Flag; } switch (bitmap.config()) { case SkBitmap::kRGB_565_Config: flags |= (kHasSpan16_Flag | kIntrinsicly16_Flag); break; case SkBitmap::kIndex8_Config: case SkBitmap::kARGB_8888_Config: if (bitmapIsOpaque) { flags |= kHasSpan16_Flag; } break; case SkBitmap::kA8_Config: break; // never set kHasSpan16_Flag default: break; } if (paint.isDither() && bitmap.config() != SkBitmap::kRGB_565_Config) { // gradients can auto-dither in their 16bit sampler, but we don't so // we clear the flag here. flags &= ~kHasSpan16_Flag; } // if we're only 1-pixel heigh, and we don't rotate, then we can claim this if (1 == bitmap.height() && only_scale_and_translate(this->getTotalInverse())) { flags |= kConstInY32_Flag; if (flags & kHasSpan16_Flag) { flags |= kConstInY16_Flag; } } fFlags = flags; return true; } #define BUF_MAX 128 void SkBitmapProcShader::shadeSpan(int x, int y, SkPMColor dstC[], int count) { const SkBitmapProcState& state = fState; if (state.fShaderProc32) { state.fShaderProc32(state, x, y, dstC, count); return; } uint32_t buffer[BUF_MAX]; SkBitmapProcState::MatrixProc mproc = state.fMatrixProc; SkBitmapProcState::SampleProc32 sproc = state.fSampleProc32; int max = fState.maxCountForBufferSize(sizeof(buffer)); SkASSERT(state.fBitmap->getPixels()); SkASSERT(state.fBitmap->pixelRef() == NULL || state.fBitmap->pixelRef()->getLockCount()); for (;;) { int n = count; if (n > max) { n = max; } mproc(state, buffer, n, x, y); sproc(state, buffer, n, dstC); if ((count -= n) == 0) { break; } x += n; dstC += n; } } void SkBitmapProcShader::shadeSpan16(int x, int y, uint16_t dstC[], int count) { const SkBitmapProcState& state = fState; if (state.fShaderProc16) { state.fShaderProc16(state, x, y, dstC, count); return; } uint32_t buffer[BUF_MAX]; SkBitmapProcState::MatrixProc mproc = state.fMatrixProc; SkBitmapProcState::SampleProc16 sproc = state.fSampleProc16; int max = fState.maxCountForBufferSize(sizeof(buffer)); SkASSERT(state.fBitmap->getPixels()); SkASSERT(state.fBitmap->pixelRef() == NULL || state.fBitmap->pixelRef()->getLockCount()); for (;;) { int n = count; if (n > max) { n = max; } mproc(state, buffer, n, x, y); sproc(state, buffer, n, dstC); if ((count -= n) == 0) { break; } x += n; dstC += n; } } /////////////////////////////////////////////////////////////////////////////// #include "SkUnPreMultiply.h" #include "SkColorShader.h" // returns true and set color if the bitmap can be drawn as a single color // (for efficiency) static bool canUseColorShader(const SkBitmap& bm, SkColor* color) { if (1 != bm.width() || 1 != bm.height()) { return false; } SkAutoLockPixels alp(bm); if (!bm.readyToDraw()) { return false; } switch (bm.config()) { case SkBitmap::kARGB_8888_Config: *color = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(0, 0)); return true; case SkBitmap::kRGB_565_Config: *color = SkPixel16ToColor(*bm.getAddr16(0, 0)); return true; case SkBitmap::kIndex8_Config: *color = SkUnPreMultiply::PMColorToColor(bm.getIndex8Color(0, 0)); return true; default: // just skip the other configs for now break; } return false; } #include "SkTemplatesPriv.h" SkShader* SkShader::CreateBitmapShader(const SkBitmap& src, TileMode tmx, TileMode tmy, void* storage, size_t storageSize) { SkShader* shader; SkColor color; if (canUseColorShader(src, &color)) { SK_PLACEMENT_NEW_ARGS(shader, SkColorShader, storage, storageSize, (color)); } else { SK_PLACEMENT_NEW_ARGS(shader, SkBitmapProcShader, storage, storageSize, (src, tmx, tmy)); } return shader; } static SkFlattenable::Registrar gBitmapProcShaderReg("SkBitmapProcShader", SkBitmapProcShader::CreateProc); /////////////////////////////////////////////////////////////////////////////// static const char* gTileModeName[] = { "clamp", "repeat", "mirror" }; bool SkBitmapProcShader::toDumpString(SkString* str) const { str->printf("BitmapShader: [%d %d %d", fRawBitmap.width(), fRawBitmap.height(), fRawBitmap.bytesPerPixel()); // add the pixelref SkPixelRef* pr = fRawBitmap.pixelRef(); if (pr) { const char* uri = pr->getURI(); if (uri) { str->appendf(" \"%s\"", uri); } } // add the (optional) matrix { SkMatrix m; if (this->getLocalMatrix(&m)) { SkString info; m.toDumpString(&info); str->appendf(" %s", info.c_str()); } } str->appendf(" [%s %s]]", gTileModeName[fState.fTileModeX], gTileModeName[fState.fTileModeY]); return true; } <|endoftext|>
<commit_before>/* CSCI 480 Assignment 3 Raytracer Name: Brandon Barber */ #include <stdlib.h> #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/glut.h> #include <pic.h> #include <string.h> #include <cmath> #include <iostream> using namespace std; #define MAX_TRIANGLES 2000 #define MAX_SPHERES 10 #define MAX_LIGHTS 10 #define PI 3.14159265 char *filename=0; //different display modes #define MODE_DISPLAY 1 #define MODE_JPEG 2 int mode=MODE_DISPLAY; //you may want to make these smaller for debugging purposes #define WIDTH 160 #define HEIGHT 120 //the field of view of the camera #define fov 60.0 unsigned char buffer[HEIGHT][WIDTH][3]; struct Vertex { double position[3]; double color_diffuse[3]; double color_specular[3]; double normal[3]; double shininess; }; typedef struct _Triangle { struct Vertex v[3]; } Triangle; typedef struct _Sphere { double position[3]; double color_diffuse[3]; double color_specular[3]; double shininess; double radius; } Sphere; typedef struct _Light { double position[3]; double color[3]; } Light; Triangle triangles[MAX_TRIANGLES]; Sphere spheres[MAX_SPHERES]; Light lights[MAX_LIGHTS]; double ambient_light[3]; int num_triangles=0; int num_spheres=0; int num_lights=0; void plot_pixel_display(int x,int y,unsigned char r,unsigned char g,unsigned char b); void plot_pixel_jpeg(int x,int y,unsigned char r,unsigned char g,unsigned char b); void plot_pixel(int x,int y,unsigned char r,unsigned char g,unsigned char b); Vertex subtract(Vertex v1, Vertex v2) { Vertex toReturn; for(int i = 0; i <= 2; i++) { toReturn.position[i] = v1.position[i] - v2.position[i]; } return toReturn; } Vertex cross(Vertex v1, Vertex v2) { Vertex toReturn; toReturn.position[0] = v1.position[1] * v2.position[2] - v1.position[2] * v2.position[1]; toReturn.position[1] = v1.position[2] * v2.position[0] - v1.position[0] * v2.position[2]; toReturn.position[2] = v1.position[0] * v2.position[1] - v1.position[1] * v2.position[0]; return toReturn; } double dot(Vertex v1, Vertex v2) { return v1.position[0] * v2.position[0] + v1.position[1] * v2.position[1] + v1.position[2] * v2.position[2]; } Vertex scale(Vertex v, double scaleFactor) { Vertex toReturn; toReturn.position[0] *= scaleFactor; toReturn.position[1] *= scaleFactor; toReturn.position[2] *= scaleFactor; return toReturn; } double magnitude(Vertex v) { return sqrt(v.position[0]*v.position[0] + v.position[1]*v.position[1] + v.position[2]*v.position[2]); } Vertex normalize(Vertex v) { Vertex toReturn; double mag = magnitude(v); toReturn.position[0] = v.position[0] / mag; toReturn.position[1] = v.position[1] / mag; toReturn.position[2] = v.position[2] / mag; return toReturn; } //MODIFY THIS FUNCTION void draw_scene() { //generate rays float ar = 1.0f*WIDTH/HEIGHT; float tanVal = tan(fov/2.0 * PI / 180.0); for(int x = 0; x < WIDTH; x++) { for(int y = 0; y < HEIGHT; y++) { float rayX = 2 * ar * tanVal * x / (1.0*WIDTH - 1) - ar * tanVal; float rayY = 2 * tanVal * y / (1.0*HEIGHT - 1) - tanVal; float rayZ = -1; float d = sqrt(rayX * rayX + rayY * rayY + rayZ * rayZ); rayX /= d; rayY /= d; rayZ /= d; float t = 0; for(int triangleIndex = 0; triangleIndex < num_triangles; triangleIndex++) { Triangle triangle = triangles[triangleIndex]; Vertex planeNormal = cross(subtract(triangle.v[1],triangle.v[0]),subtract(triangle.v[2],triangle.v[0])); planeNormal = normalize(planeNormal); Vertex zeroVector; zeroVector.position[0] = 0; zeroVector.position[1] = 0; zeroVector.position[2] = 0; Vertex rayVector; rayVector.position[0] = rayX; rayVector.position[1] = rayY; rayVector.position[2] = rayZ; double t_Triangle = -1 * dot(subtract(zeroVector,triangle.v[0]),planeNormal) / dot(rayVector, planeNormal); if(t_Triangle <= 0) { continue; } rayVector = scale(rayVector,t_Triangle); double area = .5 * magnitude(cross(subtract(triangle.v[1],triangle.v[0]),subtract(triangle.v[2],triangle.v[0]))); double alpha = magnitude(cross(subtract(triangle.v[1],rayVector),subtract(triangle.v[2],rayVector))) * .5 / area; double beta = magnitude(cross(subtract(triangle.v[0],rayVector),subtract(triangle.v[2],rayVector))) * .5 / area; double gamma = magnitude(cross(subtract(triangle.v[0],rayVector),subtract(triangle.v[1],rayVector))) * .5 / area; if(alpha >= 0 && alpha <= 1 && beta >= 0 && beta <= 1 && gamma >= 0 && gamma <= 1) { t = t_Triangle; } } for(int sphereIndex = 0;sphereIndex < num_spheres; sphereIndex++) { Sphere sphere = spheres[sphereIndex]; float a = 1; float b = 2 * (rayX * (-sphere.position[0]) + rayY * (-sphere.position[1]) + rayZ * (-sphere.position[2])); float c = sphere.position[0]*sphere.position[0] + sphere.position[1]*sphere.position[1] + sphere.position[2]*sphere.position[2] - sphere.radius * sphere.radius; float discriminant = b * b - 4 * a * c; if(discriminant < 0) { continue; } float t_0 = (-b + sqrt(discriminant))/2; float t_1 = (-b - sqrt(discriminant))/2; float sphere_t = 0; if(t_0 > 0 && t_1 > 0) { sphere_t = min(t_0,t_1); } else if(t_0 > 0) { sphere_t = t_0; } else if(t_1 > 0) { sphere_t = t_1; } else { continue; } if(sphere_t > 0) { if(t > 0) { t = min(sphere_t,t); } else { t = sphere_t; } } } if(t > 0) { glPointSize(2.0); glBegin(GL_POINTS); plot_pixel(x,y,255,255,255); glEnd(); glFlush(); } else { glPointSize(2.0); glBegin(GL_POINTS); plot_pixel(x,y,0,0,0); glEnd(); glFlush(); } } } printf("Done!\n"); fflush(stdout); } void plot_pixel_display(int x,int y,unsigned char r,unsigned char g,unsigned char b) { glColor3f(((double)r)/256.f,((double)g)/256.f,((double)b)/256.f); glVertex2i(x,y); } void plot_pixel_jpeg(int x,int y,unsigned char r,unsigned char g,unsigned char b) { buffer[HEIGHT-y-1][x][0]=r; buffer[HEIGHT-y-1][x][1]=g; buffer[HEIGHT-y-1][x][2]=b; } void plot_pixel(int x,int y,unsigned char r,unsigned char g, unsigned char b) { plot_pixel_display(x,y,r,g,b); if(mode == MODE_JPEG) plot_pixel_jpeg(x,y,r,g,b); } void save_jpg() { Pic *in = NULL; in = pic_alloc(WIDTH, HEIGHT, 3, NULL); printf("Saving JPEG file: %s\n", filename); memcpy(in->pix,buffer,3*WIDTH*HEIGHT); if (jpeg_write(filename, in)) printf("File saved Successfully\n"); else printf("Error in Saving\n"); pic_free(in); } void parse_check(char *expected,char *found) { if(strcasecmp(expected,found)) { char error[100]; printf("Expected '%s ' found '%s '\n",expected,found); printf("Parse error, abnormal abortion\n"); exit(0); } } void parse_doubles(FILE*file, char *check, double p[3]) { char str[100]; fscanf(file,"%s",str); parse_check(check,str); fscanf(file,"%lf %lf %lf",&p[0],&p[1],&p[2]); printf("%s %lf %lf %lf\n",check,p[0],p[1],p[2]); } void parse_rad(FILE*file,double *r) { char str[100]; fscanf(file,"%s",str); parse_check("rad:",str); fscanf(file,"%lf",r); printf("rad: %f\n",*r); } void parse_shi(FILE*file,double *shi) { char s[100]; fscanf(file,"%s",s); parse_check("shi:",s); fscanf(file,"%lf",shi); printf("shi: %f\n",*shi); } int loadScene(char *argv) { FILE *file = fopen(argv,"r"); int number_of_objects; char type[50]; int i; Triangle t; Sphere s; Light l; fscanf(file,"%i",&number_of_objects); printf("number of objects: %i\n",number_of_objects); char str[200]; parse_doubles(file,"amb:",ambient_light); for(i=0;i < number_of_objects;i++) { fscanf(file,"%s\n",type); printf("%s\n",type); if(strcasecmp(type,"triangle")==0) { printf("found triangle\n"); int j; for(j=0;j < 3;j++) { parse_doubles(file,"pos:",t.v[j].position); parse_doubles(file,"nor:",t.v[j].normal); parse_doubles(file,"dif:",t.v[j].color_diffuse); parse_doubles(file,"spe:",t.v[j].color_specular); parse_shi(file,&t.v[j].shininess); } if(num_triangles == MAX_TRIANGLES) { printf("too many triangles, you should increase MAX_TRIANGLES!\n"); exit(0); } triangles[num_triangles++] = t; } else if(strcasecmp(type,"sphere")==0) { printf("found sphere\n"); parse_doubles(file,"pos:",s.position); parse_rad(file,&s.radius); parse_doubles(file,"dif:",s.color_diffuse); parse_doubles(file,"spe:",s.color_specular); parse_shi(file,&s.shininess); if(num_spheres == MAX_SPHERES) { printf("too many spheres, you should increase MAX_SPHERES!\n"); exit(0); } spheres[num_spheres++] = s; } else if(strcasecmp(type,"light")==0) { printf("found light\n"); parse_doubles(file,"pos:",l.position); parse_doubles(file,"col:",l.color); if(num_lights == MAX_LIGHTS) { printf("too many lights, you should increase MAX_LIGHTS!\n"); exit(0); } lights[num_lights++] = l; } else { printf("unknown type in scene description:\n%s\n",type); exit(0); } } return 0; } void display() { } void init() { glMatrixMode(GL_PROJECTION); glOrtho(0,WIDTH,0,HEIGHT,1,-1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClearColor(0,0,0,0); glClear(GL_COLOR_BUFFER_BIT); } void idle() { //hack to make it only draw once static int once=0; if(!once) { draw_scene(); if(mode == MODE_JPEG) save_jpg(); } once=1; } int main (int argc, char ** argv) { if (argc<2 || argc > 3) { printf ("usage: %s <scenefile> [jpegname]\n", argv[0]); exit(0); } if(argc == 3) { mode = MODE_JPEG; filename = argv[2]; } else if(argc == 2) mode = MODE_DISPLAY; glutInit(&argc,argv); loadScene(argv[1]); glutInitDisplayMode(GLUT_RGBA | GLUT_SINGLE); glutInitWindowPosition(0,0); glutInitWindowSize(WIDTH,HEIGHT); int window = glutCreateWindow("Ray Tracer"); glutDisplayFunc(display); glutIdleFunc(idle); init(); glutMainLoop(); } <commit_msg>Added two little comments. close #2<commit_after>/* CSCI 480 Assignment 3 Raytracer Name: Brandon Barber */ #include <stdlib.h> #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/glut.h> #include <pic.h> #include <string.h> #include <cmath> #include <iostream> using namespace std; #define MAX_TRIANGLES 2000 #define MAX_SPHERES 10 #define MAX_LIGHTS 10 #define PI 3.14159265 char *filename=0; //different display modes #define MODE_DISPLAY 1 #define MODE_JPEG 2 int mode=MODE_DISPLAY; //you may want to make these smaller for debugging purposes #define WIDTH 160 #define HEIGHT 120 //the field of view of the camera #define fov 60.0 unsigned char buffer[HEIGHT][WIDTH][3]; struct Vertex { double position[3]; double color_diffuse[3]; double color_specular[3]; double normal[3]; double shininess; }; typedef struct _Triangle { struct Vertex v[3]; } Triangle; typedef struct _Sphere { double position[3]; double color_diffuse[3]; double color_specular[3]; double shininess; double radius; } Sphere; typedef struct _Light { double position[3]; double color[3]; } Light; Triangle triangles[MAX_TRIANGLES]; Sphere spheres[MAX_SPHERES]; Light lights[MAX_LIGHTS]; double ambient_light[3]; int num_triangles=0; int num_spheres=0; int num_lights=0; void plot_pixel_display(int x,int y,unsigned char r,unsigned char g,unsigned char b); void plot_pixel_jpeg(int x,int y,unsigned char r,unsigned char g,unsigned char b); void plot_pixel(int x,int y,unsigned char r,unsigned char g,unsigned char b); Vertex subtract(Vertex v1, Vertex v2) { Vertex toReturn; for(int i = 0; i <= 2; i++) { toReturn.position[i] = v1.position[i] - v2.position[i]; } return toReturn; } Vertex cross(Vertex v1, Vertex v2) { Vertex toReturn; toReturn.position[0] = v1.position[1] * v2.position[2] - v1.position[2] * v2.position[1]; toReturn.position[1] = v1.position[2] * v2.position[0] - v1.position[0] * v2.position[2]; toReturn.position[2] = v1.position[0] * v2.position[1] - v1.position[1] * v2.position[0]; return toReturn; } double dot(Vertex v1, Vertex v2) { return v1.position[0] * v2.position[0] + v1.position[1] * v2.position[1] + v1.position[2] * v2.position[2]; } Vertex scale(Vertex v, double scaleFactor) { Vertex toReturn; toReturn.position[0] *= scaleFactor; toReturn.position[1] *= scaleFactor; toReturn.position[2] *= scaleFactor; return toReturn; } double magnitude(Vertex v) { return sqrt(v.position[0]*v.position[0] + v.position[1]*v.position[1] + v.position[2]*v.position[2]); } Vertex normalize(Vertex v) { Vertex toReturn; double mag = magnitude(v); toReturn.position[0] = v.position[0] / mag; toReturn.position[1] = v.position[1] / mag; toReturn.position[2] = v.position[2] / mag; return toReturn; } //MODIFY THIS FUNCTION void draw_scene() { //generate rays float ar = 1.0f*WIDTH/HEIGHT; float tanVal = tan(fov/2.0 * PI / 180.0); for(int x = 0; x < WIDTH; x++) { for(int y = 0; y < HEIGHT; y++) { float rayX = 2 * ar * tanVal * x / (1.0*WIDTH - 1) - ar * tanVal; float rayY = 2 * tanVal * y / (1.0*HEIGHT - 1) - tanVal; float rayZ = -1; float d = sqrt(rayX * rayX + rayY * rayY + rayZ * rayZ); rayX /= d; rayY /= d; rayZ /= d; float t = 0; //Iterate through triangles for(int triangleIndex = 0; triangleIndex < num_triangles; triangleIndex++) { Triangle triangle = triangles[triangleIndex]; Vertex planeNormal = cross(subtract(triangle.v[1],triangle.v[0]),subtract(triangle.v[2],triangle.v[0])); planeNormal = normalize(planeNormal); Vertex zeroVector; zeroVector.position[0] = 0; zeroVector.position[1] = 0; zeroVector.position[2] = 0; Vertex rayVector; rayVector.position[0] = rayX; rayVector.position[1] = rayY; rayVector.position[2] = rayZ; double t_Triangle = -1 * dot(subtract(zeroVector,triangle.v[0]),planeNormal) / dot(rayVector, planeNormal); if(t_Triangle <= 0) { continue; } rayVector = scale(rayVector,t_Triangle); double area = .5 * magnitude(cross(subtract(triangle.v[1],triangle.v[0]),subtract(triangle.v[2],triangle.v[0]))); double alpha = magnitude(cross(subtract(triangle.v[1],rayVector),subtract(triangle.v[2],rayVector))) * .5 / area; double beta = magnitude(cross(subtract(triangle.v[0],rayVector),subtract(triangle.v[2],rayVector))) * .5 / area; double gamma = magnitude(cross(subtract(triangle.v[0],rayVector),subtract(triangle.v[1],rayVector))) * .5 / area; if(alpha >= 0 && alpha <= 1 && beta >= 0 && beta <= 1 && gamma >= 0 && gamma <= 1) { t = t_Triangle; } } //Iterate through spheres for(int sphereIndex = 0;sphereIndex < num_spheres; sphereIndex++) { Sphere sphere = spheres[sphereIndex]; float a = 1; float b = 2 * (rayX * (-sphere.position[0]) + rayY * (-sphere.position[1]) + rayZ * (-sphere.position[2])); float c = sphere.position[0]*sphere.position[0] + sphere.position[1]*sphere.position[1] + sphere.position[2]*sphere.position[2] - sphere.radius * sphere.radius; float discriminant = b * b - 4 * a * c; if(discriminant < 0) { continue; } float t_0 = (-b + sqrt(discriminant))/2; float t_1 = (-b - sqrt(discriminant))/2; float sphere_t = 0; if(t_0 > 0 && t_1 > 0) { sphere_t = min(t_0,t_1); } else if(t_0 > 0) { sphere_t = t_0; } else if(t_1 > 0) { sphere_t = t_1; } else { continue; } if(sphere_t > 0) { if(t > 0) { t = min(sphere_t,t); } else { t = sphere_t; } } } if(t > 0) { glPointSize(2.0); glBegin(GL_POINTS); plot_pixel(x,y,255,255,255); glEnd(); glFlush(); } else { glPointSize(2.0); glBegin(GL_POINTS); plot_pixel(x,y,0,0,0); glEnd(); glFlush(); } } } printf("Done!\n"); fflush(stdout); } void plot_pixel_display(int x,int y,unsigned char r,unsigned char g,unsigned char b) { glColor3f(((double)r)/256.f,((double)g)/256.f,((double)b)/256.f); glVertex2i(x,y); } void plot_pixel_jpeg(int x,int y,unsigned char r,unsigned char g,unsigned char b) { buffer[HEIGHT-y-1][x][0]=r; buffer[HEIGHT-y-1][x][1]=g; buffer[HEIGHT-y-1][x][2]=b; } void plot_pixel(int x,int y,unsigned char r,unsigned char g, unsigned char b) { plot_pixel_display(x,y,r,g,b); if(mode == MODE_JPEG) plot_pixel_jpeg(x,y,r,g,b); } void save_jpg() { Pic *in = NULL; in = pic_alloc(WIDTH, HEIGHT, 3, NULL); printf("Saving JPEG file: %s\n", filename); memcpy(in->pix,buffer,3*WIDTH*HEIGHT); if (jpeg_write(filename, in)) printf("File saved Successfully\n"); else printf("Error in Saving\n"); pic_free(in); } void parse_check(char *expected,char *found) { if(strcasecmp(expected,found)) { char error[100]; printf("Expected '%s ' found '%s '\n",expected,found); printf("Parse error, abnormal abortion\n"); exit(0); } } void parse_doubles(FILE*file, char *check, double p[3]) { char str[100]; fscanf(file,"%s",str); parse_check(check,str); fscanf(file,"%lf %lf %lf",&p[0],&p[1],&p[2]); printf("%s %lf %lf %lf\n",check,p[0],p[1],p[2]); } void parse_rad(FILE*file,double *r) { char str[100]; fscanf(file,"%s",str); parse_check("rad:",str); fscanf(file,"%lf",r); printf("rad: %f\n",*r); } void parse_shi(FILE*file,double *shi) { char s[100]; fscanf(file,"%s",s); parse_check("shi:",s); fscanf(file,"%lf",shi); printf("shi: %f\n",*shi); } int loadScene(char *argv) { FILE *file = fopen(argv,"r"); int number_of_objects; char type[50]; int i; Triangle t; Sphere s; Light l; fscanf(file,"%i",&number_of_objects); printf("number of objects: %i\n",number_of_objects); char str[200]; parse_doubles(file,"amb:",ambient_light); for(i=0;i < number_of_objects;i++) { fscanf(file,"%s\n",type); printf("%s\n",type); if(strcasecmp(type,"triangle")==0) { printf("found triangle\n"); int j; for(j=0;j < 3;j++) { parse_doubles(file,"pos:",t.v[j].position); parse_doubles(file,"nor:",t.v[j].normal); parse_doubles(file,"dif:",t.v[j].color_diffuse); parse_doubles(file,"spe:",t.v[j].color_specular); parse_shi(file,&t.v[j].shininess); } if(num_triangles == MAX_TRIANGLES) { printf("too many triangles, you should increase MAX_TRIANGLES!\n"); exit(0); } triangles[num_triangles++] = t; } else if(strcasecmp(type,"sphere")==0) { printf("found sphere\n"); parse_doubles(file,"pos:",s.position); parse_rad(file,&s.radius); parse_doubles(file,"dif:",s.color_diffuse); parse_doubles(file,"spe:",s.color_specular); parse_shi(file,&s.shininess); if(num_spheres == MAX_SPHERES) { printf("too many spheres, you should increase MAX_SPHERES!\n"); exit(0); } spheres[num_spheres++] = s; } else if(strcasecmp(type,"light")==0) { printf("found light\n"); parse_doubles(file,"pos:",l.position); parse_doubles(file,"col:",l.color); if(num_lights == MAX_LIGHTS) { printf("too many lights, you should increase MAX_LIGHTS!\n"); exit(0); } lights[num_lights++] = l; } else { printf("unknown type in scene description:\n%s\n",type); exit(0); } } return 0; } void display() { } void init() { glMatrixMode(GL_PROJECTION); glOrtho(0,WIDTH,0,HEIGHT,1,-1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClearColor(0,0,0,0); glClear(GL_COLOR_BUFFER_BIT); } void idle() { //hack to make it only draw once static int once=0; if(!once) { draw_scene(); if(mode == MODE_JPEG) save_jpg(); } once=1; } int main (int argc, char ** argv) { if (argc<2 || argc > 3) { printf ("usage: %s <scenefile> [jpegname]\n", argv[0]); exit(0); } if(argc == 3) { mode = MODE_JPEG; filename = argv[2]; } else if(argc == 2) mode = MODE_DISPLAY; glutInit(&argc,argv); loadScene(argv[1]); glutInitDisplayMode(GLUT_RGBA | GLUT_SINGLE); glutInitWindowPosition(0,0); glutInitWindowSize(WIDTH,HEIGHT); int window = glutCreateWindow("Ray Tracer"); glutDisplayFunc(display); glutIdleFunc(idle); init(); glutMainLoop(); } <|endoftext|>
<commit_before>// Created on: 2007-09-04 // Created by: Andrey BETENEV // Copyright (c) 2007-2012 OPEN CASCADE SAS // // The content of this file is subject to the Open CASCADE Technology Public // License Version 6.5 (the "License"). You may not use the content of this file // except in compliance with the License. Please obtain a copy of the License // at http://www.opencascade.org and read it completely before using this file. // // The Initial Developer of the Original Code is Open CASCADE S.A.S., having its // main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France. // // The Original Code and all software distributed under the License is // distributed on an "AS IS" basis, without warranty of any kind, and the // Initial Developer hereby disclaims all such warranties, including without // limitation, any warranties of merchantability, fitness for a particular // purpose or non-infringement. Please see the License for the specific terms // and conditions governing the rights and limitations under the License. //! @file //! Implementation of some atomic operations (elementary operations //! with data that cannot be interrupted by parallel threads in the //! multithread process) on various platforms //! //! By the moment, only operations necessary for reference counter //! in Standard_Transient objects are implemented. //! //! This is preffered to use fixed size types "int32_t" / "int64_t" for //! correct function declarations however we leave "int" assuming it is 32bits for now. #ifndef _Standard_Atomic_HeaderFile #define _Standard_Atomic_HeaderFile #include <Standard_Macro.hxx> #if (defined(_WIN32) || defined(__WIN32__)) #ifdef _MSC_VER extern "C" { long _InterlockedIncrement(long volatile* lpAddend); long _InterlockedDecrement(long volatile* lpAddend); } // force intrinsic instead of WinAPI calls #pragma intrinsic (_InterlockedIncrement) #pragma intrinsic (_InterlockedDecrement) #else extern "C" { __declspec(dllimport) long __stdcall InterlockedIncrement ( long volatile *lpAddend); __declspec(dllimport) long __stdcall InterlockedDecrement ( long volatile *lpAddend); } #define _InterlockedIncrement InterlockedIncrement #define _InterlockedDecrement InterlockedDecrement #endif #endif //! Increments atomically integer variable pointed by theValue //! and returns resulting incremented value. static int Standard_Atomic_Increment (volatile int* theValue) { #ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 // mordern g++ compiler (gcc4.4+) // built-in functions available for appropriate CPUs (at least -march=i486 should be specified on x86 platform) return __sync_add_and_fetch (theValue, 1); #elif (defined(_WIN32) || defined(__WIN32__)) // WinAPI function or MSVC intrinsic return _InterlockedIncrement(reinterpret_cast<long volatile*>(theValue)); #elif defined(LIN) // use x86 / x86_64 inline assembly (compatibility with alien compilers / old GCC) int anIncResult; __asm__ __volatile__ ( #if defined(_OCC64) "lock xaddl %%ebx, (%%rax) \n\t" "incl %%ebx \n\t" : "=b" (anIncResult) : "a" (theValue), "b" (1) : "cc", "memory"); #else "lock xaddl %%eax, (%%ecx) \n\t" "incl %%eax \n\t" : "=a" (anIncResult) : "c" (theValue), "a" (1) : "memory"); #endif return anIncResult; #else //#error "Atomic operation doesn't implemented for current platform!" return ++(*theValue); #endif } //! Decrements atomically integer variable pointed by theValue //! and returns resulting decremented value. static int Standard_Atomic_Decrement (volatile int* theValue) { #ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 // mordern g++ compiler (gcc4.4+) // built-in functions available for appropriate CPUs (at least -march=i486 should be specified on x86 platform) return __sync_sub_and_fetch (theValue, 1); #elif (defined(_WIN32) || defined(__WIN32__)) // WinAPI function or MSVC intrinsic return _InterlockedDecrement(reinterpret_cast<long volatile*>(theValue)); #elif defined(LIN) // use x86 / x86_64 inline assembly (compatibility with alien compilers / old GCC) int aDecResult; __asm__ __volatile__ ( #if defined(_OCC64) "lock xaddl %%ebx, (%%rax) \n\t" "decl %%ebx \n\t" : "=b" (aDecResult) : "a" (theValue), "b" (-1) : "cc", "memory"); #else "lock xaddl %%eax, (%%ecx) \n\t" "decl %%eax \n\t" : "=a" (aDecResult) : "c" (theValue), "a" (-1) : "memory"); #endif return aDecResult; #else //#error "Atomic operation doesn't implemented for current platform!" return --(*theValue); #endif } #endif //_Standard_Atomic_HeaderFile <commit_msg>Tab/Space fix.<commit_after>// Created on: 2007-09-04 // Created by: Andrey BETENEV // Copyright (c) 2007-2012 OPEN CASCADE SAS // // The content of this file is subject to the Open CASCADE Technology Public // License Version 6.5 (the "License"). You may not use the content of this file // except in compliance with the License. Please obtain a copy of the License // at http://www.opencascade.org and read it completely before using this file. // // The Initial Developer of the Original Code is Open CASCADE S.A.S., having its // main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France. // // The Original Code and all software distributed under the License is // distributed on an "AS IS" basis, without warranty of any kind, and the // Initial Developer hereby disclaims all such warranties, including without // limitation, any warranties of merchantability, fitness for a particular // purpose or non-infringement. Please see the License for the specific terms // and conditions governing the rights and limitations under the License. //! @file //! Implementation of some atomic operations (elementary operations //! with data that cannot be interrupted by parallel threads in the //! multithread process) on various platforms //! //! By the moment, only operations necessary for reference counter //! in Standard_Transient objects are implemented. //! //! This is preffered to use fixed size types "int32_t" / "int64_t" for //! correct function declarations however we leave "int" assuming it is 32bits for now. #ifndef _Standard_Atomic_HeaderFile #define _Standard_Atomic_HeaderFile #include <Standard_Macro.hxx> #if (defined(_WIN32) || defined(__WIN32__)) #ifdef _MSC_VER extern "C" { long _InterlockedIncrement(long volatile* lpAddend); long _InterlockedDecrement(long volatile* lpAddend); } // force intrinsic instead of WinAPI calls #pragma intrinsic (_InterlockedIncrement) #pragma intrinsic (_InterlockedDecrement) #else extern "C" { __declspec(dllimport) long __stdcall InterlockedIncrement ( long volatile *lpAddend); __declspec(dllimport) long __stdcall InterlockedDecrement ( long volatile *lpAddend); } #define _InterlockedIncrement InterlockedIncrement #define _InterlockedDecrement InterlockedDecrement #endif #endif //! Increments atomically integer variable pointed by theValue //! and returns resulting incremented value. static int Standard_Atomic_Increment (volatile int* theValue) { #ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 // mordern g++ compiler (gcc4.4+) // built-in functions available for appropriate CPUs (at least -march=i486 should be specified on x86 platform) return __sync_add_and_fetch (theValue, 1); #elif (defined(_WIN32) || defined(__WIN32__)) // WinAPI function or MSVC intrinsic return _InterlockedIncrement(reinterpret_cast<long volatile*>(theValue)); #elif defined(LIN) // use x86 / x86_64 inline assembly (compatibility with alien compilers / old GCC) int anIncResult; __asm__ __volatile__ ( #if defined(_OCC64) "lock xaddl %%ebx, (%%rax) \n\t" "incl %%ebx \n\t" : "=b" (anIncResult) : "a" (theValue), "b" (1) : "cc", "memory"); #else "lock xaddl %%eax, (%%ecx) \n\t" "incl %%eax \n\t" : "=a" (anIncResult) : "c" (theValue), "a" (1) : "memory"); #endif return anIncResult; #else //#error "Atomic operation doesn't implemented for current platform!" return ++(*theValue); #endif } //! Decrements atomically integer variable pointed by theValue //! and returns resulting decremented value. static int Standard_Atomic_Decrement (volatile int* theValue) { #ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 // mordern g++ compiler (gcc4.4+) // built-in functions available for appropriate CPUs (at least -march=i486 should be specified on x86 platform) return __sync_sub_and_fetch (theValue, 1); #elif (defined(_WIN32) || defined(__WIN32__)) // WinAPI function or MSVC intrinsic return _InterlockedDecrement(reinterpret_cast<long volatile*>(theValue)); #elif defined(LIN) // use x86 / x86_64 inline assembly (compatibility with alien compilers / old GCC) int aDecResult; __asm__ __volatile__ ( #if defined(_OCC64) "lock xaddl %%ebx, (%%rax) \n\t" "decl %%ebx \n\t" : "=b" (aDecResult) : "a" (theValue), "b" (-1) : "cc", "memory"); #else "lock xaddl %%eax, (%%ecx) \n\t" "decl %%eax \n\t" : "=a" (aDecResult) : "c" (theValue), "a" (-1) : "memory"); #endif return aDecResult; #else //#error "Atomic operation doesn't implemented for current platform!" return --(*theValue); #endif } #endif //_Standard_Atomic_HeaderFile <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //------------------------------------------------------------------------- // Event handler for AOD input // Author: Andreas Morsch, CERN //------------------------------------------------------------------------- #include <TSystem.h> #include <TTree.h> #include <TList.h> #include <TNamed.h> #include <TFile.h> #include <TH2.h> #include "AliAODInputHandler.h" #include "AliAODEvent.h" #include "AliVCuts.h" #include "AliMCEvent.h" #include "AliAODpidUtil.h" ClassImp(AliAODInputHandler) static Option_t *gAODDataType = "AOD"; //______________________________________________________________________________ AliAODInputHandler::AliAODInputHandler() : AliInputEventHandler(), fEvent(0), fMCEvent(new AliMCEvent()), fFriends(new TList()), fAODpidUtil(0x0), fMergeEvents(kFALSE), fMergeTracks(kTRUE), fMergeEMCALClusters(kTRUE), fMergePHOSClusters(kTRUE), fMergeEMCALCells(kTRUE), fMergePHOSCells(kTRUE), fFriendsConnected(kFALSE), fFileToMerge(0), fTreeToMerge(0), fAODEventToMerge(0), fMergeOffset(0) { // Default constructor fHistStatistics[0] = fHistStatistics[1] = NULL; } //______________________________________________________________________________ AliAODInputHandler::AliAODInputHandler(const char* name, const char* title): AliInputEventHandler(name, title), fEvent(0), fMCEvent(new AliMCEvent()), fFriends(new TList()), fAODpidUtil(0x0), fMergeEvents(kFALSE), fMergeTracks(kTRUE), fMergeEMCALClusters(kTRUE), fMergePHOSClusters(kTRUE), fMergeEMCALCells(kTRUE), fMergePHOSCells(kTRUE), fFriendsConnected(kFALSE), fFileToMerge(0), fTreeToMerge(0), fAODEventToMerge(0), fMergeOffset(0) { // Constructor fHistStatistics[0] = fHistStatistics[1] = NULL; } //______________________________________________________________________________ AliAODInputHandler::~AliAODInputHandler() { // Destructor fFriends->Delete(); if (fHistStatistics[0]) { delete fHistStatistics[0]; fHistStatistics[0] = 0; } if (fHistStatistics[1]) { delete fHistStatistics[1]; fHistStatistics[1] = 0; } delete fAODpidUtil; } //______________________________________________________________________________ Bool_t AliAODInputHandler::Init(TTree* tree, Option_t* opt) { // Initialisation necessary for each new tree fTree = tree; if (!fTree) return kFALSE; fTree->GetEntries(); ConnectFriends(); SwitchOffBranches(); SwitchOnBranches(); // Get pointer to AOD event if (!fEvent) fEvent = new AliAODEvent(); fEvent->ReadFromTree(fTree); if (fMixingHandler) fMixingHandler->Init(tree, opt); return kTRUE; } //______________________________________________________________________________ Bool_t AliAODInputHandler::BeginEvent(Long64_t entry) { // Begin event TClonesArray* mcParticles = (TClonesArray*) (fEvent->FindListObject("mcparticles")); if (mcParticles) fMCEvent->SetParticleArray(mcParticles); // When merging, get current event number from GetReadEntry(), // entry gives the events in the current file if (fTreeToMerge) fTreeToMerge->GetEntry(GetReadEntry() + fMergeOffset); fIsSelectedResult = fEvent->GetHeader()->GetOfflineTrigger(); if (fMixingHandler) fMixingHandler->BeginEvent(entry); return kTRUE; } //______________________________________________________________________________ Bool_t AliAODInputHandler::Notify(const char* path) { // Notifaction of directory change if (fMixingHandler) fMixingHandler->Notify(path); if (!fFriendsConnected) { ConnectFriends(); fEvent->ReadFromTree(fTree, "reconnect"); } fFriendsConnected = kFALSE; TTree *ttree = fTree->GetTree(); if (!ttree) ttree = fTree; TString statFname(ttree->GetCurrentFile()->GetName()); Int_t indarchive = statFname.Index("#"); if (indarchive<0) { statFname = gSystem->DirName(statFname); statFname += "/"; } else { statFname.Remove(indarchive+1); } statFname += "EventStat_temp.root"; TFile *statFile = 0; if (IsCheckStatistics()) statFile = TFile::Open(statFname, "READ"); if (statFile) { TList *list = (TList*)statFile->Get("cstatsout"); if (list) { AliVCuts *physSel = (AliVCuts*)list->At(0); if (physSel) { TH2F *hAll = dynamic_cast<TH2F*>(physSel->GetStatistics("ALL")); TH2F *hBin0 = dynamic_cast<TH2F*>(physSel->GetStatistics("BIN0")); if (fHistStatistics[0] && hAll) { TList tmplist; tmplist.Add(hAll); fHistStatistics[0]->Merge(&tmplist); tmplist.Clear(); tmplist.Add(hBin0); if (fHistStatistics[1] && hBin0) fHistStatistics[1]->Merge(&tmplist); } else { if (hAll && hBin0) { fHistStatistics[0] = static_cast<TH2F*>(hAll->Clone()); fHistStatistics[1] = static_cast<TH2F*>(hBin0->Clone()); fHistStatistics[0]->SetDirectory(0); fHistStatistics[1]->SetDirectory(0); } } } delete list; } delete statFile; } return kTRUE; } //______________________________________________________________________________ Bool_t AliAODInputHandler::FinishEvent() { // Finish event if (fMixingHandler) fMixingHandler->FinishEvent(); return kTRUE; } //______________________________________________________________________________ void AliAODInputHandler::AddFriend(char* filename) { // Add a friend tree TNamed* obj = new TNamed(filename, filename); fFriends->Add(obj); } //______________________________________________________________________________ Option_t *AliAODInputHandler::GetDataType() const { // Returns handled data type. return gAODDataType; } //______________________________________________________________________________ TObject *AliAODInputHandler::GetStatistics(Option_t *option) const { // Get the statistics histogram(s) from the physics selection object. This // should be called during FinishTaskOutput(). Option can be empty (default // statistics histogram) or BIN0. TString opt(option); opt.ToUpper(); if (opt=="BIN0") return fHistStatistics[1]; return fHistStatistics[0]; } void AliAODInputHandler::ConnectFriends() { // Connect the friend trees if (!fMergeEvents) { TIter next(fFriends); TNamed* obj; TString aodTreeFName,aodFriendTreeFName; TTree *ttree = fTree->GetTree(); if (!ttree) ttree = fTree; aodTreeFName = ttree->GetCurrentFile()->GetName(); while((obj = (TNamed*)next())) { aodFriendTreeFName = aodTreeFName; aodFriendTreeFName.ReplaceAll("AliAOD.root",obj->GetName()); aodFriendTreeFName.ReplaceAll("AliAODs.root",obj->GetName()); ttree->AddFriend("aodTree", aodFriendTreeFName.Data()); } } else { // Friends have to be merged TNamed* filename = (TNamed*) (fFriends->At(0)); fFileToMerge = TFile::Open(filename->GetName()); if (fFileToMerge) { fFileToMerge->GetObject("aodTree", fTreeToMerge); if (!fAODEventToMerge) fAODEventToMerge = new AliAODEvent(); fAODEventToMerge->ReadFromTree(fTreeToMerge); } } fFriendsConnected = kTRUE; } //______________________________________________________________________________ void AliAODInputHandler::CreatePIDResponse(Bool_t isMC/*=kFALSE*/) { // // create the pid response object if it does not exist yet // if (fAODpidUtil) return; fAODpidUtil=new AliAODpidUtil(isMC); } <commit_msg>Adding AliInfo informing about file change<commit_after>/************************************************************************** * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //------------------------------------------------------------------------- // Event handler for AOD input // Author: Andreas Morsch, CERN //------------------------------------------------------------------------- #include <TSystem.h> #include <TTree.h> #include <TList.h> #include <TNamed.h> #include <TFile.h> #include <TH2.h> #include "AliAODInputHandler.h" #include "AliAODEvent.h" #include "AliVCuts.h" #include "AliMCEvent.h" #include "AliAODpidUtil.h" ClassImp(AliAODInputHandler) static Option_t *gAODDataType = "AOD"; //______________________________________________________________________________ AliAODInputHandler::AliAODInputHandler() : AliInputEventHandler(), fEvent(0), fMCEvent(new AliMCEvent()), fFriends(new TList()), fAODpidUtil(0x0), fMergeEvents(kFALSE), fMergeTracks(kTRUE), fMergeEMCALClusters(kTRUE), fMergePHOSClusters(kTRUE), fMergeEMCALCells(kTRUE), fMergePHOSCells(kTRUE), fFriendsConnected(kFALSE), fFileToMerge(0), fTreeToMerge(0), fAODEventToMerge(0), fMergeOffset(0) { // Default constructor fHistStatistics[0] = fHistStatistics[1] = NULL; } //______________________________________________________________________________ AliAODInputHandler::AliAODInputHandler(const char* name, const char* title): AliInputEventHandler(name, title), fEvent(0), fMCEvent(new AliMCEvent()), fFriends(new TList()), fAODpidUtil(0x0), fMergeEvents(kFALSE), fMergeTracks(kTRUE), fMergeEMCALClusters(kTRUE), fMergePHOSClusters(kTRUE), fMergeEMCALCells(kTRUE), fMergePHOSCells(kTRUE), fFriendsConnected(kFALSE), fFileToMerge(0), fTreeToMerge(0), fAODEventToMerge(0), fMergeOffset(0) { // Constructor fHistStatistics[0] = fHistStatistics[1] = NULL; } //______________________________________________________________________________ AliAODInputHandler::~AliAODInputHandler() { // Destructor fFriends->Delete(); if (fHistStatistics[0]) { delete fHistStatistics[0]; fHistStatistics[0] = 0; } if (fHistStatistics[1]) { delete fHistStatistics[1]; fHistStatistics[1] = 0; } delete fAODpidUtil; } //______________________________________________________________________________ Bool_t AliAODInputHandler::Init(TTree* tree, Option_t* opt) { // Initialisation necessary for each new tree fTree = tree; if (!fTree) return kFALSE; fTree->GetEntries(); ConnectFriends(); SwitchOffBranches(); SwitchOnBranches(); // Get pointer to AOD event if (!fEvent) fEvent = new AliAODEvent(); fEvent->ReadFromTree(fTree); if (fMixingHandler) fMixingHandler->Init(tree, opt); return kTRUE; } //______________________________________________________________________________ Bool_t AliAODInputHandler::BeginEvent(Long64_t entry) { // Begin event TClonesArray* mcParticles = (TClonesArray*) (fEvent->FindListObject("mcparticles")); if (mcParticles) fMCEvent->SetParticleArray(mcParticles); // When merging, get current event number from GetReadEntry(), // entry gives the events in the current file if (fTreeToMerge) fTreeToMerge->GetEntry(GetReadEntry() + fMergeOffset); fIsSelectedResult = fEvent->GetHeader()->GetOfflineTrigger(); if (fMixingHandler) fMixingHandler->BeginEvent(entry); return kTRUE; } //______________________________________________________________________________ Bool_t AliAODInputHandler::Notify(const char* path) { // Notifaction of directory change if (fMixingHandler) fMixingHandler->Notify(path); if (!fFriendsConnected) { ConnectFriends(); fEvent->ReadFromTree(fTree, "reconnect"); } fFriendsConnected = kFALSE; TTree *ttree = fTree->GetTree(); if (!ttree) ttree = fTree; TString statFname(ttree->GetCurrentFile()->GetName()); AliInfo(Form("Moving to file %s", statFname.Data())); Int_t indarchive = statFname.Index("#"); if (indarchive<0) { statFname = gSystem->DirName(statFname); statFname += "/"; } else { statFname.Remove(indarchive+1); } statFname += "EventStat_temp.root"; TFile *statFile = 0; if (IsCheckStatistics()) statFile = TFile::Open(statFname, "READ"); if (statFile) { TList *list = (TList*)statFile->Get("cstatsout"); if (list) { AliVCuts *physSel = (AliVCuts*)list->At(0); if (physSel) { TH2F *hAll = dynamic_cast<TH2F*>(physSel->GetStatistics("ALL")); TH2F *hBin0 = dynamic_cast<TH2F*>(physSel->GetStatistics("BIN0")); if (fHistStatistics[0] && hAll) { TList tmplist; tmplist.Add(hAll); fHistStatistics[0]->Merge(&tmplist); tmplist.Clear(); tmplist.Add(hBin0); if (fHistStatistics[1] && hBin0) fHistStatistics[1]->Merge(&tmplist); } else { if (hAll && hBin0) { fHistStatistics[0] = static_cast<TH2F*>(hAll->Clone()); fHistStatistics[1] = static_cast<TH2F*>(hBin0->Clone()); fHistStatistics[0]->SetDirectory(0); fHistStatistics[1]->SetDirectory(0); } } } delete list; } delete statFile; } return kTRUE; } //______________________________________________________________________________ Bool_t AliAODInputHandler::FinishEvent() { // Finish event if (fMixingHandler) fMixingHandler->FinishEvent(); return kTRUE; } //______________________________________________________________________________ void AliAODInputHandler::AddFriend(char* filename) { // Add a friend tree TNamed* obj = new TNamed(filename, filename); fFriends->Add(obj); } //______________________________________________________________________________ Option_t *AliAODInputHandler::GetDataType() const { // Returns handled data type. return gAODDataType; } //______________________________________________________________________________ TObject *AliAODInputHandler::GetStatistics(Option_t *option) const { // Get the statistics histogram(s) from the physics selection object. This // should be called during FinishTaskOutput(). Option can be empty (default // statistics histogram) or BIN0. TString opt(option); opt.ToUpper(); if (opt=="BIN0") return fHistStatistics[1]; return fHistStatistics[0]; } void AliAODInputHandler::ConnectFriends() { // Connect the friend trees if (!fMergeEvents) { TIter next(fFriends); TNamed* obj; TString aodTreeFName,aodFriendTreeFName; TTree *ttree = fTree->GetTree(); if (!ttree) ttree = fTree; aodTreeFName = ttree->GetCurrentFile()->GetName(); while((obj = (TNamed*)next())) { aodFriendTreeFName = aodTreeFName; aodFriendTreeFName.ReplaceAll("AliAOD.root",obj->GetName()); aodFriendTreeFName.ReplaceAll("AliAODs.root",obj->GetName()); ttree->AddFriend("aodTree", aodFriendTreeFName.Data()); } } else { // Friends have to be merged TNamed* filename = (TNamed*) (fFriends->At(0)); fFileToMerge = TFile::Open(filename->GetName()); if (fFileToMerge) { fFileToMerge->GetObject("aodTree", fTreeToMerge); if (!fAODEventToMerge) fAODEventToMerge = new AliAODEvent(); fAODEventToMerge->ReadFromTree(fTreeToMerge); } } fFriendsConnected = kTRUE; } //______________________________________________________________________________ void AliAODInputHandler::CreatePIDResponse(Bool_t isMC/*=kFALSE*/) { // // create the pid response object if it does not exist yet // if (fAODpidUtil) return; fAODpidUtil=new AliAODpidUtil(isMC); } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2018 by Contributors * \file graph_runtime_debug.cc */ #include <tvm/runtime/packed_func.h> #include <tvm/runtime/registry.h> #include <tvm/runtime/ndarray.h> #include <chrono> #include "../graph_runtime.h" namespace tvm { namespace runtime { /*! * \brief Graph runtime with debug . * * This is the extension of GraphRuntime class used for debugging * TVM runtime PackedFunc API. */ class GraphRuntimeDebug : public GraphRuntime { public: /*! * \brief Run each operation and get the output. * \param index The index of op which needs to be run. * \return the elapsed time. */ double DebugRun(size_t index) { CHECK(index < op_execs_.size()); TVMContext ctx = data_entry_[entry_id(index, 0)]->ctx; auto tbegin = std::chrono::high_resolution_clock::now(); if (op_execs_[index]) { op_execs_[index](); } TVMSynchronize(ctx.device_type, ctx.device_id, nullptr); auto tend = std::chrono::high_resolution_clock::now(); double time = std::chrono::duration_cast<std::chrono::duration<double> >( tend - tbegin).count(); return time; } /*! * \brief Run each operation in the graph and print out the runtime per op. * \param number The number of times to run this function for taking average. * \param repeat The number of times to repeat the measurement. In total, the function will be invoked (1 + number x repeat) times, where the first one is warmed up and will be discarded in case there is lazy initialization. * \param min_repeat_ms The minimum duration of one `repeat` in milliseconds. By default, one `repeat` contains `number` runs. If this parameter is set, the parameters `number` will be dynamically adjusted to meet the minimum duration requirement of one `repeat`. */ void RunIndividual(int number, int repeat, int min_repeat_ms) { // warmup run GraphRuntime::Run(); std::vector<double> time_per_op(op_execs_.size(), 0); for (int i = 0; i < repeat; ++i) { std::chrono::time_point< std::chrono::high_resolution_clock, std::chrono::nanoseconds> tbegin, tend; double duration_ms = 0.0; do { std::fill(time_per_op.begin(), time_per_op.end(), 0); if (duration_ms > 0.0) { number = static_cast<int>( std::max((min_repeat_ms / (duration_ms / number) + 1), number * 1.618)); // 1.618 is chosen by random } tbegin = std::chrono::high_resolution_clock::now(); for (int k = 0; k < number; k++) { for (size_t index = 0; index < op_execs_.size(); ++index) { if (op_execs_[index]) { const TVMContext& ctx = data_entry_[entry_id(index, 0)]->ctx; auto op_tbegin = std::chrono::high_resolution_clock::now(); op_execs_[index](); TVMSynchronize(ctx.device_type, ctx.device_id, nullptr); auto op_tend = std::chrono::high_resolution_clock::now(); double op_duration = std::chrono::duration_cast< std::chrono::duration<double> >(op_tend - op_tbegin).count(); time_per_op[index] += op_duration * 1000; // ms } } } tend = std::chrono::high_resolution_clock::now(); duration_ms = std::chrono::duration_cast<std::chrono::duration<double> > (tend - tbegin).count() * 1000; } while (duration_ms < min_repeat_ms); LOG(INFO) << "Repeat: " << i; int op = 0; for (size_t index = 0; index < time_per_op.size(); index++) { if (op_execs_[index]) { time_per_op[index] /= number; LOG(INFO) << "Op #" << op++ << ": " << time_per_op[index] << " ms/iter"; } } } } /*! * \brief Run each operation and get the output. * \param index The index of op which needs to be returned. * \param eid The Entry id of the op. */ NDArray GetOutputByLayer(int index, int eid) { return data_entry_[entry_id(index, eid)]; } /*! * \brief GetFunction Get the function based on input. * \param name The function which needs to be invoked. * \param sptr_to_self Packed function pointer. */ PackedFunc GetFunction(const std::string& name, const std::shared_ptr<ModuleNode>& sptr_to_self); /*! * \brief Get the node index given the name of node. * \param name The name of the node. * \return The index of node. */ int GetNodeIndex(const std::string& name) const { for (size_t nid = 0; nid < GetNumOfNodes(); ++nid) { if (GetNodeName(nid) == name) { return static_cast<int>(nid); } } LOG(FATAL) << "cannot find " << name << " among nodex"; return -1; } /*! * \brief Copy index-th node to data_out. * * This method will do a partial run of the the graph * from begining upto the index-th node and return output of index-th node. * This is costly operation and suggest to use only for debug porpose. * * \param index: The index of the node. * \param data_out the node data. */ void DebugGetNodeOutput(int index, DLTensor* data_out) { CHECK_LT(static_cast<size_t>(index), op_execs_.size()); uint32_t eid = index; for (size_t i = 0; i < op_execs_.size(); ++i) { if (op_execs_[i]) op_execs_[i](); if (static_cast<int>(i) == index) break; } data_entry_[eid].CopyTo(data_out); } }; /*! * \brief GetFunction Get the function based on input. * \param name The function which needs to be invoked. * \param sptr_to_self Packed function pointer. */ PackedFunc GraphRuntimeDebug::GetFunction( const std::string& name, const std::shared_ptr<ModuleNode>& sptr_to_self) { // return member functions during query. if (name == "debug_run") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->DebugRun(static_cast<size_t>(args[0].operator int64_t())); }); } else if (name == "get_output_by_layer") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->GetOutputByLayer(args[0], args[1]); }); } else if (name == "debug_get_output") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { if (args[0].type_code() == kStr) { this->DebugGetNodeOutput(this->GetNodeIndex(args[0]), args[1]); } else { this->DebugGetNodeOutput(args[0], args[1]); } }); } else if (name == "run_individual") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { int number = args[0]; int repeat = args[1]; int min_repeat_ms = args[2]; CHECK_GT(number, 0); CHECK_GT(repeat, 0); CHECK_GE(min_repeat_ms, 0); this->RunIndividual(number, repeat, min_repeat_ms); }); } else { return GraphRuntime::GetFunction(name, sptr_to_self); } } /*! * \brief GraphRuntimeDebugCreate Get the function based on input. * \param sym_json The graph symbol in json format. * \param m Compiled module which will be loaded. * \param ctxs All devices contexts. */ Module GraphRuntimeDebugCreate(const std::string& sym_json, const tvm::runtime::Module& m, const std::vector<TVMContext>& ctxs) { std::shared_ptr<GraphRuntimeDebug> exec = std::make_shared<GraphRuntimeDebug>(); exec->Init(sym_json, m, ctxs); return Module(exec); } TVM_REGISTER_GLOBAL("tvm.graph_runtime_debug.create") .set_body([](TVMArgs args, TVMRetValue* rv) { CHECK_GE(args.num_args, 4) << "The expected number of arguments for graph_runtime.create is " "at least 4, but it has " << args.num_args; *rv = GraphRuntimeDebugCreate(args[0], args[1], GetAllContext(args)); }); TVM_REGISTER_GLOBAL("tvm.graph_runtime_debug.remote_create") .set_body([](TVMArgs args, TVMRetValue* rv) { CHECK_GE(args.num_args, 4) << "The expected number of arguments for " "graph_runtime.remote_create is " "at least 4, but it has " << args.num_args; void* mhandle = args[1]; const auto& contexts = GetAllContext(args); *rv = GraphRuntimeDebugCreate( args[0], *static_cast<tvm::runtime::Module*>(mhandle), contexts); }); } // namespace runtime } // namespace tvm <commit_msg>Minor addition to graph runtime debug (#3129)<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2018 by Contributors * \file graph_runtime_debug.cc */ #include <tvm/runtime/packed_func.h> #include <tvm/runtime/registry.h> #include <tvm/runtime/ndarray.h> #include <chrono> #include "../graph_runtime.h" namespace tvm { namespace runtime { /*! * \brief Graph runtime with debug . * * This is the extension of GraphRuntime class used for debugging * TVM runtime PackedFunc API. */ class GraphRuntimeDebug : public GraphRuntime { public: /*! * \brief Run each operation and get the output. * \param index The index of op which needs to be run. * \return the elapsed time. */ double DebugRun(size_t index) { CHECK(index < op_execs_.size()); TVMContext ctx = data_entry_[entry_id(index, 0)]->ctx; auto tbegin = std::chrono::high_resolution_clock::now(); if (op_execs_[index]) { op_execs_[index](); } TVMSynchronize(ctx.device_type, ctx.device_id, nullptr); auto tend = std::chrono::high_resolution_clock::now(); double time = std::chrono::duration_cast<std::chrono::duration<double> >( tend - tbegin).count(); return time; } /*! * \brief Run each operation in the graph and print out the runtime per op. * \param number The number of times to run this function for taking average. * \param repeat The number of times to repeat the measurement. In total, the function will be invoked (1 + number x repeat) times, where the first one is warmed up and will be discarded in case there is lazy initialization. * \param min_repeat_ms The minimum duration of one `repeat` in milliseconds. By default, one `repeat` contains `number` runs. If this parameter is set, the parameters `number` will be dynamically adjusted to meet the minimum duration requirement of one `repeat`. */ void RunIndividual(int number, int repeat, int min_repeat_ms) { // warmup run GraphRuntime::Run(); std::vector<double> time_per_op(op_execs_.size(), 0); for (int i = 0; i < repeat; ++i) { std::chrono::time_point< std::chrono::high_resolution_clock, std::chrono::nanoseconds> tbegin, tend; double duration_ms = 0.0; do { std::fill(time_per_op.begin(), time_per_op.end(), 0); if (duration_ms > 0.0) { number = static_cast<int>( std::max((min_repeat_ms / (duration_ms / number) + 1), number * 1.618)); // 1.618 is chosen by random } tbegin = std::chrono::high_resolution_clock::now(); for (int k = 0; k < number; k++) { for (size_t index = 0; index < op_execs_.size(); ++index) { if (op_execs_[index]) { const TVMContext& ctx = data_entry_[entry_id(index, 0)]->ctx; auto op_tbegin = std::chrono::high_resolution_clock::now(); op_execs_[index](); TVMSynchronize(ctx.device_type, ctx.device_id, nullptr); auto op_tend = std::chrono::high_resolution_clock::now(); double op_duration = std::chrono::duration_cast< std::chrono::duration<double> >(op_tend - op_tbegin).count(); time_per_op[index] += op_duration * 1000; // ms } } } tend = std::chrono::high_resolution_clock::now(); duration_ms = std::chrono::duration_cast<std::chrono::duration<double> > (tend - tbegin).count() * 1000; } while (duration_ms < min_repeat_ms); LOG(INFO) << "Repeat: " << i; int op = 0; for (size_t index = 0; index < time_per_op.size(); index++) { if (op_execs_[index]) { time_per_op[index] /= number; LOG(INFO) << "Op #" << op++ << " " << GetNodeName(index) << ": " << time_per_op[index] << " ms/iter"; } } } } /*! * \brief Run each operation and get the output. * \param index The index of op which needs to be returned. * \param eid The Entry id of the op. */ NDArray GetOutputByLayer(int index, int eid) { return data_entry_[entry_id(index, eid)]; } /*! * \brief GetFunction Get the function based on input. * \param name The function which needs to be invoked. * \param sptr_to_self Packed function pointer. */ PackedFunc GetFunction(const std::string& name, const std::shared_ptr<ModuleNode>& sptr_to_self); /*! * \brief Get the node index given the name of node. * \param name The name of the node. * \return The index of node. */ int GetNodeIndex(const std::string& name) const { for (size_t nid = 0; nid < GetNumOfNodes(); ++nid) { if (GetNodeName(nid) == name) { return static_cast<int>(nid); } } LOG(FATAL) << "cannot find " << name << " among nodex"; return -1; } /*! * \brief Copy index-th node to data_out. * * This method will do a partial run of the the graph * from begining upto the index-th node and return output of index-th node. * This is costly operation and suggest to use only for debug porpose. * * \param index: The index of the node. * \param data_out the node data. */ void DebugGetNodeOutput(int index, DLTensor* data_out) { CHECK_LT(static_cast<size_t>(index), op_execs_.size()); uint32_t eid = index; for (size_t i = 0; i < op_execs_.size(); ++i) { if (op_execs_[i]) op_execs_[i](); if (static_cast<int>(i) == index) break; } data_entry_[eid].CopyTo(data_out); } }; /*! * \brief GetFunction Get the function based on input. * \param name The function which needs to be invoked. * \param sptr_to_self Packed function pointer. */ PackedFunc GraphRuntimeDebug::GetFunction( const std::string& name, const std::shared_ptr<ModuleNode>& sptr_to_self) { // return member functions during query. if (name == "debug_run") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->DebugRun(static_cast<size_t>(args[0].operator int64_t())); }); } else if (name == "get_output_by_layer") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->GetOutputByLayer(args[0], args[1]); }); } else if (name == "debug_get_output") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { if (args[0].type_code() == kStr) { this->DebugGetNodeOutput(this->GetNodeIndex(args[0]), args[1]); } else { this->DebugGetNodeOutput(args[0], args[1]); } }); } else if (name == "run_individual") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { int number = args[0]; int repeat = args[1]; int min_repeat_ms = args[2]; CHECK_GT(number, 0); CHECK_GT(repeat, 0); CHECK_GE(min_repeat_ms, 0); this->RunIndividual(number, repeat, min_repeat_ms); }); } else { return GraphRuntime::GetFunction(name, sptr_to_self); } } /*! * \brief GraphRuntimeDebugCreate Get the function based on input. * \param sym_json The graph symbol in json format. * \param m Compiled module which will be loaded. * \param ctxs All devices contexts. */ Module GraphRuntimeDebugCreate(const std::string& sym_json, const tvm::runtime::Module& m, const std::vector<TVMContext>& ctxs) { std::shared_ptr<GraphRuntimeDebug> exec = std::make_shared<GraphRuntimeDebug>(); exec->Init(sym_json, m, ctxs); return Module(exec); } TVM_REGISTER_GLOBAL("tvm.graph_runtime_debug.create") .set_body([](TVMArgs args, TVMRetValue* rv) { CHECK_GE(args.num_args, 4) << "The expected number of arguments for graph_runtime.create is " "at least 4, but it has " << args.num_args; *rv = GraphRuntimeDebugCreate(args[0], args[1], GetAllContext(args)); }); TVM_REGISTER_GLOBAL("tvm.graph_runtime_debug.remote_create") .set_body([](TVMArgs args, TVMRetValue* rv) { CHECK_GE(args.num_args, 4) << "The expected number of arguments for " "graph_runtime.remote_create is " "at least 4, but it has " << args.num_args; void* mhandle = args[1]; const auto& contexts = GetAllContext(args); *rv = GraphRuntimeDebugCreate( args[0], *static_cast<tvm::runtime::Module*>(mhandle), contexts); }); } // namespace runtime } // namespace tvm <|endoftext|>
<commit_before><commit_msg>Exclude a few OpenVino flaky tests (#4572)<commit_after><|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \file expression.cpp \author (rdo@rk9.bmstu.ru) \date 07.03.2011 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "simulator/compiler/parser/pch.h" // ----------------------------------------------------------------------- INCLUDES // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/compiler/parser/expression.h" #include "simulator/runtime/rdo_resource.h" #include "simulator/runtime/calc/procedural/calc_const.h" // -------------------------------------------------------------------------------- OPEN_RDO_PARSER_NAMESPACE // -------------------------------------------------------------------------------- // -------------------- Expression // -------------------------------------------------------------------------------- Expression::Expression(CREF(LPTypeInfo) pType, CREF(rdo::runtime::LPRDOCalc) pCalc, CREF(RDOParserSrcInfo) src_info) : m_pType(pType) , m_pCalc(pCalc) { ASSERT(m_pType); if (m_pCalc) { rdo::runtime::LPRDOCalcConst pConstCalc = m_pCalc.object_dynamic_cast<rdo::runtime::RDOCalcConst>(); if (pConstCalc) { m_pValue = rdo::Factory<RDOValue>::create(pConstCalc->getValue(), src_info, m_pType); } } setSrcInfo(src_info); } Expression::Expression(CREF(LPRDOValue) pValue) : m_pType (pValue->typeInfo()) , m_pValue(pValue ) { ASSERT(pValue); ASSERT(pValue->constant()); m_pCalc = rdo::Factory<rdo::runtime::RDOCalcConst>::create(pValue->value()); ASSERT(m_pCalc); setSrcInfo(pValue->src_info()); } Expression::Expression(CREF(LPExpression) pExpression) : m_pType (pExpression->m_pType ) , m_pCalc (pExpression->m_pCalc ) , m_pValue(pExpression->m_pValue) {} Expression::~Expression() {} CREF(LPTypeInfo) Expression::typeInfo() const { return m_pType; } CREF(rdo::runtime::LPRDOCalc) Expression::calc() const { return m_pCalc; } void Expression::setSrcInfo(CREF(RDOParserSrcInfo) src_info) { RDOParserSrcInfo::setSrcInfo(src_info); if (m_pCalc) { m_pCalc->setSrcInfo(src_info); } } LPRDOValue Expression::constant() const { if (m_pValue) { return m_pValue; } return LPRDOValue(NULL); } // -------------------------------------------------------------------------------- // -------------------- ExpressionStatement // -------------------------------------------------------------------------------- ExpressionStatement::ExpressionStatement(CREF(LPTypeInfo) pType, CREF(rdo::runtime::LPRDOCalc) pCalc, CREF(rdo::runtime::RDOSrcInfo) src_info) :Expression (pType, pCalc, src_info), m_returnFlag(true ) {} ExpressionStatement::ExpressionStatement(CREF(LPExpression) pExpression) :Expression (pExpression), m_returnFlag(true ) {} ExpressionStatement::~ExpressionStatement() {} rbool ExpressionStatement::getReturn() { return m_returnFlag; } CLOSE_RDO_PARSER_NAMESPACE <commit_msg> - touch file for svn test<commit_after>/*! \copyright (c) RDO-Team, 2011 \author (rdo@rk9.bmstu.ru) \date 07.03.2011 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "simulator/compiler/parser/pch.h" // ----------------------------------------------------------------------- INCLUDES // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/compiler/parser/expression.h" #include "simulator/runtime/rdo_resource.h" #include "simulator/runtime/calc/procedural/calc_const.h" // -------------------------------------------------------------------------------- OPEN_RDO_PARSER_NAMESPACE // -------------------------------------------------------------------------------- // -------------------- Expression // -------------------------------------------------------------------------------- Expression::Expression(CREF(LPTypeInfo) pType, CREF(rdo::runtime::LPRDOCalc) pCalc, CREF(RDOParserSrcInfo) src_info) : m_pType(pType) , m_pCalc(pCalc) { ASSERT(m_pType); if (m_pCalc) { rdo::runtime::LPRDOCalcConst pConstCalc = m_pCalc.object_dynamic_cast<rdo::runtime::RDOCalcConst>(); if (pConstCalc) { m_pValue = rdo::Factory<RDOValue>::create(pConstCalc->getValue(), src_info, m_pType); } } setSrcInfo(src_info); } Expression::Expression(CREF(LPRDOValue) pValue) : m_pType (pValue->typeInfo()) , m_pValue(pValue ) { ASSERT(pValue); ASSERT(pValue->constant()); m_pCalc = rdo::Factory<rdo::runtime::RDOCalcConst>::create(pValue->value()); ASSERT(m_pCalc); setSrcInfo(pValue->src_info()); } Expression::Expression(CREF(LPExpression) pExpression) : m_pType (pExpression->m_pType ) , m_pCalc (pExpression->m_pCalc ) , m_pValue(pExpression->m_pValue) {} Expression::~Expression() {} CREF(LPTypeInfo) Expression::typeInfo() const { return m_pType; } CREF(rdo::runtime::LPRDOCalc) Expression::calc() const { return m_pCalc; } void Expression::setSrcInfo(CREF(RDOParserSrcInfo) src_info) { RDOParserSrcInfo::setSrcInfo(src_info); if (m_pCalc) { m_pCalc->setSrcInfo(src_info); } } LPRDOValue Expression::constant() const { if (m_pValue) { return m_pValue; } return LPRDOValue(NULL); } // -------------------------------------------------------------------------------- // -------------------- ExpressionStatement // -------------------------------------------------------------------------------- ExpressionStatement::ExpressionStatement(CREF(LPTypeInfo) pType, CREF(rdo::runtime::LPRDOCalc) pCalc, CREF(rdo::runtime::RDOSrcInfo) src_info) :Expression (pType, pCalc, src_info), m_returnFlag(true ) {} ExpressionStatement::ExpressionStatement(CREF(LPExpression) pExpression) :Expression (pExpression), m_returnFlag(true ) {} ExpressionStatement::~ExpressionStatement() {} rbool ExpressionStatement::getReturn() { return m_returnFlag; } CLOSE_RDO_PARSER_NAMESPACE <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////////// // Copyright � 2007, Daniel �nnerby // // 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 author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #include "pch.hpp" #include <core/debug.h> #include <core/playback/Transport.h> #include <core/plugin/PluginFactory.h> #include <algorithm> #include <boost/thread.hpp> using namespace musik::core::audio; static std::string TAG = "Transport"; #define RESET_NEXT_PLAYER() \ delete this->nextPlayer; \ this->nextPlayer = NULL; #define DEFER(x, y) \ { \ boost::thread thread(boost::bind(x, this, y)); \ thread.detach(); \ } static void stopPlayer(Player* p) { p->Stop(); } static void deletePlayer(Player* p) { delete p; } Transport::Transport() : volume(1.0) , state(PlaybackStopped) , nextPlayer(NULL) , nextCanStart(false) { this->output = Player::CreateDefaultOutput(); } Transport::~Transport() { } Transport::PlaybackState Transport::GetPlaybackState() { boost::recursive_mutex::scoped_lock lock(this->stateMutex); return this->state; } void Transport::PrepareNextTrack(const std::string& trackUrl) { bool startNext = false; { boost::recursive_mutex::scoped_lock lock(this->stateMutex); this->nextPlayer = new Player(trackUrl, this->output); startNext = this->nextCanStart; } if (startNext) { this->StartWithPlayer(this->nextPlayer); } } void Transport::Start(const std::string& url) { musik::debug::info(TAG, "we were asked to start the track at " + url); Player* newPlayer = new Player(url, this->output); musik::debug::info(TAG, "Player created successfully"); this->StartWithPlayer(newPlayer); } void Transport::StartWithPlayer(Player* newPlayer) { if (newPlayer) { { boost::recursive_mutex::scoped_lock lock(this->stateMutex); bool playingNext = (newPlayer == nextPlayer); if (newPlayer != nextPlayer) { delete nextPlayer; } this->nextPlayer = NULL; /* first argument suppresses the "Stop" event from getting triggered, the second param is used for gapless playback -- we won't stop the output and will allow pending buffers to finish */ this->Stop(true, !playingNext); this->SetNextCanStart(false); newPlayer->PlaybackStarted.connect(this, &Transport::OnPlaybackStarted); newPlayer->PlaybackAlmostEnded.connect(this, &Transport::OnPlaybackAlmostEnded); newPlayer->PlaybackFinished.connect(this, &Transport::OnPlaybackFinished); newPlayer->PlaybackError.connect(this, &Transport::OnPlaybackError); musik::debug::info(TAG, "play()"); this->active.push_front(newPlayer); this->output->Resume(); newPlayer->Play(); } this->RaiseStreamEvent(Transport::StreamScheduled, newPlayer); } } void Transport::Stop() { this->Stop(false, true); } void Transport::Stop(bool suppressStopEvent, bool stopOutput) { musik::debug::info(TAG, "stop"); std::list<Player*> toDelete; { boost::recursive_mutex::scoped_lock lock(this->stateMutex); RESET_NEXT_PLAYER(); std::swap(toDelete, this->active); } /* delete these in the background to avoid deadlock in some cases where this method is implicitly triggered via Player callback. however, we should stop them immediately so they stop producing audio. */ std::for_each(toDelete.begin(), toDelete.end(), stopPlayer); DEFER(&Transport::DeletePlayers, toDelete); if (stopOutput) { /* stopping the transport will stop any buffers that are currently in flight. this makes the sound end immediately. */ this->output->Stop(); } if (!suppressStopEvent) { /* if we know we're starting another track immediately, suppress the stop event. this functionality is not available to the public interface, it's an internal optimization */ this->SetPlaybackState(PlaybackStopped); } } bool Transport::Pause() { musik::debug::info(TAG, "pause"); size_t count = 0; this->output->Pause(); { boost::recursive_mutex::scoped_lock lock(this->stateMutex); count = this->active.size(); } if (count) { this->SetPlaybackState(PlaybackPaused); return true; } return false; } bool Transport::Resume() { musik::debug::info(TAG, "resume"); this->output->Resume(); size_t count = 0; { boost::recursive_mutex::scoped_lock lock(this->stateMutex); count = this->active.size(); auto it = this->active.begin(); while (it != this->active.end()) { (*it)->Play(); ++it; } } if (count) { this->SetPlaybackState(Transport::PlaybackPlaying); return true; } return false; } double Transport::Position() { boost::recursive_mutex::scoped_lock lock(this->stateMutex); if (!this->active.empty()) { return this->active.front()->Position(); } return 0; } void Transport::SetPosition(double seconds) { boost::recursive_mutex::scoped_lock lock(this->stateMutex); if (!this->active.empty()) { this->active.front()->SetPosition(seconds); this->TimeChanged(seconds); } } double Transport::Volume() { return this->volume; } void Transport::SetVolume(double volume) { double oldVolume = this->volume; volume = std::max(0.0, std::min(1.0, volume)); this->volume = volume; if (oldVolume != this->volume) { this->VolumeChanged(); } std::string output = boost::str( boost::format("set volume %d%%") % round(volume * 100)); musik::debug::info(TAG, output); this->output->SetVolume(this->volume); } void Transport::RemoveActive(Player* player) { bool found = false; { boost::recursive_mutex::scoped_lock lock(this->stateMutex); std::list<Player*>::iterator it = std::find(this->active.begin(), this->active.end(), player); if (it != this->active.end()) { this->active.erase(it); found = true; } } /* outside of the critical section, otherwise potential deadlock */ if (found) { delete player; } } void Transport::DeletePlayers(std::list<Player*> players) { std::for_each(players.begin(), players.end(), deletePlayer); } void Transport::SetNextCanStart(bool nextCanStart) { boost::recursive_mutex::scoped_lock lock(this->stateMutex); this->nextCanStart = nextCanStart; } void Transport::OnPlaybackStarted(Player* player) { this->RaiseStreamEvent(Transport::StreamPlaying, player); this->SetPlaybackState(Transport::PlaybackPlaying); } void Transport::OnPlaybackAlmostEnded(Player* player) { this->SetNextCanStart(true); this->RaiseStreamEvent(Transport::StreamAlmostDone, player); { boost::recursive_mutex::scoped_lock lock(this->stateMutex); /* if another component configured a next player while we were playing, go ahead and get it started now. */ if (this->nextPlayer) { this->StartWithPlayer(this->nextPlayer); } } } void Transport::OnPlaybackFinished(Player* player) { this->SetNextCanStart(true); this->RaiseStreamEvent(Transport::StreamFinished, player); bool stopped = false; { boost::recursive_mutex::scoped_lock lock(this->stateMutex); bool startedNext = false; if (this->nextPlayer) { this->StartWithPlayer(this->nextPlayer); startedNext = true; } /* we're considered stopped if we were unable to automatically start the next track, and the number of players is zero... or the number of players is one, and it's the current player. remember, we free players asynchronously. */ if (!startedNext) { stopped = !this->active.size() || (this->active.size() == 1 && this->active.front() == player); } } if (stopped) { this->SetPlaybackState(Transport::PlaybackStopped); } DEFER(&Transport::RemoveActive, player); } void Transport::OnPlaybackError(Player* player) { this->SetNextCanStart(true); this->RaiseStreamEvent(Transport::StreamError, player); this->SetPlaybackState(Transport::PlaybackStopped); DEFER(&Transport::RemoveActive, player); } void Transport::SetPlaybackState(int state) { bool changed = false; { boost::recursive_mutex::scoped_lock lock(this->stateMutex); changed = (this->state != state); this->state = (PlaybackState) state; } if (changed) { this->PlaybackEvent(state); } } void Transport::RaiseStreamEvent(int type, Player* player) { this->StreamEvent(type, player->GetUrl()); } <commit_msg>Ensure Tranpsort is properly stopped after all playback has completed.<commit_after>////////////////////////////////////////////////////////////////////////////// // Copyright � 2007, Daniel �nnerby // // 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 author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #include "pch.hpp" #include <core/debug.h> #include <core/playback/Transport.h> #include <core/plugin/PluginFactory.h> #include <algorithm> #include <boost/thread.hpp> using namespace musik::core::audio; static std::string TAG = "Transport"; #define RESET_NEXT_PLAYER() \ delete this->nextPlayer; \ this->nextPlayer = NULL; #define DEFER(x, y) \ { \ boost::thread thread(boost::bind(x, this, y)); \ thread.detach(); \ } static void stopPlayer(Player* p) { p->Stop(); } static void deletePlayer(Player* p) { delete p; } Transport::Transport() : volume(1.0) , state(PlaybackStopped) , nextPlayer(NULL) , nextCanStart(false) { this->output = Player::CreateDefaultOutput(); } Transport::~Transport() { } Transport::PlaybackState Transport::GetPlaybackState() { boost::recursive_mutex::scoped_lock lock(this->stateMutex); return this->state; } void Transport::PrepareNextTrack(const std::string& trackUrl) { bool startNext = false; { boost::recursive_mutex::scoped_lock lock(this->stateMutex); this->nextPlayer = new Player(trackUrl, this->output); startNext = this->nextCanStart; } if (startNext) { this->StartWithPlayer(this->nextPlayer); } } void Transport::Start(const std::string& url) { musik::debug::info(TAG, "we were asked to start the track at " + url); Player* newPlayer = new Player(url, this->output); musik::debug::info(TAG, "Player created successfully"); this->StartWithPlayer(newPlayer); } void Transport::StartWithPlayer(Player* newPlayer) { if (newPlayer) { { boost::recursive_mutex::scoped_lock lock(this->stateMutex); bool playingNext = (newPlayer == nextPlayer); if (newPlayer != nextPlayer) { delete nextPlayer; } this->nextPlayer = NULL; /* first argument suppresses the "Stop" event from getting triggered, the second param is used for gapless playback -- we won't stop the output and will allow pending buffers to finish */ this->Stop(true, !playingNext); this->SetNextCanStart(false); newPlayer->PlaybackStarted.connect(this, &Transport::OnPlaybackStarted); newPlayer->PlaybackAlmostEnded.connect(this, &Transport::OnPlaybackAlmostEnded); newPlayer->PlaybackFinished.connect(this, &Transport::OnPlaybackFinished); newPlayer->PlaybackError.connect(this, &Transport::OnPlaybackError); musik::debug::info(TAG, "play()"); this->active.push_front(newPlayer); this->output->Resume(); newPlayer->Play(); } this->RaiseStreamEvent(Transport::StreamScheduled, newPlayer); } } void Transport::Stop() { this->Stop(false, true); } void Transport::Stop(bool suppressStopEvent, bool stopOutput) { musik::debug::info(TAG, "stop"); std::list<Player*> toDelete; { boost::recursive_mutex::scoped_lock lock(this->stateMutex); RESET_NEXT_PLAYER(); std::swap(toDelete, this->active); } /* delete these in the background to avoid deadlock in some cases where this method is implicitly triggered via Player callback. however, we should stop them immediately so they stop producing audio. */ std::for_each(toDelete.begin(), toDelete.end(), stopPlayer); DEFER(&Transport::DeletePlayers, toDelete); if (stopOutput) { /* stopping the transport will stop any buffers that are currently in flight. this makes the sound end immediately. */ this->output->Stop(); } if (!suppressStopEvent) { /* if we know we're starting another track immediately, suppress the stop event. this functionality is not available to the public interface, it's an internal optimization */ this->SetPlaybackState(PlaybackStopped); } } bool Transport::Pause() { musik::debug::info(TAG, "pause"); size_t count = 0; this->output->Pause(); { boost::recursive_mutex::scoped_lock lock(this->stateMutex); count = this->active.size(); } if (count) { this->SetPlaybackState(PlaybackPaused); return true; } return false; } bool Transport::Resume() { musik::debug::info(TAG, "resume"); this->output->Resume(); size_t count = 0; { boost::recursive_mutex::scoped_lock lock(this->stateMutex); count = this->active.size(); auto it = this->active.begin(); while (it != this->active.end()) { (*it)->Play(); ++it; } } if (count) { this->SetPlaybackState(Transport::PlaybackPlaying); return true; } return false; } double Transport::Position() { boost::recursive_mutex::scoped_lock lock(this->stateMutex); if (!this->active.empty()) { return this->active.front()->Position(); } return 0; } void Transport::SetPosition(double seconds) { boost::recursive_mutex::scoped_lock lock(this->stateMutex); if (!this->active.empty()) { this->active.front()->SetPosition(seconds); this->TimeChanged(seconds); } } double Transport::Volume() { return this->volume; } void Transport::SetVolume(double volume) { double oldVolume = this->volume; volume = std::max(0.0, std::min(1.0, volume)); this->volume = volume; if (oldVolume != this->volume) { this->VolumeChanged(); } std::string output = boost::str( boost::format("set volume %d%%") % round(volume * 100)); musik::debug::info(TAG, output); this->output->SetVolume(this->volume); } void Transport::RemoveActive(Player* player) { bool found = false; { boost::recursive_mutex::scoped_lock lock(this->stateMutex); std::list<Player*>::iterator it = std::find(this->active.begin(), this->active.end(), player); if (it != this->active.end()) { this->active.erase(it); found = true; } } /* outside of the critical section, otherwise potential deadlock */ if (found) { delete player; } } void Transport::DeletePlayers(std::list<Player*> players) { std::for_each(players.begin(), players.end(), deletePlayer); } void Transport::SetNextCanStart(bool nextCanStart) { boost::recursive_mutex::scoped_lock lock(this->stateMutex); this->nextCanStart = nextCanStart; } void Transport::OnPlaybackStarted(Player* player) { this->RaiseStreamEvent(Transport::StreamPlaying, player); this->SetPlaybackState(Transport::PlaybackPlaying); } void Transport::OnPlaybackAlmostEnded(Player* player) { this->SetNextCanStart(true); this->RaiseStreamEvent(Transport::StreamAlmostDone, player); { boost::recursive_mutex::scoped_lock lock(this->stateMutex); /* if another component configured a next player while we were playing, go ahead and get it started now. */ if (this->nextPlayer) { this->StartWithPlayer(this->nextPlayer); } } } void Transport::OnPlaybackFinished(Player* player) { this->SetNextCanStart(true); this->RaiseStreamEvent(Transport::StreamFinished, player); bool stopped = false; { boost::recursive_mutex::scoped_lock lock(this->stateMutex); bool startedNext = false; if (this->nextPlayer) { this->StartWithPlayer(this->nextPlayer); startedNext = true; } /* we're considered stopped if we were unable to automatically start the next track, and the number of players is zero... or the number of players is one, and it's the current player. remember, we free players asynchronously. */ if (!startedNext) { stopped = !this->active.size() || (this->active.size() == 1 && this->active.front() == player); } } if (stopped) { this->Stop(); } DEFER(&Transport::RemoveActive, player); } void Transport::OnPlaybackError(Player* player) { this->SetNextCanStart(true); this->RaiseStreamEvent(Transport::StreamError, player); this->SetPlaybackState(Transport::PlaybackStopped); DEFER(&Transport::RemoveActive, player); } void Transport::SetPlaybackState(int state) { bool changed = false; { boost::recursive_mutex::scoped_lock lock(this->stateMutex); changed = (this->state != state); this->state = (PlaybackState) state; } if (changed) { this->PlaybackEvent(state); } } void Transport::RaiseStreamEvent(int type, Player* player) { this->StreamEvent(type, player->GetUrl()); } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef PCL_RECOGNITION_OCCLUSION_REASONING_HPP_ #define PCL_RECOGNITION_OCCLUSION_REASONING_HPP_ #include <pcl/recognition/hv/occlusion_reasoning.h> /////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> pcl::occlusion_reasoning::ZBuffering<ModelT, SceneT>::ZBuffering (int resx, int resy, float f) : f_ (f), cx_ (resx), cy_ (resy), depth_ (NULL) { } /////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> pcl::occlusion_reasoning::ZBuffering<ModelT, SceneT>::ZBuffering () : f_ (), cx_ (), cy_ (), depth_ (NULL) { } /////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> pcl::occlusion_reasoning::ZBuffering<ModelT, SceneT>::~ZBuffering () { if (depth_ != NULL) delete[] depth_; } /////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> void pcl::occlusion_reasoning::ZBuffering<ModelT, SceneT>::filter (typename pcl::PointCloud<ModelT>::ConstPtr & model, typename pcl::PointCloud<ModelT>::Ptr & filtered, float thres) { float cx, cy; cx = static_cast<float> (cx_) / 2.f - 0.5f; cy = static_cast<float> (cy_) / 2.f - 0.5f; std::vector<int> indices_to_keep; indices_to_keep.resize (model->points.size ()); int keep = 0; for (size_t i = 0; i < model->points.size (); i++) { float x = model->points[i].x; float y = model->points[i].y; float z = model->points[i].z; int u = static_cast<int> (f_ * x / z + cx); int v = static_cast<int> (f_ * y / z + cy); if (u >= cx_ || v >= cy_ || u < 0 || v < 0) continue; //Check if point depth (distance to camera) is greater than the (u,v) meaning that the point is not visible if ((z - thres) > depth_[u * cy_ + v] || !pcl_isfinite(depth_[u * cy_ + v])) continue; indices_to_keep[keep] = static_cast<int> (i); keep++; } indices_to_keep.resize (keep); pcl::copyPointCloud (*model, indices_to_keep, *filtered); } /////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> void pcl::occlusion_reasoning::ZBuffering<ModelT, SceneT>::computeDepthMap (typename pcl::PointCloud<SceneT>::ConstPtr & scene, bool compute_focal, bool smooth, int wsize) { float cx, cy; cx = static_cast<float> (cx_) / 2.f - 0.5f; cy = static_cast<float> (cy_) / 2.f - 0.5f; //compute the focal length if (compute_focal) { float max_u, max_v, min_u, min_v; max_u = max_v = std::numeric_limits<float>::max () * -1; min_u = min_v = std::numeric_limits<float>::max (); for (size_t i = 0; i < scene->points.size (); i++) { float b_x = scene->points[i].x / scene->points[i].z; if (b_x > max_u) max_u = b_x; if (b_x < min_u) min_u = b_x; float b_y = scene->points[i].y / scene->points[i].z; if (b_y > max_v) max_v = b_y; if (b_y < min_v) min_v = b_y; } float maxC = std::max (std::max (std::abs (max_u), std::abs (max_v)), std::max (std::abs (min_u), std::abs (min_v))); f_ = (cx) / maxC; } depth_ = new float[cx_ * cy_]; for (int i = 0; i < (cx_ * cy_); i++) depth_[i] = std::numeric_limits<float>::quiet_NaN (); for (size_t i = 0; i < scene->points.size (); i++) { float x = scene->points[i].x; float y = scene->points[i].y; float z = scene->points[i].z; int u = static_cast<int> (f_ * x / z + cx); int v = static_cast<int> (f_ * y / z + cy); if (u >= cx_ || v >= cy_ || u < 0 || v < 0) continue; if ((z < depth_[u * cy_ + v]) || (!pcl_isfinite(depth_[u * cy_ + v]))) depth_[u * cx_ + v] = z; } if (smooth) { //Dilate and smooth the depth map int ws = wsize; int ws2 = std::floor (static_cast<float> (ws) / 2.f); float * depth_smooth = new float[cx_ * cy_]; for (int i = 0; i < (cx_ * cy_); i++) depth_smooth[i] = std::numeric_limits<float>::quiet_NaN (); for (int u = ws2; u < (cx_ - ws2); u++) { for (int v = ws2; v < (cy_ - ws2); v++) { float min = std::numeric_limits<float>::max (); for (int j = (u - ws2); j <= (u + ws2); j++) { for (int i = (v - ws2); i <= (v + ws2); i++) { if (pcl_isfinite(depth_[j * cx_ + i]) && (depth_[j * cx_ + i] < min)) { min = depth_[j * cx_ + i]; } } } if (min < (std::numeric_limits<float>::max () - 0.1)) { depth_smooth[u * cx_ + v] = min; } } } memcpy (depth_, depth_smooth, sizeof(float) * cx_ * cy_); delete[] depth_smooth; } } #endif // PCL_RECOGNITION_OCCLUSION_REASONING_HPP_ <commit_msg>fixed compiler warning<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef PCL_RECOGNITION_OCCLUSION_REASONING_HPP_ #define PCL_RECOGNITION_OCCLUSION_REASONING_HPP_ #include <pcl/recognition/hv/occlusion_reasoning.h> /////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> pcl::occlusion_reasoning::ZBuffering<ModelT, SceneT>::ZBuffering (int resx, int resy, float f) : f_ (f), cx_ (resx), cy_ (resy), depth_ (NULL) { } /////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> pcl::occlusion_reasoning::ZBuffering<ModelT, SceneT>::ZBuffering () : f_ (), cx_ (), cy_ (), depth_ (NULL) { } /////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> pcl::occlusion_reasoning::ZBuffering<ModelT, SceneT>::~ZBuffering () { if (depth_ != NULL) delete[] depth_; } /////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> void pcl::occlusion_reasoning::ZBuffering<ModelT, SceneT>::filter (typename pcl::PointCloud<ModelT>::ConstPtr & model, typename pcl::PointCloud<ModelT>::Ptr & filtered, float thres) { float cx, cy; cx = static_cast<float> (cx_) / 2.f - 0.5f; cy = static_cast<float> (cy_) / 2.f - 0.5f; std::vector<int> indices_to_keep; indices_to_keep.resize (model->points.size ()); int keep = 0; for (size_t i = 0; i < model->points.size (); i++) { float x = model->points[i].x; float y = model->points[i].y; float z = model->points[i].z; int u = static_cast<int> (f_ * x / z + cx); int v = static_cast<int> (f_ * y / z + cy); if (u >= cx_ || v >= cy_ || u < 0 || v < 0) continue; //Check if point depth (distance to camera) is greater than the (u,v) meaning that the point is not visible if ((z - thres) > depth_[u * cy_ + v] || !pcl_isfinite(depth_[u * cy_ + v])) continue; indices_to_keep[keep] = static_cast<int> (i); keep++; } indices_to_keep.resize (keep); pcl::copyPointCloud (*model, indices_to_keep, *filtered); } /////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> void pcl::occlusion_reasoning::ZBuffering<ModelT, SceneT>::computeDepthMap (typename pcl::PointCloud<SceneT>::ConstPtr & scene, bool compute_focal, bool smooth, int wsize) { float cx, cy; cx = static_cast<float> (cx_) / 2.f - 0.5f; cy = static_cast<float> (cy_) / 2.f - 0.5f; //compute the focal length if (compute_focal) { float max_u, max_v, min_u, min_v; max_u = max_v = std::numeric_limits<float>::max () * -1; min_u = min_v = std::numeric_limits<float>::max (); for (size_t i = 0; i < scene->points.size (); i++) { float b_x = scene->points[i].x / scene->points[i].z; if (b_x > max_u) max_u = b_x; if (b_x < min_u) min_u = b_x; float b_y = scene->points[i].y / scene->points[i].z; if (b_y > max_v) max_v = b_y; if (b_y < min_v) min_v = b_y; } float maxC = std::max (std::max (std::abs (max_u), std::abs (max_v)), std::max (std::abs (min_u), std::abs (min_v))); f_ = (cx) / maxC; } depth_ = new float[cx_ * cy_]; for (int i = 0; i < (cx_ * cy_); i++) depth_[i] = std::numeric_limits<float>::quiet_NaN (); for (size_t i = 0; i < scene->points.size (); i++) { float x = scene->points[i].x; float y = scene->points[i].y; float z = scene->points[i].z; int u = static_cast<int> (f_ * x / z + cx); int v = static_cast<int> (f_ * y / z + cy); if (u >= cx_ || v >= cy_ || u < 0 || v < 0) continue; if ((z < depth_[u * cy_ + v]) || (!pcl_isfinite(depth_[u * cy_ + v]))) depth_[u * cx_ + v] = z; } if (smooth) { //Dilate and smooth the depth map int ws = wsize; int ws2 = int (std::floor (static_cast<float> (ws) / 2.f)); float * depth_smooth = new float[cx_ * cy_]; for (int i = 0; i < (cx_ * cy_); i++) depth_smooth[i] = std::numeric_limits<float>::quiet_NaN (); for (int u = ws2; u < (cx_ - ws2); u++) { for (int v = ws2; v < (cy_ - ws2); v++) { float min = std::numeric_limits<float>::max (); for (int j = (u - ws2); j <= (u + ws2); j++) { for (int i = (v - ws2); i <= (v + ws2); i++) { if (pcl_isfinite(depth_[j * cx_ + i]) && (depth_[j * cx_ + i] < min)) { min = depth_[j * cx_ + i]; } } } if (min < (std::numeric_limits<float>::max () - 0.1)) { depth_smooth[u * cx_ + v] = min; } } } memcpy (depth_, depth_smooth, sizeof(float) * cx_ * cy_); delete[] depth_smooth; } } #endif // PCL_RECOGNITION_OCCLUSION_REASONING_HPP_ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: taskpanelist.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: ssa $ $Date: 2002-02-22 09:10:27 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SV_SVDATA_HXX #include <svdata.hxx> #endif #ifndef _RCID_H #include <rcid.h> #endif #ifndef _SV_DOCKWIN_HXX #include <dockwin.hxx> #endif #include <taskpanelist.hxx> // compares window pos left-to-right bool LTR( const Window*& w1, const Window*& w2) { Point pos1, pos2; if( w1->GetType() == RSC_DOCKINGWINDOW ) pos1 = ((DockingWindow*)w1)->GetPosPixel(); else pos1 = w1->GetPosPixel(); if( w2->GetType() == RSC_DOCKINGWINDOW ) pos2 = ((DockingWindow*)w2)->GetPosPixel(); else pos2 = w2->GetPosPixel(); if( pos1.X() == pos2.X() ) return ( pos1.Y() < pos2.Y() ); else return ( pos1.X() < pos2.X() ); } // -------------------------------------------------- TaskPaneList::TaskPaneList() { } TaskPaneList::~TaskPaneList() { } // -------------------------------------------------- void TaskPaneList::AddWindow( Window *pWindow ) { bool bDockingWindow=false; bool bToolbox=false; if( pWindow ) { if( pWindow->GetType() == RSC_DOCKINGWINDOW ) bDockingWindow = true; else if( pWindow->GetType() == RSC_TOOLBOX ) bToolbox = true; bool bFound = false; ::std::list< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( *p++ == pWindow ) { bFound = true; break; } } // avoid duplicates if( !bFound ) mTaskPanes.push_back( pWindow ); } } // -------------------------------------------------- void TaskPaneList::RemoveWindow( Window *pWindow ) { mTaskPanes.remove( pWindow ); } // -------------------------------------------------- BOOL TaskPaneList::HandleKeyEvent( KeyEvent aKeyEvent ) { KeyCode aKeyCode = aKeyEvent.GetKeyCode(); if( (aKeyCode.IsMod1() && aKeyCode.GetCode() == KEY_TAB) // Ctrl-TAB || aKeyCode.GetCode() == KEY_F6 // F6 ) { // is the focus in the list ? BOOL bHasFocus = FALSE; ::std::list< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { Window *pWin = *p; if( (*p)->HasChildPathFocus( TRUE ) ) { // activate next task pane Window *pNextWin = FindNextPane( *p ); if( pNextWin != *p ) { ImplGetSVData()->maWinData.mbNoSaveFocus = TRUE; pNextWin->GrabFocus(); ImplGetSVData()->maWinData.mbNoSaveFocus = FALSE; } return TRUE; } else p++; } } return FALSE; } // -------------------------------------------------- Window* TaskPaneList::FindNextPane( Window *pWindow ) { mTaskPanes.sort(LTR); ::std::list< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( *p == pWindow ) { unsigned n = mTaskPanes.size(); while( --n ) { if( ++p == mTaskPanes.end() ) p = mTaskPanes.begin(); if( (*p)->IsVisible() ) return *p; } break; } else ++p; } return pWindow; // nothing found } // -------------------------------------------------- <commit_msg>#652903#<commit_after>/************************************************************************* * * $RCSfile: taskpanelist.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2002-02-22 16:44:20 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SV_SVDATA_HXX #include <svdata.hxx> #endif #ifndef _RCID_H #include <rcid.h> #endif #ifndef _SV_DOCKWIN_HXX #include <dockwin.hxx> #endif #include <taskpanelist.hxx> // compares window pos left-to-right bool LTR( const Window*& w1, const Window*& w2) { Point pos1, pos2; if( w1->GetType() == RSC_DOCKINGWINDOW ) pos1 = ((DockingWindow*)w1)->GetPosPixel(); else pos1 = w1->GetPosPixel(); if( w2->GetType() == RSC_DOCKINGWINDOW ) pos2 = ((DockingWindow*)w2)->GetPosPixel(); else pos2 = w2->GetPosPixel(); if( pos1.X() == pos2.X() ) return ( pos1.Y() < pos2.Y() ); else return ( pos1.X() < pos2.X() ); } // -------------------------------------------------- TaskPaneList::TaskPaneList() { } TaskPaneList::~TaskPaneList() { } // -------------------------------------------------- void TaskPaneList::AddWindow( Window *pWindow ) { bool bDockingWindow=false; bool bToolbox=false; if( pWindow ) { if( pWindow->GetType() == RSC_DOCKINGWINDOW ) bDockingWindow = true; else if( pWindow->GetType() == RSC_TOOLBOX ) bToolbox = true; bool bFound = false; ::std::list< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( *p++ == pWindow ) { bFound = true; break; } } // avoid duplicates if( !bFound ) mTaskPanes.push_back( pWindow ); } } // -------------------------------------------------- void TaskPaneList::RemoveWindow( Window *pWindow ) { mTaskPanes.remove( pWindow ); } // -------------------------------------------------- BOOL TaskPaneList::HandleKeyEvent( KeyEvent aKeyEvent ) { KeyCode aKeyCode = aKeyEvent.GetKeyCode(); if( (aKeyCode.IsMod1() && aKeyCode.GetCode() == KEY_TAB) // Ctrl-TAB || aKeyCode.GetCode() == KEY_F6 // F6 ) { // is the focus in the list ? BOOL bHasFocus = FALSE; ::std::list< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { Window *pWin = *p; if( (*p)->HasChildPathFocus( TRUE ) ) { // activate next task pane Window *pNextWin = FindNextPane( *p ); if( pNextWin != *p ) { ImplGetSVData()->maWinData.mbNoSaveFocus = TRUE; pNextWin->GrabFocus(); ImplGetSVData()->maWinData.mbNoSaveFocus = FALSE; } return TRUE; } else p++; } } return FALSE; } // -------------------------------------------------- Window* TaskPaneList::FindNextPane( Window *pWindow ) { //mTaskPanes.sort(LTR); ::std::list< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( *p == pWindow ) { unsigned n = mTaskPanes.size(); while( --n ) { if( ++p == mTaskPanes.end() ) p = mTaskPanes.begin(); if( (*p)->IsVisible() ) return *p; } break; } else ++p; } return pWindow; // nothing found } // -------------------------------------------------- <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: gtkgdi.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2006-05-11 10:01:13 $ * * 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 _VCL_GTKGDI_HXX #define _VCL_GTKGDI_HXX #include <prex.h> #include <gtk/gtk.h> #include <gdk/gdkx.h> #include <gdk/gdkkeysyms.h> #include <postx.h> #ifndef _SV_SALGDI_H #include <salgdi.h> #endif class GtkSalGraphics : public X11SalGraphics { GtkWidget *m_pWindow; Region m_aClipRegion; public: GtkSalGraphics( GtkWidget *window ) : m_pWindow( window ), m_aClipRegion( REGION_NULL ) {} virtual ~GtkSalGraphics(); inline GtkWidget* GetGtkWidget() const { return m_pWindow; } inline GdkWindow* GetGdkWindow() const { return m_pWindow->window; } inline GtkSalFrame* GetGtkFrame() const { return static_cast<GtkSalFrame*>(m_pFrame); } // will be set when UI theme was changed static BOOL bThemeChanged; static BOOL bNeedPixmapPaint; static BOOL bGlobalNeedPixmapPaint; static BOOL bToolbarGripWorkaround; // native widget methods virtual BOOL IsNativeControlSupported( ControlType nType, ControlPart nPart ); virtual BOOL hitTestNativeControl( ControlType nType, ControlPart nPart, const Region& rControlRegion, const Point& aPos, SalControlHandle& rControlHandle, BOOL& rIsInside ); virtual BOOL drawNativeControl( ControlType nType, ControlPart nPart, const Region& rControlRegion, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, rtl::OUString aCaption ); virtual BOOL drawNativeControlText( ControlType nType, ControlPart nPart, const Region& rControlRegion, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, rtl::OUString aCaption ); virtual BOOL getNativeControlRegion( ControlType nType, ControlPart nPart, const Region& rControlRegion, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, rtl::OUString aCaption, Region &rNativeBoundingRegion, Region &rNativeContentRegion ); //helper methods for frame's UpdateSettings void updateSettings( AllSettings& rSettings ); virtual void ResetClipRegion(); virtual void BeginSetClipRegion( ULONG nCount ); virtual BOOL unionClipRegion( long nX, long nY, long nWidth, long nHeight ); virtual void EndSetClipRegion(); // some themes set the background pixmap of our window EVERY time // a control is painted; but presentation effects need // the background set to None; workaround: set the background // before copyBits virtual void copyBits( const SalTwoRect* pPosAry, SalGraphics* pSrcGraphics ); protected: typedef std::list< Rectangle > clipList; GdkPixmap* NWGetPixmapFromScreen( Rectangle srcRect ); BOOL NWRenderPixmapToScreen( GdkPixmap* pPixmap, Rectangle dstRect ); BOOL NWPaintGTKButton( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, OUString aCaption ); BOOL NWPaintGTKRadio( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, OUString aCaption ); BOOL NWPaintGTKCheck( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, OUString aCaption ); BOOL NWPaintGTKScrollbar( ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, OUString aCaption ); BOOL NWPaintGTKEditBox( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, OUString aCaption ); BOOL NWPaintGTKSpinBox( ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, OUString aCaption ); BOOL NWPaintGTKComboBox( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, OUString aCaption ); BOOL NWPaintGTKTabItem( ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, OUString aCaption ); BOOL NWPaintGTKListBox( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, OUString aCaption ); BOOL NWPaintGTKToolbar( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, OUString aCaption ); BOOL NWPaintGTKMenubar( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, OUString aCaption ); BOOL NWPaintGTKPopupMenu( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, OUString aCaption ); BOOL NWPaintGTKTooltip( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, OUString aCaption ); }; #endif // _VCL_GTKGDI_HXX <commit_msg>INTEGRATION: CWS warnings01 (1.6.70); FILE MERGED 2006/05/23 19:59:05 sb 1.6.70.3: RESYNC: (1.6-1.8); FILE MERGED 2005/11/11 14:31:20 pl 1.6.70.2: #i55991# removed warnings 2005/11/07 11:54:15 pl 1.6.70.1: #i55991# removed warnings<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: gtkgdi.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2006-06-19 19:47:44 $ * * 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 _VCL_GTKGDI_HXX #define _VCL_GTKGDI_HXX #include <prex.h> #include <gtk/gtk.h> #include <gdk/gdkx.h> #include <gdk/gdkkeysyms.h> #include <postx.h> #ifndef _SV_SALGDI_H #include <salgdi.h> #endif class GtkSalGraphics : public X11SalGraphics { GtkWidget *m_pWindow; Region m_aClipRegion; public: GtkSalGraphics( GtkWidget *window ) : m_pWindow( window ), m_aClipRegion( REGION_NULL ) {} virtual ~GtkSalGraphics(); inline GtkWidget* GetGtkWidget() const { return m_pWindow; } inline GdkWindow* GetGdkWindow() const { return m_pWindow->window; } inline GtkSalFrame* GetGtkFrame() const { return static_cast<GtkSalFrame*>(m_pFrame); } // will be set when UI theme was changed static BOOL bThemeChanged; static BOOL bNeedPixmapPaint; static BOOL bGlobalNeedPixmapPaint; static BOOL bToolbarGripWorkaround; // native widget methods virtual BOOL IsNativeControlSupported( ControlType nType, ControlPart nPart ); virtual BOOL hitTestNativeControl( ControlType nType, ControlPart nPart, const Region& rControlRegion, const Point& aPos, SalControlHandle& rControlHandle, BOOL& rIsInside ); virtual BOOL drawNativeControl( ControlType nType, ControlPart nPart, const Region& rControlRegion, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, const rtl::OUString& rCaption ); virtual BOOL drawNativeControlText( ControlType nType, ControlPart nPart, const Region& rControlRegion, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, const rtl::OUString& rCaption ); virtual BOOL getNativeControlRegion( ControlType nType, ControlPart nPart, const Region& rControlRegion, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, const rtl::OUString& rCaption, Region &rNativeBoundingRegion, Region &rNativeContentRegion ); //helper methods for frame's UpdateSettings void updateSettings( AllSettings& rSettings ); virtual void ResetClipRegion(); virtual void BeginSetClipRegion( ULONG nCount ); virtual BOOL unionClipRegion( long nX, long nY, long nWidth, long nHeight ); virtual void EndSetClipRegion(); // some themes set the background pixmap of our window EVERY time // a control is painted; but presentation effects need // the background set to None; workaround: set the background // before copyBits virtual void copyBits( const SalTwoRect* pPosAry, SalGraphics* pSrcGraphics ); protected: typedef std::list< Rectangle > clipList; GdkPixmap* NWGetPixmapFromScreen( Rectangle srcRect ); BOOL NWRenderPixmapToScreen( GdkPixmap* pPixmap, Rectangle dstRect ); BOOL NWPaintGTKButton( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, const OUString& rCaption ); BOOL NWPaintGTKRadio( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, const OUString& rCaption ); BOOL NWPaintGTKCheck( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, const OUString& rCaption ); BOOL NWPaintGTKScrollbar( ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, const OUString& rCaption ); BOOL NWPaintGTKEditBox( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, const OUString& rCaption ); BOOL NWPaintGTKSpinBox( ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, const OUString& rCaption ); BOOL NWPaintGTKComboBox( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, const OUString& rCaption ); BOOL NWPaintGTKTabItem( ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, const OUString& rCaption ); BOOL NWPaintGTKListBox( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, const OUString& rCaption ); BOOL NWPaintGTKToolbar( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, const OUString& rCaption ); BOOL NWPaintGTKMenubar( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, const OUString& rCaption ); BOOL NWPaintGTKPopupMenu( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, const OUString& rCaption ); BOOL NWPaintGTKTooltip( GdkDrawable* gdkDrawable, ControlType nType, ControlPart nPart, const Rectangle& rControlRectangle, const clipList& rClipList, ControlState nState, const ImplControlValue& aValue, SalControlHandle& rControlHandle, const OUString& rCaption ); }; #endif // _VCL_GTKGDI_HXX <|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/operators/detection_map_op.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; class DetectionMAPOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("DetectRes"), "Input(DetectRes) of DetectionMAPOp should not be null."); PADDLE_ENFORCE(ctx->HasInput("Label"), "Input(Label) of DetectionMAPOp should not be null."); PADDLE_ENFORCE( ctx->HasOutput("AccumPosCount"), "Output(AccumPosCount) of DetectionMAPOp should not be null."); PADDLE_ENFORCE( ctx->HasOutput("AccumTruePos"), "Output(AccumTruePos) of DetectionMAPOp should not be null."); PADDLE_ENFORCE( ctx->HasOutput("AccumFalsePos"), "Output(AccumFalsePos) of DetectionMAPOp should not be null."); PADDLE_ENFORCE(ctx->HasOutput("MAP"), "Output(MAP) of DetectionMAPOp should not be null."); auto det_dims = ctx->GetInputDim("DetectRes"); PADDLE_ENFORCE_EQ(det_dims.size(), 2UL, "The rank of Input(DetectRes) must be 2, " "the shape is [N, 6]."); PADDLE_ENFORCE_EQ(det_dims[1], 6UL, "The shape is of Input(DetectRes) [N, 6]."); auto label_dims = ctx->GetInputDim("Label"); PADDLE_ENFORCE_EQ(label_dims.size(), 2, "The rank of Input(Label) must be 2, " "the shape is [N, 6]."); PADDLE_ENFORCE_EQ(label_dims[1], 6, "The shape is of Input(Label) [N, 6]."); if (ctx->HasInput("PosCount")) { PADDLE_ENFORCE(ctx->HasInput("TruePos"), "Input(TruePos) of DetectionMAPOp should not be null when " "Input(TruePos) is not null."); PADDLE_ENFORCE( ctx->HasInput("FalsePos"), "Input(FalsePos) of DetectionMAPOp should not be null when " "Input(FalsePos) is not null."); } ctx->SetOutputDim("MAP", framework::make_ddim({1})); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( framework::ToDataType( ctx.Input<framework::Tensor>("DetectRes")->type()), ctx.device_context()); } }; class DetectionMAPOpMaker : public framework::OpProtoAndCheckerMaker { public: DetectionMAPOpMaker(OpProto* proto, OpAttrChecker* op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput("DetectRes", "(LoDTensor) A 2-D LoDTensor with shape [M, 6] represents the " "detections. Each row has 6 values: " "[label, confidence, xmin, ymin, xmax, ymax], M is the total " "number of detect results in this mini-batch. For each instance, " "the offsets in first dimension are called LoD, the number of " "offset is N + 1, if LoD[i + 1] - LoD[i] == 0, means there is " "no detected data."); AddInput("Label", "(LoDTensor) A 2-D LoDTensor with shape[N, 6] represents the" "Labeled ground-truth data. Each row has 6 values: " "[label, is_difficult, xmin, ymin, xmax, ymax], N is the total " "number of ground-truth data in this mini-batch. For each " "instance, the offsets in first dimension are called LoD, " "the number of offset is N + 1, if LoD[i + 1] - LoD[i] == 0, " "means there is no ground-truth data."); AddInput("HasState", "(Tensor<int>) A tensor with shape [1], 0 means ignoring input " "states, which including PosCount, TruePos, FalsePos.") .AsDispensable(); AddInput("PosCount", "(Tensor) A tensor with shape [Ncls, 1], store the " "input positive example count of each class, Ncls is the count of " "input classification. " "This input is used to pass the AccumPosCount generated by the " "previous mini-batch when the multi mini-batches cumulative " "calculation carried out. " "When the input(PosCount) is empty, the cumulative " "calculation is not carried out, and only the results of the " "current mini-batch are calculated.") .AsDispensable(); AddInput("TruePos", "(LoDTensor) A 2-D LoDTensor with shape [Ntp, 2], store the " "input true positive example of each class." "This input is used to pass the AccumTruePos generated by the " "previous mini-batch when the multi mini-batches cumulative " "calculation carried out. ") .AsDispensable(); AddInput("FalsePos", "(LoDTensor) A 2-D LoDTensor with shape [Nfp, 2], store the " "input false positive example of each class." "This input is used to pass the AccumFalsePos generated by the " "previous mini-batch when the multi mini-batches cumulative " "calculation carried out. ") .AsDispensable(); AddOutput("AccumPosCount", "(Tensor) A tensor with shape [Ncls, 1], store the " "positive example count of each class. It combines the input " "input(PosCount) and the positive example count computed from " "input(Detection) and input(Label)."); AddOutput("AccumTruePos", "(LoDTensor) A LoDTensor with shape [Ntp', 2], store the " "true positive example of each class. It combines the " "input(TruePos) and the true positive examples computed from " "input(Detection) and input(Label)."); AddOutput("AccumFalsePos", "(LoDTensor) A LoDTensor with shape [Nfp', 2], store the " "false positive example of each class. It combines the " "input(FalsePos) and the false positive examples computed from " "input(Detection) and input(Label)."); AddOutput("MAP", "(Tensor) A tensor with shape [1], store the mAP evaluate " "result of the detection."); AddAttr<int>("class_num", "(int) " "The class number."); AddAttr<int>( "background_label", "(int, defalut: 0) " "The index of background label, the background label will be ignored. " "If set to -1, then all categories will be considered.") .SetDefault(0); AddAttr<float>( "overlap_threshold", "(float) " "The lower bound jaccard overlap threshold of detection output and " "ground-truth data.") .SetDefault(.5f); AddAttr<bool>("evaluate_difficult", "(bool, default true) " "Switch to control whether the difficult data is evaluated.") .SetDefault(true); AddAttr<std::string>("ap_type", "(string, default 'integral') " "The AP algorithm type, 'integral' or '11point'.") .SetDefault("integral") .InEnum({"integral", "11point"}) .AddCustomChecker([](const std::string& ap_type) { PADDLE_ENFORCE_NE(GetAPType(ap_type), APType::kNone, "The ap_type should be 'integral' or '11point."); }); AddComment(R"DOC( Detection mAP evaluate operator. The general steps are as follows. First, calculate the true positive and false positive according to the input of detection and labels, then calculate the mAP evaluate value. Supporting '11 point' and 'integral' mAP algorithm. Please get more information from the following articles: https://sanchom.wordpress.com/tag/average-precision/ https://arxiv.org/abs/1512.02325 )DOC"); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_WITHOUT_GRADIENT(detection_map, ops::DetectionMAPOp, ops::DetectionMAPOpMaker); REGISTER_OP_CPU_KERNEL( detection_map, ops::DetectionMAPOpKernel<paddle::platform::CPUPlace, float>, ops::DetectionMAPOpKernel<paddle::platform::CPUPlace, double>); <commit_msg>Fix detection_map_op for multi-device. (#8845)<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/operators/detection_map_op.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; class DetectionMAPOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("DetectRes"), "Input(DetectRes) of DetectionMAPOp should not be null."); PADDLE_ENFORCE(ctx->HasInput("Label"), "Input(Label) of DetectionMAPOp should not be null."); PADDLE_ENFORCE( ctx->HasOutput("AccumPosCount"), "Output(AccumPosCount) of DetectionMAPOp should not be null."); PADDLE_ENFORCE( ctx->HasOutput("AccumTruePos"), "Output(AccumTruePos) of DetectionMAPOp should not be null."); PADDLE_ENFORCE( ctx->HasOutput("AccumFalsePos"), "Output(AccumFalsePos) of DetectionMAPOp should not be null."); PADDLE_ENFORCE(ctx->HasOutput("MAP"), "Output(MAP) of DetectionMAPOp should not be null."); auto det_dims = ctx->GetInputDim("DetectRes"); PADDLE_ENFORCE_EQ(det_dims.size(), 2UL, "The rank of Input(DetectRes) must be 2, " "the shape is [N, 6]."); PADDLE_ENFORCE_EQ(det_dims[1], 6UL, "The shape is of Input(DetectRes) [N, 6]."); auto label_dims = ctx->GetInputDim("Label"); PADDLE_ENFORCE_EQ(label_dims.size(), 2, "The rank of Input(Label) must be 2, " "the shape is [N, 6]."); PADDLE_ENFORCE_EQ(label_dims[1], 6, "The shape is of Input(Label) [N, 6]."); if (ctx->HasInput("PosCount")) { PADDLE_ENFORCE(ctx->HasInput("TruePos"), "Input(TruePos) of DetectionMAPOp should not be null when " "Input(TruePos) is not null."); PADDLE_ENFORCE( ctx->HasInput("FalsePos"), "Input(FalsePos) of DetectionMAPOp should not be null when " "Input(FalsePos) is not null."); } ctx->SetOutputDim("MAP", framework::make_ddim({1})); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( framework::ToDataType( ctx.Input<framework::Tensor>("DetectRes")->type()), platform::CPUPlace()); } }; class DetectionMAPOpMaker : public framework::OpProtoAndCheckerMaker { public: DetectionMAPOpMaker(OpProto* proto, OpAttrChecker* op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput("DetectRes", "(LoDTensor) A 2-D LoDTensor with shape [M, 6] represents the " "detections. Each row has 6 values: " "[label, confidence, xmin, ymin, xmax, ymax], M is the total " "number of detect results in this mini-batch. For each instance, " "the offsets in first dimension are called LoD, the number of " "offset is N + 1, if LoD[i + 1] - LoD[i] == 0, means there is " "no detected data."); AddInput("Label", "(LoDTensor) A 2-D LoDTensor with shape[N, 6] represents the" "Labeled ground-truth data. Each row has 6 values: " "[label, is_difficult, xmin, ymin, xmax, ymax], N is the total " "number of ground-truth data in this mini-batch. For each " "instance, the offsets in first dimension are called LoD, " "the number of offset is N + 1, if LoD[i + 1] - LoD[i] == 0, " "means there is no ground-truth data."); AddInput("HasState", "(Tensor<int>) A tensor with shape [1], 0 means ignoring input " "states, which including PosCount, TruePos, FalsePos.") .AsDispensable(); AddInput("PosCount", "(Tensor) A tensor with shape [Ncls, 1], store the " "input positive example count of each class, Ncls is the count of " "input classification. " "This input is used to pass the AccumPosCount generated by the " "previous mini-batch when the multi mini-batches cumulative " "calculation carried out. " "When the input(PosCount) is empty, the cumulative " "calculation is not carried out, and only the results of the " "current mini-batch are calculated.") .AsDispensable(); AddInput("TruePos", "(LoDTensor) A 2-D LoDTensor with shape [Ntp, 2], store the " "input true positive example of each class." "This input is used to pass the AccumTruePos generated by the " "previous mini-batch when the multi mini-batches cumulative " "calculation carried out. ") .AsDispensable(); AddInput("FalsePos", "(LoDTensor) A 2-D LoDTensor with shape [Nfp, 2], store the " "input false positive example of each class." "This input is used to pass the AccumFalsePos generated by the " "previous mini-batch when the multi mini-batches cumulative " "calculation carried out. ") .AsDispensable(); AddOutput("AccumPosCount", "(Tensor) A tensor with shape [Ncls, 1], store the " "positive example count of each class. It combines the input " "input(PosCount) and the positive example count computed from " "input(Detection) and input(Label)."); AddOutput("AccumTruePos", "(LoDTensor) A LoDTensor with shape [Ntp', 2], store the " "true positive example of each class. It combines the " "input(TruePos) and the true positive examples computed from " "input(Detection) and input(Label)."); AddOutput("AccumFalsePos", "(LoDTensor) A LoDTensor with shape [Nfp', 2], store the " "false positive example of each class. It combines the " "input(FalsePos) and the false positive examples computed from " "input(Detection) and input(Label)."); AddOutput("MAP", "(Tensor) A tensor with shape [1], store the mAP evaluate " "result of the detection."); AddAttr<int>("class_num", "(int) " "The class number."); AddAttr<int>( "background_label", "(int, defalut: 0) " "The index of background label, the background label will be ignored. " "If set to -1, then all categories will be considered.") .SetDefault(0); AddAttr<float>( "overlap_threshold", "(float) " "The lower bound jaccard overlap threshold of detection output and " "ground-truth data.") .SetDefault(.5f); AddAttr<bool>("evaluate_difficult", "(bool, default true) " "Switch to control whether the difficult data is evaluated.") .SetDefault(true); AddAttr<std::string>("ap_type", "(string, default 'integral') " "The AP algorithm type, 'integral' or '11point'.") .SetDefault("integral") .InEnum({"integral", "11point"}) .AddCustomChecker([](const std::string& ap_type) { PADDLE_ENFORCE_NE(GetAPType(ap_type), APType::kNone, "The ap_type should be 'integral' or '11point."); }); AddComment(R"DOC( Detection mAP evaluate operator. The general steps are as follows. First, calculate the true positive and false positive according to the input of detection and labels, then calculate the mAP evaluate value. Supporting '11 point' and 'integral' mAP algorithm. Please get more information from the following articles: https://sanchom.wordpress.com/tag/average-precision/ https://arxiv.org/abs/1512.02325 )DOC"); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_WITHOUT_GRADIENT(detection_map, ops::DetectionMAPOp, ops::DetectionMAPOpMaker); REGISTER_OP_CPU_KERNEL( detection_map, ops::DetectionMAPOpKernel<paddle::platform::CPUPlace, float>, ops::DetectionMAPOpKernel<paddle::platform::CPUPlace, double>); <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.1 2003/10/09 13:51:16 neilg * implementation of a StringPool implementation that permits thread-safe updates. This can now be used by a grammar pool that is locked so that scanners have somehwere to store information about newly-encountered URIs * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/SynchronizedStringPool.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // XMLSynchronizedStringPool: Constructors and Destructor // --------------------------------------------------------------------------- XMLSynchronizedStringPool::XMLSynchronizedStringPool(const XMLStringPool *constPool , const unsigned int modulus , MemoryManager* const manager) : XMLStringPool(modulus, manager) , fConstPool(constPool) { } XMLSynchronizedStringPool::~XMLSynchronizedStringPool() { } // --------------------------------------------------------------------------- // XMLSynchronizedStringPool: Pool management methods // --------------------------------------------------------------------------- unsigned int XMLSynchronizedStringPool::addOrFind(const XMLCh* const newString) { unsigned int id = fConstPool->getId(newString); if(id) return id; // might have to add it to our own table. // synchronize this bit { XMLMutexLock lockInit(&fMutex); id = XMLStringPool::addOrFind(newString); return id; } } bool XMLSynchronizedStringPool::exists(const XMLCh* const newString) const { if(fConstPool->exists(newString)) return true; return XMLStringPool::exists(newString); } bool XMLSynchronizedStringPool::exists(const unsigned int id) const { if (!id || (id >= fCurId+fConstPool->getStringCount())) return false; return true; } void XMLSynchronizedStringPool::flushAll() { // don't touch const pool! XMLStringPool::flushAll(); } unsigned int XMLSynchronizedStringPool::getId(const XMLCh* const toFind) const { unsigned int retVal = fConstPool->getId(toFind); if(retVal) return retVal; // make sure we return a truly unique id return XMLStringPool::getId(toFind)+fConstPool->getStringCount(); } const XMLCh* XMLSynchronizedStringPool::getValueForId(const unsigned int id) const { if (id <= fConstPool->getStringCount()) return fConstPool->getValueForId(id); return XMLStringPool::getValueForId(id-fConstPool->getStringCount()); } unsigned int XMLSynchronizedStringPool::getStringCount() const { return fCurId+fConstPool->getStringCount()-1; } XERCES_CPP_NAMESPACE_END <commit_msg>fix bug in synchronized addOrFind method; thanks to Khaled for pointing this out<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.2 2003/10/09 15:35:13 neilg * fix bug in synchronized addOrFind method; thanks to Khaled for pointing this out * * Revision 1.1 2003/10/09 13:51:16 neilg * implementation of a StringPool implementation that permits thread-safe updates. This can now be used by a grammar pool that is locked so that scanners have somehwere to store information about newly-encountered URIs * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/SynchronizedStringPool.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // XMLSynchronizedStringPool: Constructors and Destructor // --------------------------------------------------------------------------- XMLSynchronizedStringPool::XMLSynchronizedStringPool(const XMLStringPool *constPool , const unsigned int modulus , MemoryManager* const manager) : XMLStringPool(modulus, manager) , fConstPool(constPool) { } XMLSynchronizedStringPool::~XMLSynchronizedStringPool() { } // --------------------------------------------------------------------------- // XMLSynchronizedStringPool: Pool management methods // --------------------------------------------------------------------------- unsigned int XMLSynchronizedStringPool::addOrFind(const XMLCh* const newString) { unsigned int id = fConstPool->getId(newString); if(id) return id; // might have to add it to our own table. // synchronize this bit { XMLMutexLock lockInit(&fMutex); id = XMLStringPool::addOrFind(newString); return id+fConstPool->getStringCount(); } } bool XMLSynchronizedStringPool::exists(const XMLCh* const newString) const { if(fConstPool->exists(newString)) return true; return XMLStringPool::exists(newString); } bool XMLSynchronizedStringPool::exists(const unsigned int id) const { if (!id || (id >= fCurId+fConstPool->getStringCount())) return false; return true; } void XMLSynchronizedStringPool::flushAll() { // don't touch const pool! XMLStringPool::flushAll(); } unsigned int XMLSynchronizedStringPool::getId(const XMLCh* const toFind) const { unsigned int retVal = fConstPool->getId(toFind); if(retVal) return retVal; // make sure we return a truly unique id return XMLStringPool::getId(toFind)+fConstPool->getStringCount(); } const XMLCh* XMLSynchronizedStringPool::getValueForId(const unsigned int id) const { if (id <= fConstPool->getStringCount()) return fConstPool->getValueForId(id); return XMLStringPool::getValueForId(id-fConstPool->getStringCount()); } unsigned int XMLSynchronizedStringPool::getStringCount() const { return fCurId+fConstPool->getStringCount()-1; } XERCES_CPP_NAMESPACE_END <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <string> #include <vector> #include <sstream> #include "SSDB_client.h" #include "gtest/gtest.h" #include "ssdb_test.h" #include <algorithm> using namespace std; class RDBTest : public SSDBTest { public: ssdb::Status s; std::vector<std::string> list,getList; std::vector<std::string> keys; std::map<std::string, double> items; std::map<std::string, std::string> kvs; string key, val, getVal, field, dumpVal, restoreVal; uint32_t keysNum; double score, getScore; int64_t ret, ttl, counts; }; TEST_F(RDBTest, Test_rdb_base_dump_restore) { counts = rand()%9+1; key = "key";//GetRandomKey_(); field = "field";//GetRandomField_(); val = "val";//GetRandomVal_(); score = GetRandomDouble_(); string Replace = ""; ASSERT_TRUE(Replace.empty()); ttl = 0; //kv type client->del(key); client->set(key,val); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("ok",s.code())<<"string type dump error."<<endl; client->del(key); s = client->get(key, &getVal); EXPECT_EQ("not_found",s.code())<<"key should be deleted"<<endl; s = client->restore(key, ttl, dumpVal, Replace, &restoreVal); EXPECT_EQ("ok",s.code())<<"string type restore error."<<endl; s = client->get(key, &getVal); ASSERT_EQ(val, getVal)<<"string type restore wrong val!"<<endl; client->del(key); //hash kvs.clear(); keys.clear(); list.clear(); for(int n = 0;n < counts; n++){ kvs.insert(std::make_pair(field+itoa(n), val+itoa(n))); keys.push_back(field+itoa(n)); } s = client->multi_hset(key, kvs); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("ok",s.code())<<"hash type dump error."<<endl; client->del(key); s = client->restore(key, ttl, dumpVal, Replace, &restoreVal); EXPECT_EQ("ok",s.code())<<"hash type restore error."<<endl; s = client->hsize(key, &ret); ASSERT_EQ(counts, ret)<<"fail to hsize key!"<<endl; s = client->multi_hget(key, keys, &list); for(int n = 0;n < counts; n++){ ASSERT_EQ(field+itoa(n), list[0+2*n]); ASSERT_EQ(val+itoa(n), list[1+2*n]); } client->del(key); //list s = client->qpush_front(key, keys, &ret); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("ok",s.code())<<"list type dump error."<<endl; client->del(key); s = client->restore(key, ttl, dumpVal, Replace, &restoreVal); EXPECT_EQ("ok",s.code())<<"list type restore error."<<endl; s = client->qsize(key, &ret); ASSERT_EQ(counts, ret)<<"fail to qsize key!"<<endl; list.clear(); s = client->qslice(key, 0, -1, &list); sort(list.begin(), list.end()); for(std::vector<string>::iterator kit = keys.begin(), lit = list.begin();lit != list.end();kit++,lit++) { ASSERT_EQ(*kit, *lit)<<"list type restore val error."<<endl; } client->del(key); //set s = client->sadd(key, keys, &ret); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("ok",s.code())<<"set type dump error."<<endl; client->del(key); s = client->restore(key, ttl, dumpVal, Replace, &restoreVal); EXPECT_EQ("ok",s.code())<<"set type restore error."<<endl; s = client->scard(key, &ret); ASSERT_EQ(counts, ret)<<"fail to scard key!"<<endl; list.clear(); s = client->smembers(key, &list); for(std::vector<string>::iterator kit = keys.begin(), lit = list.begin();lit != list.end();kit++,lit++) { ASSERT_EQ(*kit, *lit)<<"set type restore val error."<<endl; } client->del(key); //zset items.clear(); keys.clear(); for(int n = 0;n < counts; n++){ items.insert(std::make_pair(field+itoa(n),score+n)); keys.push_back(field+itoa(n)); } s = client->zset(key, items, &ret); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("ok",s.code())<<"zset type dump error."<<endl; client->del(key); s = client->restore(key, ttl, dumpVal, Replace, &restoreVal); EXPECT_EQ("ok",s.code())<<"zset type restore error."<<endl; s = client->zsize(key, &ret); ASSERT_EQ(counts, ret)<<"fail to zsize key"<<endl; for(int n = 0;n < counts; n++){ s = client->zget(key, field+itoa(n), &getScore); ASSERT_EQ("ok", s.code()); ASSERT_NEAR(score+n, getScore, eps)<<"zset type restore score error"<<endl; } client->del(key); } TEST_F(RDBTest, Test_rdb_replace_dump_restore) { key = GetRandomKey_(); val = GetRandomVal_(); ttl = 0; string Replace = "replace"; client->del(key); client->set(key,val); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("ok",s.code())<<"string type dump error."<<endl; client->set(key,val+"exist"); s = client->restore(key, ttl, dumpVal, "", &restoreVal); EXPECT_EQ("error",s.code())<<"string type restore exist key without replace should be error."<<endl; s = client->get(key, &getVal); ASSERT_EQ(val+"exist", getVal)<<"string type restore exist key without replace should remain!"<<endl; s = client->restore(key, ttl, dumpVal, Replace, &restoreVal); EXPECT_EQ("ok",s.code())<<"string type exist key with replace restore error."<<endl; s = client->get(key, &getVal); ASSERT_EQ(val, getVal)<<"string type exist key with replace restore wrong val!"<<endl; client->del(key); } TEST_F(RDBTest, Test_rdb_ttl_dump_restore) { key = "key";//GetRandomKey_(); val = "val";//GetRandomVal_(); ttl = -1; client->del(key); client->set(key,val); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("ok",s.code())<<"string type dump error."<<endl; client->del(key); s = client->restore(key, ttl, dumpVal, "", &restoreVal); EXPECT_EQ("error",s.code())<<"string type with ttl<0 should restore error."<<endl; getVal.clear(); s = client->get(key, &getVal); ASSERT_TRUE(getVal.empty()&&s.not_found())<<"val should null! "; ttl = 5000; s = client->restore(key, ttl, dumpVal, "", &restoreVal); EXPECT_EQ("ok",s.code())<<"string type with ttl>0 restore error."<<endl; s = client->get(key, &getVal); ASSERT_EQ(val, getVal)<<"string type with ttl>0 restore wrong val!"<<endl; s = client->pttl(key, &ret); EXPECT_TRUE(ret >= 3000 && ret <= 5000)<<ret<<" ttl should near "<<ttl<<endl; client->del(key); ttl = 2569591501; s = client->restore(key, ttl, dumpVal, "", &restoreVal); EXPECT_EQ("ok",s.code())<<"string type with ttl overflow 32 bit integer restore error."<<endl; s = client->get(key, &getVal); ASSERT_EQ(val, getVal)<<"string type with ttl overflow 32 bit integer restore wrong val!"<<endl; s = client->pttl(key, &ret); EXPECT_TRUE(ret >= 2569591501-3000 && ret <= 2569591501)<<ret<<" ttl should near "<<ttl<<endl; client->del(key); } TEST_F(RDBTest, Test_rdb_syntax_dump_restore) { key = GetRandomKey_(); val = GetRandomVal_(); ttl = 0; client->del(key); client->set(key,val); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("ok",s.code())<<"string type dump error."<<endl; client->del(key); s = client->restore(key, ttl, dumpVal, "invaild", &restoreVal); EXPECT_EQ("error",s.code())<<"with invalid option should restore error."<<endl; getVal.clear(); s = client->get(key, &getVal); ASSERT_TRUE(getVal.empty()&&s.not_found())<<"val should null! "; s = client->restore(key, ttl, dumpVal+'0', "", &restoreVal); EXPECT_EQ("error",s.code())<<"with invalid serialized-value should restore error."<<endl; getVal.clear(); s = client->get(key, &getVal); ASSERT_TRUE(getVal.empty()&&s.not_found())<<"val should null! "; client->del(key); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("not_found",s.code())<<"dump non existing key should not found:"<<s.code()<<endl; EXPECT_TRUE(dumpVal.empty())<<dumpVal<<"dump non existing key return nil:"<<endl; client->del(key); } <commit_msg>[Test] dump multi threads case.<commit_after>#include <stdio.h> #include <stdlib.h> #include <string> #include <vector> #include <sstream> #include "SSDB_client.h" #include "gtest/gtest.h" #include "ssdb_test.h" #include <algorithm> using namespace std; class RDBTest : public SSDBTest { public: ssdb::Status s; static const int BIG_KEY_NUM = 10000; std::vector<std::string> list,getList; std::vector<std::string> keys; std::map<std::string, double> items; std::map<std::string, std::string> kvs; string key, val, getVal, field, dumpVal, restoreVal; uint32_t keysNum; double score, getScore; int64_t ret, ttl, counts; static void* restore_thread_func(void *arg); static const int threadsNum = 9; pthread_t bg_tid[threadsNum]; string restorekey; }; void* RDBTest::restore_thread_func(void *arg) { ssdb::Status s_restore; RDBTest* mthreadsTest = (RDBTest*)arg; ssdb::Client *tmpclient = ssdb::Client::connect(mthreadsTest->ip.data(), mthreadsTest->port); string restoreVal; if(tmpclient == NULL) { cout<<"fail to connect to server in read_thread_func!"; return (void *)NULL; } s_restore = tmpclient->restore(mthreadsTest->restorekey, 0, mthreadsTest->dumpVal, "replace", &restoreVal); if(!s_restore.ok()) { cout<<"restore key fail!"<<mthreadsTest->dumpVal.size()<<s_restore.code()<<endl; } else { cout<<"success!"<<endl; } delete tmpclient; tmpclient = NULL; return (void *)NULL; } TEST_F(RDBTest, Test_rdb_base_dump_restore) { counts = rand()%9+1; key = "key";//GetRandomKey_(); field = "field";//GetRandomField_(); val = "val";//GetRandomVal_(); score = GetRandomDouble_(); string Replace = ""; ASSERT_TRUE(Replace.empty()); ttl = 0; //kv type client->del(key); client->set(key,val); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("ok",s.code())<<"string type dump error."<<endl; client->del(key); s = client->get(key, &getVal); EXPECT_EQ("not_found",s.code())<<"key should be deleted"<<endl; s = client->restore(key, ttl, dumpVal, Replace, &restoreVal); EXPECT_EQ("ok",s.code())<<"string type restore error."<<endl; s = client->get(key, &getVal); ASSERT_EQ(val, getVal)<<"string type restore wrong val!"<<endl; client->del(key); //hash kvs.clear(); keys.clear(); list.clear(); for(int n = 0;n < counts; n++){ kvs.insert(std::make_pair(field+itoa(n), val+itoa(n))); keys.push_back(field+itoa(n)); } s = client->multi_hset(key, kvs); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("ok",s.code())<<"hash type dump error."<<endl; client->del(key); s = client->restore(key, ttl, dumpVal, Replace, &restoreVal); EXPECT_EQ("ok",s.code())<<"hash type restore error."<<endl; s = client->hsize(key, &ret); ASSERT_EQ(counts, ret)<<"fail to hsize key!"<<endl; s = client->multi_hget(key, keys, &list); for(int n = 0;n < counts; n++){ ASSERT_EQ(field+itoa(n), list[0+2*n]); ASSERT_EQ(val+itoa(n), list[1+2*n]); } client->del(key); //list s = client->qpush_front(key, keys, &ret); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("ok",s.code())<<"list type dump error."<<endl; client->del(key); s = client->restore(key, ttl, dumpVal, Replace, &restoreVal); EXPECT_EQ("ok",s.code())<<"list type restore error."<<endl; s = client->qsize(key, &ret); ASSERT_EQ(counts, ret)<<"fail to qsize key!"<<endl; list.clear(); s = client->qslice(key, 0, -1, &list); sort(list.begin(), list.end()); for(std::vector<string>::iterator kit = keys.begin(), lit = list.begin();lit != list.end();kit++,lit++) { ASSERT_EQ(*kit, *lit)<<"list type restore val error."<<endl; } client->del(key); //set s = client->sadd(key, keys, &ret); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("ok",s.code())<<"set type dump error."<<endl; client->del(key); s = client->restore(key, ttl, dumpVal, Replace, &restoreVal); EXPECT_EQ("ok",s.code())<<"set type restore error."<<endl; s = client->scard(key, &ret); ASSERT_EQ(counts, ret)<<"fail to scard key!"<<endl; list.clear(); s = client->smembers(key, &list); for(std::vector<string>::iterator kit = keys.begin(), lit = list.begin();lit != list.end();kit++,lit++) { ASSERT_EQ(*kit, *lit)<<"set type restore val error."<<endl; } client->del(key); //zset items.clear(); keys.clear(); for(int n = 0;n < counts; n++){ items.insert(std::make_pair(field+itoa(n),score+n)); keys.push_back(field+itoa(n)); } s = client->zset(key, items, &ret); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("ok",s.code())<<"zset type dump error."<<endl; client->del(key); s = client->restore(key, ttl, dumpVal, Replace, &restoreVal); EXPECT_EQ("ok",s.code())<<"zset type restore error."<<endl; s = client->zsize(key, &ret); ASSERT_EQ(counts, ret)<<"fail to zsize key"<<endl; for(int n = 0;n < counts; n++){ s = client->zget(key, field+itoa(n), &getScore); ASSERT_EQ("ok", s.code()); ASSERT_NEAR(score+n, getScore, eps)<<"zset type restore score error"<<endl; } client->del(key); } TEST_F(RDBTest, Test_rdb_replace_dump_restore) { key = GetRandomKey_(); val = GetRandomVal_(); ttl = 0; string Replace = "replace"; client->del(key); client->set(key,val); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("ok",s.code())<<"string type dump error."<<endl; client->set(key,val+"exist"); s = client->restore(key, ttl, dumpVal, "", &restoreVal); EXPECT_EQ("error",s.code())<<"string type restore exist key without replace should be error."<<endl; s = client->get(key, &getVal); ASSERT_EQ(val+"exist", getVal)<<"string type restore exist key without replace should remain!"<<endl; s = client->restore(key, ttl, dumpVal, Replace, &restoreVal); EXPECT_EQ("ok",s.code())<<"string type exist key with replace restore error."<<endl; s = client->get(key, &getVal); ASSERT_EQ(val, getVal)<<"string type exist key with replace restore wrong val!"<<endl; client->del(key); } TEST_F(RDBTest, Test_rdb_ttl_dump_restore) { key = "key";//GetRandomKey_(); val = "val";//GetRandomVal_(); ttl = -1; client->del(key); client->set(key,val); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("ok",s.code())<<"string type dump error."<<endl; client->del(key); s = client->restore(key, ttl, dumpVal, "", &restoreVal); EXPECT_EQ("error",s.code())<<"string type with ttl<0 should restore error."<<endl; getVal.clear(); s = client->get(key, &getVal); ASSERT_TRUE(getVal.empty()&&s.not_found())<<"val should null! "; ttl = 5000; s = client->restore(key, ttl, dumpVal, "", &restoreVal); EXPECT_EQ("ok",s.code())<<"string type with ttl>0 restore error."<<endl; s = client->get(key, &getVal); ASSERT_EQ(val, getVal)<<"string type with ttl>0 restore wrong val!"<<endl; s = client->pttl(key, &ret); EXPECT_TRUE(ret >= 3000 && ret <= 5000)<<ret<<" ttl should near "<<ttl<<endl; client->del(key); ttl = 2569591501; s = client->restore(key, ttl, dumpVal, "", &restoreVal); EXPECT_EQ("ok",s.code())<<"string type with ttl overflow 32 bit integer restore error."<<endl; s = client->get(key, &getVal); ASSERT_EQ(val, getVal)<<"string type with ttl overflow 32 bit integer restore wrong val!"<<endl; s = client->pttl(key, &ret); EXPECT_TRUE(ret >= 2569591501-3000 && ret <= 2569591501)<<ret<<" ttl should near "<<ttl<<endl; client->del(key); } TEST_F(RDBTest, Test_rdb_syntax_dump_restore) { key = GetRandomKey_(); val = GetRandomVal_(); ttl = 0; client->del(key); client->set(key,val); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("ok",s.code())<<"string type dump error."<<endl; client->del(key); s = client->restore(key, ttl, dumpVal, "invaild", &restoreVal); EXPECT_EQ("error",s.code())<<"with invalid option should restore error."<<endl; getVal.clear(); s = client->get(key, &getVal); ASSERT_TRUE(getVal.empty()&&s.not_found())<<"val should null! "; s = client->restore(key, ttl, dumpVal+'0', "", &restoreVal); EXPECT_EQ("error",s.code())<<"with invalid serialized-value should restore error."<<endl; getVal.clear(); s = client->get(key, &getVal); ASSERT_TRUE(getVal.empty()&&s.not_found())<<"val should null! "; client->del(key); dumpVal.clear(); s = client->dump(key, &dumpVal); EXPECT_EQ("not_found",s.code())<<"dump non existing key should not found:"<<s.code()<<endl; EXPECT_TRUE(dumpVal.empty())<<dumpVal<<"dump non existing key return nil:"<<endl; client->del(key); } TEST_F(RDBTest, Test_rdb_big_key_dump_restore) { key = "hkey"; string restorekey = "hrestorekey"; field = "field"; val = "val"; keysNum = BIG_KEY_NUM; keys.clear(); kvs.clear(); for(int n = 0;n < keysNum; n++) { keys.push_back(field+itoa(n)); kvs.insert(std::make_pair(field+itoa(n), val+itoa(n))); } client->del(key); client->multi_hset(key, kvs); string dumpVal, restoreVal; s = client->dump(key, &dumpVal); cout<<dumpVal.size()<<endl; ASSERT_TRUE(s.ok())<<"dump big key fail!"<<s.code()<<endl; s = client->restore(restorekey, 0, dumpVal, "replace", &restoreVal); ASSERT_TRUE(s.ok())<<"restore big key fail!"<<s.code()<<endl; s = client->multi_hget(restorekey, keys, &getList); for(int n = 0;n < getList.size()/2; n++){ if(field+itoa(n)!=getList[0+2*n]|| val+itoa(n)!=getList[1+2*n]) { cout<<n<<":"<<getList[0+2*n]<<":"<<getList[1+2*n]<<endl; break; } } client->multi_del(key); client->multi_del(restorekey); } TEST_F(RDBTest, Test_rdb_big_key_mthreads_dump_restore) { key = "hkey"; restorekey = "hrestorekey"; field = "field"; val = "val"; keysNum = BIG_KEY_NUM; keys.clear(); kvs.clear(); for(int n = 0;n < keysNum; n++) { keys.push_back(field+itoa(n)); kvs.insert(std::make_pair(field+itoa(n), val+itoa(n))); } client->del(key); client->multi_hset(key, kvs); s = client->dump(key, &dumpVal); cout<<dumpVal.size()<<endl; ASSERT_TRUE(s.ok())<<"dump big key fail!"<<s.code()<<endl; for(int n = 0; n < threadsNum; n++) { pthread_create(&bg_tid[n], NULL, &restore_thread_func, this); usleep(1000); } void * status; for(int n = 0; n < threadsNum; n++) { pthread_join(bg_tid[n], &status); } s = client->del(key); s = client->del(restorekey); } <|endoftext|>
<commit_before>// Copyright (c) 2007-2008 Facebook // // 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. // // See accompanying file LICENSE or visit the Scribe site at: // http://developers.facebook.com/scribe/ // // @author Bobby Johnson // @author James Wang // @author Jason Sobel // @author Avinash Lakshman #include "common.h" #include "scribe_server.h" #include "conn_pool.h" using std::string; using std::ostringstream; using std::map; using boost::shared_ptr; using namespace apache::thrift; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace apache::thrift::server; using namespace scribe::thrift; ConnPool::ConnPool() : defThresholdBeforeReconnect(-1) { pthread_mutex_init(&mapMutex, NULL); } ConnPool::ConnPool(msg_threshold_map_t *msgThresholdMap_, int defaultThreshold_, int allowableDelta_) : defThresholdBeforeReconnect(defaultThreshold_), allowableDeltaBeforeReconnect(allowableDelta_), msgThresholdMap(msgThresholdMap_) { pthread_mutex_init(&mapMutex, NULL); } ConnPool::~ConnPool() { pthread_mutex_destroy(&mapMutex); } string ConnPool::makeKey(const string& hostname, unsigned long port) { string key(hostname); key += ":"; ostringstream oss; oss << port; key += oss.str(); return key; } bool ConnPool::open(const string& hostname, unsigned long port, int timeout) { int msgThreshold = msgThresholdMap->count(ConnPool::makeKey(hostname, port)) ? msgThresholdMap->find(ConnPool::makeKey(hostname, port))->second : defThresholdBeforeReconnect; if (msgThreshold > 0 && msgThreshold > allowableDeltaBeforeReconnect) { msgThreshold += 2 * (rand() % allowableDeltaBeforeReconnect) - allowableDeltaBeforeReconnect; } return openCommon(makeKey(hostname, port), shared_ptr<scribeConn>(new scribeConn(hostname, port, timeout, msgThreshold))); } bool ConnPool::open(const string &service, const server_vector_t &servers, int timeout) { return openCommon(service, shared_ptr<scribeConn>(new scribeConn(service, servers, timeout, defThresholdBeforeReconnect))); } void ConnPool::close(const string& hostname, unsigned long port) { closeCommon(makeKey(hostname, port)); } void ConnPool::close(const string &service) { closeCommon(service); } int ConnPool::send(const string& hostname, unsigned long port, shared_ptr<logentry_vector_t> messages) { return sendCommon(makeKey(hostname, port), messages); } int ConnPool::send(const string &service, shared_ptr<logentry_vector_t> messages) { return sendCommon(service, messages); } bool ConnPool::openCommon(const string &key, shared_ptr<scribeConn> conn) { #define RETURN(x) {pthread_mutex_unlock(&mapMutex); return(x);} // note on locking: // The mapMutex locks all reads and writes to the connMap. // The locks on each connection serialize writes and deletion. // The lock on a connection doesn't protect its refcount, as refcounts // are only accessed under the mapMutex. // mapMutex MUST be held before attempting to lock particular connection pthread_mutex_lock(&mapMutex); conn_map_t::iterator iter = connMap.find(key); if (iter != connMap.end()) { shared_ptr<scribeConn> old_conn = (*iter).second; if (old_conn->isOpen()) { old_conn->addRef(); RETURN(true); } if (conn->open()) { LOG_OPER("CONN_POOL: switching to a new connection <%s>", key.c_str()); conn->setRef(old_conn->getRef()); conn->addRef(); // old connection will be magically deleted by shared_ptr connMap[key] = conn; RETURN(true); } RETURN(false); } // don't need to lock the conn yet, because no one know about // it until we release the mapMutex if (conn->open()) { // ref count starts at one, so don't addRef here connMap[key] = conn; RETURN(true); } // conn object that failed to open is deleted RETURN(false); #undef RETURN } void ConnPool::closeCommon(const string &key) { pthread_mutex_lock(&mapMutex); conn_map_t::iterator iter = connMap.find(key); if (iter != connMap.end()) { (*iter).second->releaseRef(); if ((*iter).second->getRef() <= 0) { (*iter).second->lock(); (*iter).second->close(); (*iter).second->unlock(); connMap.erase(iter); } } else { // This can be bad. If one client double closes then other cleints are screwed LOG_OPER("LOGIC ERROR: attempting to close connection <%s> that connPool has no entry for", key.c_str()); } pthread_mutex_unlock(&mapMutex); } int ConnPool::sendCommon(const string &key, shared_ptr<logentry_vector_t> messages) { pthread_mutex_lock(&mapMutex); conn_map_t::iterator iter = connMap.find(key); if (iter != connMap.end()) { (*iter).second->lock(); pthread_mutex_unlock(&mapMutex); int result = (*iter).second->send(messages); (*iter).second->unlock(); return result; } else { LOG_OPER("send failed. No connection pool entry for <%s>", key.c_str()); pthread_mutex_unlock(&mapMutex); return (CONN_FATAL); } } scribeConn::scribeConn(const string& hostname, unsigned long port, int timeout_, int msgThresholdBeforeReconnect_) : refCount(1), serviceBased(false), remoteHost(hostname), remotePort(port), timeout(timeout_), lastHeartbeat(time(NULL)), msgThresholdBeforeReconnect(msgThresholdBeforeReconnect_) { pthread_mutex_init(&mutex, NULL); #ifdef USE_ZOOKEEPER zkRegistrationZnode = hostname; #endif } scribeConn::scribeConn(const string& service, const server_vector_t &servers, int timeout_, int msgThresholdBeforeReconnect_) : refCount(1), serviceBased(true), serviceName(service), serverList(servers), timeout(timeout_), lastHeartbeat(time(NULL)), msgThresholdBeforeReconnect(msgThresholdBeforeReconnect_) { pthread_mutex_init(&mutex, NULL); } scribeConn::~scribeConn() { pthread_mutex_destroy(&mutex); } void scribeConn::addRef() { ++refCount; } void scribeConn::releaseRef() { --refCount; } unsigned scribeConn::getRef() { return refCount; } void scribeConn::setRef(unsigned r) { refCount = r; } void scribeConn::lock() { pthread_mutex_lock(&mutex); } void scribeConn::unlock() { pthread_mutex_unlock(&mutex); } bool scribeConn::isOpen() { return framedTransport->isOpen(); } bool scribeConn::open() { try { #ifdef USE_ZOOKEEPER if (0 == zkRegistrationZnode.find("zk://")) { string parentZnode = zkRegistrationZnode.substr(5, string::npos); if (g_ZKClient->getRemoteScribe(parentZnode, remoteHost, remotePort)) { LOG_OPER("Got remote scribe from zookeeper <%s:%lu>", remoteHost.c_str(), remotePort); } else { LOG_OPER("Unable to get a remote Scribe from %s", zkRegistrationZnode.c_str()); } } #endif socket = serviceBased ? shared_ptr<TSocket>(new TSocketPool(serverList)) : shared_ptr<TSocket>(new TSocket(remoteHost, remotePort)); if (!socket) { throw std::runtime_error("Failed to create socket"); } socket->setConnTimeout(timeout); socket->setRecvTimeout(timeout); socket->setSendTimeout(timeout); /* Turn off SO_LINGER (rely on the TCP stack in the kernel to do the right * thing on close()). * * By default, a TSocket has SO_LINGER turned on, with no timeout. * This means that a close() returns immediately and the underlying stack * discards any unsent data, and sends a RST (reset) to the peer. * * This is bad for multiple reasons. The implementation of SO_LINGER is OS * dependent (not always clear of the side effects) and it will confuse the * Network Store clients (will trigger IOException). * * See related issue https://issues.apache.org/jira/browse/THRIFT-748. */ socket->setLinger(false, 0); framedTransport = shared_ptr<TFramedTransport>(new TFramedTransport(socket)); if (!framedTransport) { throw std::runtime_error("Failed to create framed transport"); } protocol = shared_ptr<TBinaryProtocol>(new TBinaryProtocol(framedTransport)); if (!protocol) { throw std::runtime_error("Failed to create protocol"); } protocol->setStrict(false, false); resendClient = shared_ptr<scribeClient>(new scribeClient(protocol)); if (!resendClient) { throw std::runtime_error("Failed to create network client"); } framedTransport->open(); if (serviceBased) { remoteHost = socket->getPeerHost(); } } catch (const TTransportException& ttx) { LOG_OPER("failed to open connection to remote scribe server %s thrift error <%s>", connectionString().c_str(), ttx.what()); return false; } catch (const std::exception& stx) { LOG_OPER("failed to open connection to remote scribe server %s std error <%s>", connectionString().c_str(), stx.what()); return false; } LOG_OPER("Opened connection to remote scribe server %s", connectionString().c_str()); return true; } void scribeConn::close() { try { LOG_DEBUG("Closing connection to remote scribe server %s", connectionString().c_str()); framedTransport->close(); } catch (const TTransportException& ttx) { LOG_OPER("error <%s> while closing connection to remote scribe server %s", ttx.what(), connectionString().c_str()); } } /** * Reopen connection if needed: if max_msg_before_reconnect has been set and * the number of messages sent to a single peer is greater than this threshold, * force a disconnect and reopen a connection. * This can be needed for load balancing and fault tolerance, where a set of * servers constitute the Network Store and are all behind a load balancer or * a single DNS (DNS round robin). */ void scribeConn::reopenConnectionIfNeeded() { if (msgThresholdBeforeReconnect > 0 && sentSinceLastReconnect > msgThresholdBeforeReconnect) { LOG_OPER("Sent <%ld> messages since last reconnect to %s, threshold is <%d>, re-opening the connection", sentSinceLastReconnect, connectionString().c_str(), msgThresholdBeforeReconnect); if (isOpen()) { close(); } else { LOG_OPER("Cannot close the current connection with %s, connection doesn't seem open", connectionString().c_str()); } if (!isOpen()) { open(); // Reset counter for number of messages sent between two reconnections sentSinceLastReconnect = 0; g_Handler->incCounter(NUMBER_OF_RECONNECTS, 1); } else { LOG_OPER("Cannot re-open the connection with %s, connection seems open already", connectionString().c_str()); } } } int scribeConn::send(boost::shared_ptr<logentry_vector_t> messages) { bool fatal; int size = messages->size(); if (size <= 0) { LOG_DEBUG("[%s] DEBUG: send called with no messages.", connectionString().c_str()); return CONN_OK; } if (!isOpen()) { if (!open()) { return (CONN_FATAL); } } // Copy the vector of pointers to a vector of objects // This is because thrift doesn't support vectors of pointers, // but we need to use them internally to avoid even more copies. std::vector<LogEntry> msgs; map<string, int> categorySendCounts; msgs.reserve(size); for (logentry_vector_t::iterator iter = messages->begin(); iter != messages->end(); ++iter) { msgs.push_back(**iter); categorySendCounts[(*iter)->category] += 1; } ResultCode result = TRY_LATER; try { result = resendClient->Log(msgs); if (result == OK) { sentSinceLastReconnect += size; g_Handler->incCounter("sent", size); // Periodically log sent message stats. While these statistics are // available as counters they may not be being collected, and serve // as heartbeats useful when diagnosing issues. for (map<string, int>::iterator it = categorySendCounts.begin(); it != categorySendCounts.end(); ++it) { sendCounts[it->first + ":" + g_Handler->resultCodeToString(result)] += it->second; } time_t now = time(NULL); if (now - lastHeartbeat > 60) { for (map<string, int>::iterator it2 = sendCounts.begin(); it2 != sendCounts.end(); ++it2) { LOG_OPER("Send counts %s: %s=%d", connectionString().c_str(), it2->first.c_str(), it2->second); } sendCounts.clear(); lastHeartbeat = now; } LOG_OPER("Successfully sent <%d> messages to remote scribe server %s (<%ld> since last reconnection)", size, connectionString().c_str(), sentSinceLastReconnect); reopenConnectionIfNeeded(); return (CONN_OK); } fatal = false; LOG_OPER("Failed to send <%d> messages, remote scribe server %s " "returned error code <%d>", size, connectionString().c_str(), (int) result); } catch (const TTransportException& ttx) { fatal = true; LOG_OPER("Failed to send <%d> messages to remote scribe server %s " "error <%s>", size, connectionString().c_str(), ttx.what()); } catch (...) { fatal = true; LOG_OPER("Unknown exception sending <%d> messages to remote scribe " "server %s", size, connectionString().c_str()); } /* * If this is a serviceBased connection then close it. We might * be lucky and get another service when we reopen this connection. * If the IP:port of the remote is fixed then no point closing this * connection ... we are going to get the same connection back. */ if (serviceBased || fatal) { close(); return (CONN_FATAL); } return (CONN_TRANSIENT); } std::string scribeConn::connectionString() { if (serviceBased) { return "<" + remoteHost + " Service: " + serviceName + ">"; } else { char port[10]; snprintf(port, 10, "%lu", remotePort); return "<" + remoteHost + ":" + string(port) + ">"; } } <commit_msg>reduce log chatter by bumping "successfully sent messages" message to LOG_DEBUG<commit_after>// Copyright (c) 2007-2008 Facebook // // 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. // // See accompanying file LICENSE or visit the Scribe site at: // http://developers.facebook.com/scribe/ // // @author Bobby Johnson // @author James Wang // @author Jason Sobel // @author Avinash Lakshman #include "common.h" #include "scribe_server.h" #include "conn_pool.h" using std::string; using std::ostringstream; using std::map; using boost::shared_ptr; using namespace apache::thrift; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace apache::thrift::server; using namespace scribe::thrift; ConnPool::ConnPool() : defThresholdBeforeReconnect(-1) { pthread_mutex_init(&mapMutex, NULL); } ConnPool::ConnPool(msg_threshold_map_t *msgThresholdMap_, int defaultThreshold_, int allowableDelta_) : defThresholdBeforeReconnect(defaultThreshold_), allowableDeltaBeforeReconnect(allowableDelta_), msgThresholdMap(msgThresholdMap_) { pthread_mutex_init(&mapMutex, NULL); } ConnPool::~ConnPool() { pthread_mutex_destroy(&mapMutex); } string ConnPool::makeKey(const string& hostname, unsigned long port) { string key(hostname); key += ":"; ostringstream oss; oss << port; key += oss.str(); return key; } bool ConnPool::open(const string& hostname, unsigned long port, int timeout) { int msgThreshold = msgThresholdMap->count(ConnPool::makeKey(hostname, port)) ? msgThresholdMap->find(ConnPool::makeKey(hostname, port))->second : defThresholdBeforeReconnect; if (msgThreshold > 0 && msgThreshold > allowableDeltaBeforeReconnect) { msgThreshold += 2 * (rand() % allowableDeltaBeforeReconnect) - allowableDeltaBeforeReconnect; } return openCommon(makeKey(hostname, port), shared_ptr<scribeConn>(new scribeConn(hostname, port, timeout, msgThreshold))); } bool ConnPool::open(const string &service, const server_vector_t &servers, int timeout) { return openCommon(service, shared_ptr<scribeConn>(new scribeConn(service, servers, timeout, defThresholdBeforeReconnect))); } void ConnPool::close(const string& hostname, unsigned long port) { closeCommon(makeKey(hostname, port)); } void ConnPool::close(const string &service) { closeCommon(service); } int ConnPool::send(const string& hostname, unsigned long port, shared_ptr<logentry_vector_t> messages) { return sendCommon(makeKey(hostname, port), messages); } int ConnPool::send(const string &service, shared_ptr<logentry_vector_t> messages) { return sendCommon(service, messages); } bool ConnPool::openCommon(const string &key, shared_ptr<scribeConn> conn) { #define RETURN(x) {pthread_mutex_unlock(&mapMutex); return(x);} // note on locking: // The mapMutex locks all reads and writes to the connMap. // The locks on each connection serialize writes and deletion. // The lock on a connection doesn't protect its refcount, as refcounts // are only accessed under the mapMutex. // mapMutex MUST be held before attempting to lock particular connection pthread_mutex_lock(&mapMutex); conn_map_t::iterator iter = connMap.find(key); if (iter != connMap.end()) { shared_ptr<scribeConn> old_conn = (*iter).second; if (old_conn->isOpen()) { old_conn->addRef(); RETURN(true); } if (conn->open()) { LOG_OPER("CONN_POOL: switching to a new connection <%s>", key.c_str()); conn->setRef(old_conn->getRef()); conn->addRef(); // old connection will be magically deleted by shared_ptr connMap[key] = conn; RETURN(true); } RETURN(false); } // don't need to lock the conn yet, because no one know about // it until we release the mapMutex if (conn->open()) { // ref count starts at one, so don't addRef here connMap[key] = conn; RETURN(true); } // conn object that failed to open is deleted RETURN(false); #undef RETURN } void ConnPool::closeCommon(const string &key) { pthread_mutex_lock(&mapMutex); conn_map_t::iterator iter = connMap.find(key); if (iter != connMap.end()) { (*iter).second->releaseRef(); if ((*iter).second->getRef() <= 0) { (*iter).second->lock(); (*iter).second->close(); (*iter).second->unlock(); connMap.erase(iter); } } else { // This can be bad. If one client double closes then other cleints are screwed LOG_OPER("LOGIC ERROR: attempting to close connection <%s> that connPool has no entry for", key.c_str()); } pthread_mutex_unlock(&mapMutex); } int ConnPool::sendCommon(const string &key, shared_ptr<logentry_vector_t> messages) { pthread_mutex_lock(&mapMutex); conn_map_t::iterator iter = connMap.find(key); if (iter != connMap.end()) { (*iter).second->lock(); pthread_mutex_unlock(&mapMutex); int result = (*iter).second->send(messages); (*iter).second->unlock(); return result; } else { LOG_OPER("send failed. No connection pool entry for <%s>", key.c_str()); pthread_mutex_unlock(&mapMutex); return (CONN_FATAL); } } scribeConn::scribeConn(const string& hostname, unsigned long port, int timeout_, int msgThresholdBeforeReconnect_) : refCount(1), serviceBased(false), remoteHost(hostname), remotePort(port), timeout(timeout_), lastHeartbeat(time(NULL)), msgThresholdBeforeReconnect(msgThresholdBeforeReconnect_) { pthread_mutex_init(&mutex, NULL); #ifdef USE_ZOOKEEPER zkRegistrationZnode = hostname; #endif } scribeConn::scribeConn(const string& service, const server_vector_t &servers, int timeout_, int msgThresholdBeforeReconnect_) : refCount(1), serviceBased(true), serviceName(service), serverList(servers), timeout(timeout_), lastHeartbeat(time(NULL)), msgThresholdBeforeReconnect(msgThresholdBeforeReconnect_) { pthread_mutex_init(&mutex, NULL); } scribeConn::~scribeConn() { pthread_mutex_destroy(&mutex); } void scribeConn::addRef() { ++refCount; } void scribeConn::releaseRef() { --refCount; } unsigned scribeConn::getRef() { return refCount; } void scribeConn::setRef(unsigned r) { refCount = r; } void scribeConn::lock() { pthread_mutex_lock(&mutex); } void scribeConn::unlock() { pthread_mutex_unlock(&mutex); } bool scribeConn::isOpen() { return framedTransport->isOpen(); } bool scribeConn::open() { try { #ifdef USE_ZOOKEEPER if (0 == zkRegistrationZnode.find("zk://")) { string parentZnode = zkRegistrationZnode.substr(5, string::npos); if (g_ZKClient->getRemoteScribe(parentZnode, remoteHost, remotePort)) { LOG_OPER("Got remote scribe from zookeeper <%s:%lu>", remoteHost.c_str(), remotePort); } else { LOG_OPER("Unable to get a remote Scribe from %s", zkRegistrationZnode.c_str()); } } #endif socket = serviceBased ? shared_ptr<TSocket>(new TSocketPool(serverList)) : shared_ptr<TSocket>(new TSocket(remoteHost, remotePort)); if (!socket) { throw std::runtime_error("Failed to create socket"); } socket->setConnTimeout(timeout); socket->setRecvTimeout(timeout); socket->setSendTimeout(timeout); /* Turn off SO_LINGER (rely on the TCP stack in the kernel to do the right * thing on close()). * * By default, a TSocket has SO_LINGER turned on, with no timeout. * This means that a close() returns immediately and the underlying stack * discards any unsent data, and sends a RST (reset) to the peer. * * This is bad for multiple reasons. The implementation of SO_LINGER is OS * dependent (not always clear of the side effects) and it will confuse the * Network Store clients (will trigger IOException). * * See related issue https://issues.apache.org/jira/browse/THRIFT-748. */ socket->setLinger(false, 0); framedTransport = shared_ptr<TFramedTransport>(new TFramedTransport(socket)); if (!framedTransport) { throw std::runtime_error("Failed to create framed transport"); } protocol = shared_ptr<TBinaryProtocol>(new TBinaryProtocol(framedTransport)); if (!protocol) { throw std::runtime_error("Failed to create protocol"); } protocol->setStrict(false, false); resendClient = shared_ptr<scribeClient>(new scribeClient(protocol)); if (!resendClient) { throw std::runtime_error("Failed to create network client"); } framedTransport->open(); if (serviceBased) { remoteHost = socket->getPeerHost(); } } catch (const TTransportException& ttx) { LOG_OPER("failed to open connection to remote scribe server %s thrift error <%s>", connectionString().c_str(), ttx.what()); return false; } catch (const std::exception& stx) { LOG_OPER("failed to open connection to remote scribe server %s std error <%s>", connectionString().c_str(), stx.what()); return false; } LOG_OPER("Opened connection to remote scribe server %s", connectionString().c_str()); return true; } void scribeConn::close() { try { LOG_DEBUG("Closing connection to remote scribe server %s", connectionString().c_str()); framedTransport->close(); } catch (const TTransportException& ttx) { LOG_OPER("error <%s> while closing connection to remote scribe server %s", ttx.what(), connectionString().c_str()); } } /** * Reopen connection if needed: if max_msg_before_reconnect has been set and * the number of messages sent to a single peer is greater than this threshold, * force a disconnect and reopen a connection. * This can be needed for load balancing and fault tolerance, where a set of * servers constitute the Network Store and are all behind a load balancer or * a single DNS (DNS round robin). */ void scribeConn::reopenConnectionIfNeeded() { if (msgThresholdBeforeReconnect > 0 && sentSinceLastReconnect > msgThresholdBeforeReconnect) { LOG_OPER("Sent <%ld> messages since last reconnect to %s, threshold is <%d>, re-opening the connection", sentSinceLastReconnect, connectionString().c_str(), msgThresholdBeforeReconnect); if (isOpen()) { close(); } else { LOG_OPER("Cannot close the current connection with %s, connection doesn't seem open", connectionString().c_str()); } if (!isOpen()) { open(); // Reset counter for number of messages sent between two reconnections sentSinceLastReconnect = 0; g_Handler->incCounter(NUMBER_OF_RECONNECTS, 1); } else { LOG_OPER("Cannot re-open the connection with %s, connection seems open already", connectionString().c_str()); } } } int scribeConn::send(boost::shared_ptr<logentry_vector_t> messages) { bool fatal; int size = messages->size(); if (size <= 0) { LOG_DEBUG("[%s] DEBUG: send called with no messages.", connectionString().c_str()); return CONN_OK; } if (!isOpen()) { if (!open()) { return (CONN_FATAL); } } // Copy the vector of pointers to a vector of objects // This is because thrift doesn't support vectors of pointers, // but we need to use them internally to avoid even more copies. std::vector<LogEntry> msgs; map<string, int> categorySendCounts; msgs.reserve(size); for (logentry_vector_t::iterator iter = messages->begin(); iter != messages->end(); ++iter) { msgs.push_back(**iter); categorySendCounts[(*iter)->category] += 1; } ResultCode result = TRY_LATER; try { result = resendClient->Log(msgs); if (result == OK) { sentSinceLastReconnect += size; g_Handler->incCounter("sent", size); // Periodically log sent message stats. While these statistics are // available as counters they may not be being collected, and serve // as heartbeats useful when diagnosing issues. for (map<string, int>::iterator it = categorySendCounts.begin(); it != categorySendCounts.end(); ++it) { sendCounts[it->first + ":" + g_Handler->resultCodeToString(result)] += it->second; } time_t now = time(NULL); if (now - lastHeartbeat > 60) { for (map<string, int>::iterator it2 = sendCounts.begin(); it2 != sendCounts.end(); ++it2) { LOG_OPER("Send counts %s: %s=%d", connectionString().c_str(), it2->first.c_str(), it2->second); } sendCounts.clear(); lastHeartbeat = now; } LOG_DEBUG("Successfully sent <%d> messages to remote scribe server %s (<%ld> since last reconnection)", size, connectionString().c_str(), sentSinceLastReconnect); reopenConnectionIfNeeded(); return (CONN_OK); } fatal = false; LOG_OPER("Failed to send <%d> messages, remote scribe server %s " "returned error code <%d>", size, connectionString().c_str(), (int) result); } catch (const TTransportException& ttx) { fatal = true; LOG_OPER("Failed to send <%d> messages to remote scribe server %s " "error <%s>", size, connectionString().c_str(), ttx.what()); } catch (...) { fatal = true; LOG_OPER("Unknown exception sending <%d> messages to remote scribe " "server %s", size, connectionString().c_str()); } /* * If this is a serviceBased connection then close it. We might * be lucky and get another service when we reopen this connection. * If the IP:port of the remote is fixed then no point closing this * connection ... we are going to get the same connection back. */ if (serviceBased || fatal) { close(); return (CONN_FATAL); } return (CONN_TRANSIENT); } std::string scribeConn::connectionString() { if (serviceBased) { return "<" + remoteHost + " Service: " + serviceName + ">"; } else { char port[10]; snprintf(port, 10, "%lu", remotePort); return "<" + remoteHost + ":" + string(port) + ">"; } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // // This file is part of Swift2D. // // // // Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer // // // //////////////////////////////////////////////////////////////////////////////// // includes ------------------------------------------------------------------- #include <swift2d/particles/ParticleUpdateShader.hpp> namespace swift { //////////////////////////////////////////////////////////////////////////////// ParticleUpdateShader::ParticleUpdateShader() : Shader( R"( // vertex shader --------------------------------------------------------- @include "version" layout(location=0) in vec2 position; layout(location=1) in vec2 velocity; layout(location=2) in vec2 life; layout(location=3) in vec2 rotation; out vec2 varying_position; out vec2 varying_velocity; out vec2 varying_life; out vec2 varying_rotation; void main(void) { varying_position = position; varying_velocity = velocity; varying_life = life; varying_rotation = rotation; } )", "", // empty fragment shader R"( // geometry shader ------------------------------------------------------- @include "version" layout(points) in; layout(points) out; layout(max_vertices = 50) out; in vec2 varying_position[]; in vec2 varying_velocity[]; in vec2 varying_life[]; in vec2 varying_rotation[]; // general uniforms uniform vec2 time; // x: frame time y: total time [millisec] // spawn uniforms uniform sampler2D noise_tex; uniform int spawn_count; uniform vec3 transform[50]; // xy: pos z: rot uniform vec2 life; // x: life y: life variance [sec] uniform vec2 velocity; // x: velocity y: velocity variance uniform vec2 rotation; // x: rotation y: rotation variance uniform vec2 pos_rot_variance; // update uniforms uniform sampler2D gravity_map; uniform mat3 projection; uniform vec3 dynamics; // x: mass y: linear damp z: angular damp out vec2 out_position; out vec2 out_velocity; out vec2 out_life; out vec2 out_rotation; vec3 get_random(float seed) { seed = mod(seed, 10); return (texture(noise_tex, vec2(seed*1.3, seed*2.1)).xyz - 0.5) * 2.0; } void main(void) { if (spawn_count >= 0) { // spawn new particles ----------------------------------------------- for (int i=0; i<spawn_count; ++i) { float delta = 1.0*i/spawn_count; vec3 random = get_random((i+1)*time.y); float l = life.x + random.x * life.y; float d = transform[i].z + random.y * pos_rot_variance.y; float v = velocity.x + random.z * velocity.y; float r = rotation.x + random.z * rotation.y; out_position = transform[i].xy + random.xy*pos_rot_variance.x; out_life = vec2(0, l*1000.0); out_velocity = vec2(cos(d), sin(d)) * v; out_rotation = vec2(d, r); EmitVertex(); EndPrimitive(); } } else { // update existing particles ----------------------------------------- if (varying_life[0].x < 1) { vec2 texcoords = ((projection * vec3(varying_position[0], 1)).xy + 1.0) * 0.5; float clip_dist = 0.3; if (texcoords.x > -clip_dist && texcoords.y > -clip_dist && texcoords.x < 1+clip_dist && texcoords.y < 1+clip_dist) { vec2 gravity = (texture(gravity_map, texcoords).rg - 0.5) * dynamics.x; out_position = varying_position[0] + varying_velocity[0] * time.x / 1000; out_life = vec2(varying_life[0].x + time.x/varying_life[0].y, varying_life[0].y); out_velocity = (varying_velocity[0] + gravity*time.x*0.1) - 0.1 * varying_velocity[0] * dynamics.y * time.x; out_rotation = vec2(varying_rotation[0].x + varying_rotation[0].y * time.x / 1000, varying_rotation[0].y - 0.01 * varying_rotation[0].y * dynamics.z * time.x); EmitVertex(); EndPrimitive(); } } } } )", {"out_position", "out_velocity", "out_life", "out_rotation"} ) , time(get_uniform<math::vec2>("time")) , noise_tex(get_uniform<int>("noise_tex")) , spawn_count(get_uniform<int>("spawn_count")) , transform(get_uniform<math::vec3>("transform")) , life(get_uniform<math::vec2>("life")) , pos_rot_variance(get_uniform<math::vec2>("pos_rot_variance")) , velocity(get_uniform<math::vec2>("velocity")) , rotation(get_uniform<math::vec2>("rotation")) , gravity_map(get_uniform<int>("gravity_map")) , projection(get_uniform<math::mat3>("projection")) , dynamics(get_uniform<math::vec3>("dynamics")) {} //////////////////////////////////////////////////////////////////////////////// } <commit_msg>fixed life variance bug<commit_after>//////////////////////////////////////////////////////////////////////////////// // // // This file is part of Swift2D. // // // // Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer // // // //////////////////////////////////////////////////////////////////////////////// // includes ------------------------------------------------------------------- #include <swift2d/particles/ParticleUpdateShader.hpp> namespace swift { //////////////////////////////////////////////////////////////////////////////// ParticleUpdateShader::ParticleUpdateShader() : Shader( R"( // vertex shader --------------------------------------------------------- @include "version" layout(location=0) in vec2 position; layout(location=1) in vec2 velocity; layout(location=2) in vec2 life; layout(location=3) in vec2 rotation; out vec2 varying_position; out vec2 varying_velocity; out vec2 varying_life; out vec2 varying_rotation; void main(void) { varying_position = position; varying_velocity = velocity; varying_life = life; varying_rotation = rotation; } )", "", // empty fragment shader R"( // geometry shader ------------------------------------------------------- @include "version" layout(points) in; layout(points) out; layout(max_vertices = 50) out; in vec2 varying_position[]; in vec2 varying_velocity[]; in vec2 varying_life[]; in vec2 varying_rotation[]; // general uniforms uniform vec2 time; // x: frame time y: total time [millisec] // spawn uniforms uniform sampler2D noise_tex; uniform int spawn_count; uniform vec3 transform[50]; // xy: pos z: rot uniform vec2 life; // x: life y: life variance [sec] uniform vec2 velocity; // x: velocity y: velocity variance uniform vec2 rotation; // x: rotation y: rotation variance uniform vec2 pos_rot_variance; // update uniforms uniform sampler2D gravity_map; uniform mat3 projection; uniform vec3 dynamics; // x: mass y: linear damp z: angular damp out vec2 out_position; out vec2 out_velocity; out vec2 out_life; out vec2 out_rotation; vec3 get_random(float seed) { seed = mod(seed, 10); return (texture(noise_tex, vec2(seed*1.3, seed*2.1)).xyz - 0.5) * 2.0; } void main(void) { if (spawn_count >= 0) { // spawn new particles ----------------------------------------------- for (int i=0; i<spawn_count; ++i) { float delta = 1.0*i/spawn_count; vec3 random = get_random((i+1)*time.y); float l = max(0, life.x + random.x * life.y); float d = transform[i].z + random.y * pos_rot_variance.y; float v = velocity.x + random.z * velocity.y; float r = rotation.x + random.z * rotation.y; out_position = transform[i].xy + random.xy*pos_rot_variance.x; out_life = vec2(0, l*1000.0); out_velocity = vec2(cos(d), sin(d)) * v; out_rotation = vec2(d, r); EmitVertex(); EndPrimitive(); } } else { // update existing particles ----------------------------------------- if (varying_life[0].x < 1) { vec2 texcoords = ((projection * vec3(varying_position[0], 1)).xy + 1.0) * 0.5; float clip_dist = 0.3; if (texcoords.x > -clip_dist && texcoords.y > -clip_dist && texcoords.x < 1+clip_dist && texcoords.y < 1+clip_dist) { vec2 gravity = (texture(gravity_map, texcoords).rg - 0.5) * dynamics.x; out_position = varying_position[0] + varying_velocity[0] * time.x / 1000; out_life = vec2(varying_life[0].x + time.x/varying_life[0].y, varying_life[0].y); out_velocity = (varying_velocity[0] + gravity*time.x*0.1) - 0.1 * varying_velocity[0] * dynamics.y * time.x; out_rotation = vec2(varying_rotation[0].x + varying_rotation[0].y * time.x / 1000, varying_rotation[0].y - 0.01 * varying_rotation[0].y * dynamics.z * time.x); EmitVertex(); EndPrimitive(); } } } } )", {"out_position", "out_velocity", "out_life", "out_rotation"} ) , time(get_uniform<math::vec2>("time")) , noise_tex(get_uniform<int>("noise_tex")) , spawn_count(get_uniform<int>("spawn_count")) , transform(get_uniform<math::vec3>("transform")) , life(get_uniform<math::vec2>("life")) , pos_rot_variance(get_uniform<math::vec2>("pos_rot_variance")) , velocity(get_uniform<math::vec2>("velocity")) , rotation(get_uniform<math::vec2>("rotation")) , gravity_map(get_uniform<int>("gravity_map")) , projection(get_uniform<math::mat3>("projection")) , dynamics(get_uniform<math::vec3>("dynamics")) {} //////////////////////////////////////////////////////////////////////////////// } <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2015, GameDuell GmbH * 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 <types/NativeData.h> #include <string> #include <hx/CFFI.h> class NativeData_Impl : public NativeData { public: void setup(int lengthInBytes); void setupWithExistingPointer(uint8_t* existingPtr, int lengthInBytes); void cleanUp(); void writeData(const NativeData *d); void writePointer(const void* pointer, int lengthInBytes); void resize(int newSize); void trim(); ~NativeData_Impl(); NativeData_Impl(); }; void NativeData_Impl::setup(int lengthInBytes) { cleanUp(); ptr = (uint8_t *)calloc(lengthInBytes, 1); allocedLength = lengthInBytes; offset = 0; offsetLength = lengthInBytes; externalPtr = false; } void NativeData_Impl::setupWithExistingPointer(uint8_t* existingPtr, int lengthInBytes) { cleanUp(); ptr = existingPtr; allocedLength = lengthInBytes; offset = 0; offsetLength = lengthInBytes; externalPtr = true; } void NativeData_Impl::cleanUp() { if(allocedLength > 0 && !externalPtr) free(ptr); ptr = 0; allocedLength = 0; offset = 0; offsetLength = 0; externalPtr = false; } NativeData_Impl::NativeData_Impl() { ptr = 0; allocedLength = 0; offset = 0; offsetLength = 0; externalPtr = false; } void NativeData_Impl::writeData(const NativeData *d) { memcpy(ptr + offset, d->ptr + d->offset, d->offsetLength); } void NativeData_Impl::writePointer(const void* pointer, int lengthInBytes) { memcpy(ptr + offset, pointer, lengthInBytes); } void NativeData_Impl::resize(int newSize) { if(externalPtr) { uint8_t* prevPtr = ptr; ptr = (uint8_t*)calloc(newSize, 1); memcpy(ptr, prevPtr, allocedLength); externalPtr = false; } else { if (newSize == 0) { cleanUp(); } else { ptr = (uint8_t*)realloc(ptr, newSize); int extraSizeToZeroOut = newSize - allocedLength; if(extraSizeToZeroOut > 0) { memset(ptr + allocedLength, 0, extraSizeToZeroOut); } } } allocedLength = newSize; } void NativeData_Impl::trim() { uint8_t* prevPtr = ptr; ptr = (uint8_t*)calloc(offsetLength, 1); memcpy(ptr, prevPtr + offset, offsetLength); if (externalPtr) { externalPtr = false; } else { free(prevPtr); } allocedLength = offsetLength; offset = 0; } NativeData_Impl::~NativeData_Impl() { cleanUp(); } static void finalizer(value abstract_object) { NativeData_Impl* data = (NativeData_Impl *)val_data(abstract_object); data->cleanUp(); delete data; } DEFINE_KIND(k_NativeData) void* NativeData::createHaxePointer() { value v; v = alloc_abstract(k_NativeData, new NativeData_Impl()); val_gc(v, (hxFinalizer) &finalizer); return (void*)v; } <commit_msg>fixed bug with resize data with external ptr<commit_after>/* * Copyright (c) 2003-2015, GameDuell GmbH * 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 <types/NativeData.h> #include <string> #include <hx/CFFI.h> class NativeData_Impl : public NativeData { public: void setup(int lengthInBytes); void setupWithExistingPointer(uint8_t* existingPtr, int lengthInBytes); void cleanUp(); void writeData(const NativeData *d); void writePointer(const void* pointer, int lengthInBytes); void resize(int newSize); void trim(); ~NativeData_Impl(); NativeData_Impl(); }; void NativeData_Impl::setup(int lengthInBytes) { cleanUp(); ptr = (uint8_t *)calloc(lengthInBytes, 1); allocedLength = lengthInBytes; offset = 0; offsetLength = lengthInBytes; externalPtr = false; } void NativeData_Impl::setupWithExistingPointer(uint8_t* existingPtr, int lengthInBytes) { cleanUp(); ptr = existingPtr; allocedLength = lengthInBytes; offset = 0; offsetLength = lengthInBytes; externalPtr = true; } void NativeData_Impl::cleanUp() { if(allocedLength > 0 && !externalPtr) free(ptr); ptr = 0; allocedLength = 0; offset = 0; offsetLength = 0; externalPtr = false; } NativeData_Impl::NativeData_Impl() { ptr = 0; allocedLength = 0; offset = 0; offsetLength = 0; externalPtr = false; } void NativeData_Impl::writeData(const NativeData *d) { memcpy(ptr + offset, d->ptr + d->offset, d->offsetLength); } void NativeData_Impl::writePointer(const void* pointer, int lengthInBytes) { memcpy(ptr + offset, pointer, lengthInBytes); } void NativeData_Impl::resize(int newSize) { if(externalPtr) { uint8_t* prevPtr = ptr; ptr = (uint8_t*)calloc(newSize, 1); if (newSize > allocedLength) { memcpy(ptr, prevPtr, allocedLength); } else { memcpy(ptr, prevPtr, newSize); } externalPtr = false; } else { if (newSize == 0) { cleanUp(); } else { ptr = (uint8_t*)realloc(ptr, newSize); int extraSizeToZeroOut = newSize - allocedLength; if(extraSizeToZeroOut > 0) { memset(ptr + allocedLength, 0, extraSizeToZeroOut); } } } allocedLength = newSize; } void NativeData_Impl::trim() { uint8_t* prevPtr = ptr; ptr = (uint8_t*)calloc(offsetLength, 1); memcpy(ptr, prevPtr + offset, offsetLength); if (externalPtr) { externalPtr = false; } else { free(prevPtr); } allocedLength = offsetLength; offset = 0; } NativeData_Impl::~NativeData_Impl() { cleanUp(); } static void finalizer(value abstract_object) { NativeData_Impl* data = (NativeData_Impl *)val_data(abstract_object); data->cleanUp(); delete data; } DEFINE_KIND(k_NativeData) void* NativeData::createHaxePointer() { value v; v = alloc_abstract(k_NativeData, new NativeData_Impl()); val_gc(v, (hxFinalizer) &finalizer); return (void*)v; } <|endoftext|>
<commit_before>/* Copyright (c) 2012, The Mineserver 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 The Mineserver Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 <map> #include "constants.h" #include "random.h" std::map<uint8_t, DropPtr> BLOCKDROPS; const unsigned int SERVER_CONSOLE_UID = -1; const std::string VERSION = "0.1.16 (Alpha)"; const int PROTOCOL_VERSION = 28; const char COMMENTPREFIX = '#'; // Configuration const std::string CONFIG_FILE = "config.cfg"; // PID file const std::string PID_FILE = "mineserver.pid"; //allocate 1 MB for chunk files const int ALLOCATE_NBTFILE = 1048576; const int kMaxChatMessageLength = 119; void initConstants() { // Block drops (10000 = 100%) // Blocks that always drop one item BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_STONE, DropPtr(new Drop(BLOCK_COBBLESTONE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_GRASS, DropPtr(new Drop(BLOCK_DIRT, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_DIRT, DropPtr(new Drop(BLOCK_DIRT, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_COBBLESTONE, DropPtr(new Drop(BLOCK_COBBLESTONE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_PLANK, DropPtr(new Drop(BLOCK_PLANK, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_SAPLING, DropPtr(new Drop(BLOCK_SAPLING, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_SAND, DropPtr(new Drop(BLOCK_SAND, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_COAL_ORE, DropPtr(new Drop(ITEM_COAL, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_IRON_ORE, DropPtr(new Drop(BLOCK_IRON_ORE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_GOLD_ORE, DropPtr(new Drop(BLOCK_GOLD_ORE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_DIAMOND_ORE, DropPtr(new Drop(ITEM_DIAMOND, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_WOOD, DropPtr(new Drop(BLOCK_WOOD, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_WOOL, DropPtr(new Drop(BLOCK_WOOL, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_WOODEN_STAIRS, DropPtr(new Drop(BLOCK_PLANK, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_RED_ROSE, DropPtr(new Drop(BLOCK_RED_ROSE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_YELLOW_FLOWER, DropPtr(new Drop(BLOCK_YELLOW_FLOWER, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_BROWN_MUSHROOM, DropPtr(new Drop(BLOCK_BROWN_MUSHROOM, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_RED_MUSHROOM, DropPtr(new Drop(BLOCK_RED_MUSHROOM, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_LADDER, DropPtr(new Drop(BLOCK_LADDER, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_CACTUS, DropPtr(new Drop(BLOCK_CACTUS, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_REED, DropPtr(new Drop(ITEM_REED, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_PUMPKIN, DropPtr(new Drop(BLOCK_PUMPKIN, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_TORCH, DropPtr(new Drop(BLOCK_TORCH, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_REDSTONE_TORCH_OFF, DropPtr(new Drop(BLOCK_REDSTONE_TORCH_OFF, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_REDSTONE_TORCH_ON, DropPtr(new Drop(BLOCK_REDSTONE_TORCH_ON, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_GLOWSTONE, DropPtr(new Drop(ITEM_GLOWSTONE_DUST, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_BRICK, DropPtr(new Drop(ITEM_CLAY_BRICK, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_JUKEBOX, DropPtr(new Drop(BLOCK_JUKEBOX, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_NETHERSTONE, DropPtr(new Drop(BLOCK_NETHERSTONE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_SLOW_SAND, DropPtr(new Drop(BLOCK_SLOW_SAND, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_JACK_O_LANTERN, DropPtr(new Drop(BLOCK_JACK_O_LANTERN, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_MINECART_TRACKS, DropPtr(new Drop(BLOCK_MINECART_TRACKS, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_MOSSY_COBBLESTONE, DropPtr(new Drop(BLOCK_MOSSY_COBBLESTONE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_OBSIDIAN, DropPtr(new Drop(BLOCK_OBSIDIAN, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_STEP, DropPtr(new Drop(BLOCK_STEP, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_WOODEN_DOOR, DropPtr(new Drop(ITEM_WOODEN_DOOR, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_IRON_DOOR, DropPtr(new Drop(ITEM_IRON_DOOR, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_SNOW, DropPtr(new Drop(ITEM_SNOWBALL, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_IRON_BLOCK, DropPtr(new Drop(BLOCK_IRON_BLOCK, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_GOLD_BLOCK, DropPtr(new Drop(BLOCK_GOLD_BLOCK, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_DIAMOND_BLOCK, DropPtr(new Drop(BLOCK_DIAMOND_BLOCK, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_LAPIS_BLOCK, DropPtr(new Drop(BLOCK_LAPIS_BLOCK, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_BED, DropPtr(new Drop(ITEM_BED, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_FURNACE, DropPtr(new Drop(BLOCK_FURNACE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_BURNING_FURNACE, DropPtr(new Drop(BLOCK_FURNACE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_CHEST, DropPtr(new Drop(BLOCK_CHEST, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_WORKBENCH, DropPtr(new Drop(BLOCK_WORKBENCH, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_SIGN_POST, DropPtr(new Drop(ITEM_SIGN, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_WALL_SIGN, DropPtr(new Drop(ITEM_SIGN, 10000, 1)))); // Always drop but give more than one item BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_REDSTONE_ORE, DropPtr(new Drop(ITEM_REDSTONE, 10000, 4)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_CLAY, DropPtr(new Drop(ITEM_CLAY_BALLS, 10000, 4)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_SNOW_BLOCK, DropPtr(new Drop(ITEM_SNOWBALL, 10000, 4)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_DOUBLE_STEP, DropPtr(new Drop(BLOCK_STEP, 10000, 2)))); // Blocks that drop items by chance BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_GRAVEL, DropPtr(new Drop(ITEM_FLINT, 850, 1, 0, DropPtr(new Drop(BLOCK_GRAVEL, 10000, 1)))))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_LEAVES, DropPtr(new Drop(BLOCK_SAPLING, 1200, 1)))); // Blocks that drop nothing: // BLOCK_TNT, BLOCK_GLASS, BLOCK_MOB_SPAWNER // Blocks that drop items with metadata BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_LAPIS_ORE, DropPtr(new Drop(ITEM_DYE, 10000, 1, DYE_LAPIS_LAZULI)))); } void Drop::getDrop(int16_t& item, uint8_t& count, uint8_t& meta) { Drop *cur = this; while (cur) { if (cur->probability >= uniformUINT(0, 9999)) { item = cur->item_id; count = cur->count; if (cur->meta != -1) meta = (uint8_t)cur->meta; return; } else { cur = cur->alt_drop.get(); } } count = 0; } <commit_msg>Set the protocol version 28 -> 29 (Minecraft 1.2.4).<commit_after>/* Copyright (c) 2012, The Mineserver 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 The Mineserver Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 <map> #include "constants.h" #include "random.h" std::map<uint8_t, DropPtr> BLOCKDROPS; const unsigned int SERVER_CONSOLE_UID = -1; const std::string VERSION = "0.1.16 (Alpha)"; const int PROTOCOL_VERSION = 29; const char COMMENTPREFIX = '#'; // Configuration const std::string CONFIG_FILE = "config.cfg"; // PID file const std::string PID_FILE = "mineserver.pid"; //allocate 1 MB for chunk files const int ALLOCATE_NBTFILE = 1048576; const int kMaxChatMessageLength = 119; void initConstants() { // Block drops (10000 = 100%) // Blocks that always drop one item BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_STONE, DropPtr(new Drop(BLOCK_COBBLESTONE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_GRASS, DropPtr(new Drop(BLOCK_DIRT, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_DIRT, DropPtr(new Drop(BLOCK_DIRT, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_COBBLESTONE, DropPtr(new Drop(BLOCK_COBBLESTONE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_PLANK, DropPtr(new Drop(BLOCK_PLANK, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_SAPLING, DropPtr(new Drop(BLOCK_SAPLING, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_SAND, DropPtr(new Drop(BLOCK_SAND, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_COAL_ORE, DropPtr(new Drop(ITEM_COAL, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_IRON_ORE, DropPtr(new Drop(BLOCK_IRON_ORE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_GOLD_ORE, DropPtr(new Drop(BLOCK_GOLD_ORE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_DIAMOND_ORE, DropPtr(new Drop(ITEM_DIAMOND, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_WOOD, DropPtr(new Drop(BLOCK_WOOD, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_WOOL, DropPtr(new Drop(BLOCK_WOOL, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_WOODEN_STAIRS, DropPtr(new Drop(BLOCK_PLANK, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_RED_ROSE, DropPtr(new Drop(BLOCK_RED_ROSE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_YELLOW_FLOWER, DropPtr(new Drop(BLOCK_YELLOW_FLOWER, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_BROWN_MUSHROOM, DropPtr(new Drop(BLOCK_BROWN_MUSHROOM, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_RED_MUSHROOM, DropPtr(new Drop(BLOCK_RED_MUSHROOM, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_LADDER, DropPtr(new Drop(BLOCK_LADDER, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_CACTUS, DropPtr(new Drop(BLOCK_CACTUS, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_REED, DropPtr(new Drop(ITEM_REED, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_PUMPKIN, DropPtr(new Drop(BLOCK_PUMPKIN, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_TORCH, DropPtr(new Drop(BLOCK_TORCH, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_REDSTONE_TORCH_OFF, DropPtr(new Drop(BLOCK_REDSTONE_TORCH_OFF, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_REDSTONE_TORCH_ON, DropPtr(new Drop(BLOCK_REDSTONE_TORCH_ON, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_GLOWSTONE, DropPtr(new Drop(ITEM_GLOWSTONE_DUST, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_BRICK, DropPtr(new Drop(ITEM_CLAY_BRICK, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_JUKEBOX, DropPtr(new Drop(BLOCK_JUKEBOX, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_NETHERSTONE, DropPtr(new Drop(BLOCK_NETHERSTONE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_SLOW_SAND, DropPtr(new Drop(BLOCK_SLOW_SAND, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_JACK_O_LANTERN, DropPtr(new Drop(BLOCK_JACK_O_LANTERN, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_MINECART_TRACKS, DropPtr(new Drop(BLOCK_MINECART_TRACKS, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_MOSSY_COBBLESTONE, DropPtr(new Drop(BLOCK_MOSSY_COBBLESTONE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_OBSIDIAN, DropPtr(new Drop(BLOCK_OBSIDIAN, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_STEP, DropPtr(new Drop(BLOCK_STEP, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_WOODEN_DOOR, DropPtr(new Drop(ITEM_WOODEN_DOOR, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_IRON_DOOR, DropPtr(new Drop(ITEM_IRON_DOOR, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_SNOW, DropPtr(new Drop(ITEM_SNOWBALL, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_IRON_BLOCK, DropPtr(new Drop(BLOCK_IRON_BLOCK, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_GOLD_BLOCK, DropPtr(new Drop(BLOCK_GOLD_BLOCK, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_DIAMOND_BLOCK, DropPtr(new Drop(BLOCK_DIAMOND_BLOCK, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_LAPIS_BLOCK, DropPtr(new Drop(BLOCK_LAPIS_BLOCK, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_BED, DropPtr(new Drop(ITEM_BED, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_FURNACE, DropPtr(new Drop(BLOCK_FURNACE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_BURNING_FURNACE, DropPtr(new Drop(BLOCK_FURNACE, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_CHEST, DropPtr(new Drop(BLOCK_CHEST, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_WORKBENCH, DropPtr(new Drop(BLOCK_WORKBENCH, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_SIGN_POST, DropPtr(new Drop(ITEM_SIGN, 10000, 1)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_WALL_SIGN, DropPtr(new Drop(ITEM_SIGN, 10000, 1)))); // Always drop but give more than one item BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_REDSTONE_ORE, DropPtr(new Drop(ITEM_REDSTONE, 10000, 4)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_CLAY, DropPtr(new Drop(ITEM_CLAY_BALLS, 10000, 4)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_SNOW_BLOCK, DropPtr(new Drop(ITEM_SNOWBALL, 10000, 4)))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_DOUBLE_STEP, DropPtr(new Drop(BLOCK_STEP, 10000, 2)))); // Blocks that drop items by chance BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_GRAVEL, DropPtr(new Drop(ITEM_FLINT, 850, 1, 0, DropPtr(new Drop(BLOCK_GRAVEL, 10000, 1)))))); BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_LEAVES, DropPtr(new Drop(BLOCK_SAPLING, 1200, 1)))); // Blocks that drop nothing: // BLOCK_TNT, BLOCK_GLASS, BLOCK_MOB_SPAWNER // Blocks that drop items with metadata BLOCKDROPS.insert(std::pair<uint8_t, DropPtr>(BLOCK_LAPIS_ORE, DropPtr(new Drop(ITEM_DYE, 10000, 1, DYE_LAPIS_LAZULI)))); } void Drop::getDrop(int16_t& item, uint8_t& count, uint8_t& meta) { Drop *cur = this; while (cur) { if (cur->probability >= uniformUINT(0, 9999)) { item = cur->item_id; count = cur->count; if (cur->meta != -1) meta = (uint8_t)cur->meta; return; } else { cur = cur->alt_drop.get(); } } count = 0; } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "entity/components/PositionManager.h" TEST(PositionManagerTest, PositionComponentComparisons) { PositionComponent p1 = { 3, 4 }; PositionComponent p2 = { 3, 4 }; PositionComponent p3 = { 3, 5 }; EXPECT_TRUE(p1 == p2); EXPECT_FALSE(p1 == p3); EXPECT_FALSE(p1 != p2); EXPECT_TRUE(p1 != p3); } TEST(PositionManagerTest, PositionManagerIsCorrectType) { PositionManager pm; EXPECT_EQ(Position, pm.getComponentType()); } TEST(PositionManagerTest, EntityDoesNotHaveComponent) { PositionManager pm; Entity e = 5; EXPECT_FALSE(pm.entityHasComponent(e)); } TEST(PositionManagerTest, AddedEntityHasComponent) { PositionManager pm; Entity e = 5; pm.addComponent(e); EXPECT_TRUE(pm.entityHasComponent(e)); } TEST(PositionManagerTest, RemoveComponent) { PositionManager pm; Entity e = 5; pm.addComponent(e); ASSERT_TRUE(pm.entityHasComponent(e)); pm.removeComponent(e); EXPECT_FALSE(pm.entityHasComponent(e)); } TEST(PositionManagerTest, PositionDefaultsToNULL) { PositionManager pm; Entity e = 5; pm.addComponent(e); EXPECT_EQ(PositionManager::NULL_POS.x, pm.getPosition(e).x); EXPECT_EQ(PositionManager::NULL_POS.y, pm.getPosition(e).y); EXPECT_EQ(PositionManager::NULL_POS.x, pm.getX(e)); EXPECT_EQ(PositionManager::NULL_POS.y, pm.getY(e)); } TEST(PositionManagerTest, SetPosition) { PositionManager pm; Entity e = 5; PositionComponent pos = {4, 2}; pm.setPosition(e, pos); EXPECT_EQ(pos.x, pm.getPosition(e).x); EXPECT_EQ(pos.y, pm.getPosition(e).y); EXPECT_EQ(pos.x, pm.getX(e)); EXPECT_EQ(pos.y, pm.getY(e)); } TEST(PositionManagerTest, SetPositionByCoordinate) { PositionManager pm; Entity e = 5; pm.setX(e, 4); pm.setY(e, 2); EXPECT_EQ(4, pm.getPosition(e).x); EXPECT_EQ(2, pm.getPosition(e).y); EXPECT_EQ(4, pm.getX(e)); EXPECT_EQ(2, pm.getY(e)); } TEST(PositionManagerTest, FindEntityByPosition) { PositionManager pm; Entity e1 = 5; Entity e2 = 7; PositionComponent pos1 = { 4, 2 }; PositionComponent pos2 = { 3, 5 }; PositionComponent pos3 = { 5, 5 }; pm.setPosition(e1, pos1); pm.setPosition(e2, pos2); EXPECT_TRUE(pm.isPositionOccupied(pos1)); EXPECT_TRUE(pm.isPositionOccupied(pos2)); EXPECT_TRUE(pm.isPositionOccupied(4, 2)); EXPECT_TRUE(pm.isPositionOccupied(3, 5)); EXPECT_FALSE(pm.isPositionOccupied(pos3)); EXPECT_FALSE(pm.isPositionOccupied(5, 5)); EXPECT_EQ(e1, pm.getEntityAtPosition(pos1)); EXPECT_EQ(e1, pm.getEntityAtPosition(4, 2)); EXPECT_EQ(e2, pm.getEntityAtPosition(pos2)); EXPECT_EQ(e2, pm.getEntityAtPosition(3, 5)); } <commit_msg>Test getEntityAtPosition returns NULL_ENTITY<commit_after>#include "gtest/gtest.h" #include "entity/components/PositionManager.h" TEST(PositionManagerTest, PositionComponentComparisons) { PositionComponent p1 = { 3, 4 }; PositionComponent p2 = { 3, 4 }; PositionComponent p3 = { 3, 5 }; EXPECT_TRUE(p1 == p2); EXPECT_FALSE(p1 == p3); EXPECT_FALSE(p1 != p2); EXPECT_TRUE(p1 != p3); } TEST(PositionManagerTest, PositionManagerIsCorrectType) { PositionManager pm; EXPECT_EQ(Position, pm.getComponentType()); } TEST(PositionManagerTest, EntityDoesNotHaveComponent) { PositionManager pm; Entity e = 5; EXPECT_FALSE(pm.entityHasComponent(e)); } TEST(PositionManagerTest, AddedEntityHasComponent) { PositionManager pm; Entity e = 5; pm.addComponent(e); EXPECT_TRUE(pm.entityHasComponent(e)); } TEST(PositionManagerTest, RemoveComponent) { PositionManager pm; Entity e = 5; pm.addComponent(e); ASSERT_TRUE(pm.entityHasComponent(e)); pm.removeComponent(e); EXPECT_FALSE(pm.entityHasComponent(e)); } TEST(PositionManagerTest, PositionDefaultsToNULL) { PositionManager pm; Entity e = 5; pm.addComponent(e); EXPECT_EQ(PositionManager::NULL_POS.x, pm.getPosition(e).x); EXPECT_EQ(PositionManager::NULL_POS.y, pm.getPosition(e).y); EXPECT_EQ(PositionManager::NULL_POS.x, pm.getX(e)); EXPECT_EQ(PositionManager::NULL_POS.y, pm.getY(e)); } TEST(PositionManagerTest, SetPosition) { PositionManager pm; Entity e = 5; PositionComponent pos = {4, 2}; pm.setPosition(e, pos); EXPECT_EQ(pos.x, pm.getPosition(e).x); EXPECT_EQ(pos.y, pm.getPosition(e).y); EXPECT_EQ(pos.x, pm.getX(e)); EXPECT_EQ(pos.y, pm.getY(e)); } TEST(PositionManagerTest, SetPositionByCoordinate) { PositionManager pm; Entity e = 5; pm.setX(e, 4); pm.setY(e, 2); EXPECT_EQ(4, pm.getPosition(e).x); EXPECT_EQ(2, pm.getPosition(e).y); EXPECT_EQ(4, pm.getX(e)); EXPECT_EQ(2, pm.getY(e)); } TEST(PositionManagerTest, FindEntityByPosition) { PositionManager pm; Entity e1 = 5; Entity e2 = 7; PositionComponent pos1 = { 4, 2 }; PositionComponent pos2 = { 3, 5 }; PositionComponent pos3 = { 5, 5 }; pm.setPosition(e1, pos1); pm.setPosition(e2, pos2); EXPECT_TRUE(pm.isPositionOccupied(pos1)); EXPECT_TRUE(pm.isPositionOccupied(pos2)); EXPECT_TRUE(pm.isPositionOccupied(4, 2)); EXPECT_TRUE(pm.isPositionOccupied(3, 5)); EXPECT_FALSE(pm.isPositionOccupied(pos3)); EXPECT_FALSE(pm.isPositionOccupied(5, 5)); EXPECT_EQ(e1, pm.getEntityAtPosition(pos1)); EXPECT_EQ(e1, pm.getEntityAtPosition(4, 2)); EXPECT_EQ(e2, pm.getEntityAtPosition(pos2)); EXPECT_EQ(e2, pm.getEntityAtPosition(3, 5)); EXPECT_EQ(NULL_ENTITY, pm.getEntityAtPosition(pos3)); EXPECT_EQ(NULL_ENTITY, pm.getEntityAtPosition(5, 5)); } <|endoftext|>
<commit_before>/* Copyright (c) 2017 InversePalindrome Memento Mori - StateSystem.cpp InversePalindrome.com */ #include "StateSystem.hpp" #include "EntityManager.hpp" #include "SystemManager.hpp" #include "ControllerSystem.hpp" #include "PositionComponent.hpp" #include <Thor/Math/Random.hpp> const std::unordered_map<PickupType, std::string> StateSystem::pickupFiles = { { PickupType::Heart, "Resources/Files/Heart.txt" } }; StateSystem::StateSystem(SystemManager& systemManager) : System(System::ID::State, systemManager) { EntityComposition entityComposition; entityComposition[static_cast<std::size_t>(Component::ID::State)] = true; componentRequirements.push_back(entityComposition); systemManager.getMessageHandler()->subscribe(EntityMessage::Move, this); systemManager.getMessageHandler()->subscribe(EntityMessage::ChangeState, this); } void StateSystem::handleEvent(EntityID entityID, EntityEvent event) { switch (event) { case EntityEvent::Died: this->addPickup(entityID); this->systemManager->getEntityManager()->removeEntity(entityID); this->systemManager->getEntityManager()->setDeadEntityCount(this->systemManager->getEntityManager()->getDeadEntityCount() + 1u); break; case EntityEvent::BecameIdle: this->changeState(entityID, EntityState::Idle); break; } } void StateSystem::update(sf::Time deltaTime) { } void StateSystem::notify(const Message& message) { switch (message.messageType) { case EntityMessage::Move: { auto* state = this->systemManager->getEntityManager()->getComponent<StateComponent>(message.receiverID, Component::ID::State); if (state->getState() != EntityState::Dead) { EntityEvent event; if (message.data.at(DataID::Direction) == static_cast<std::size_t>(Direction::Up)) { event = EntityEvent::MoveUp; } else if (message.data.at(DataID::Direction) == static_cast<std::size_t>(Direction::Down)) { event = EntityEvent::MoveDown; } else if (message.data.at(DataID::Direction) == static_cast<std::size_t>(Direction::Right)) { event = EntityEvent::MoveRight; } else if (message.data.at(DataID::Direction) == static_cast<std::size_t>(Direction::Left)) { event = EntityEvent::MoveLeft; } this->systemManager->addEvent(message.receiverID, event); this->changeState(message.receiverID, EntityState::Walking); } } break; case EntityMessage::ChangeState: this->changeState(message.receiverID, static_cast<EntityState>(message.data.at(DataID::State))); break; } } void StateSystem::changeState(EntityID entityID, EntityState entityState) { auto* state = this->systemManager->getEntityManager()->getComponent<StateComponent>(entityID, Component::ID::State); if (state->getState() != entityState) { state->setState(entityState); Message message(EntityMessage::StateChanged); message.receiverID = entityID; message.data[DataID::State] = static_cast<std::size_t>(entityState); this->systemManager->getMessageHandler()->dispatch(message); } } void StateSystem::addPickup(EntityID entityID) { float dropProbability = thor::random(0.f, 1.f); if (dropProbability <= 0.2f) { std::size_t pickupType = thor::random(0u, static_cast<std::size_t>(PickupType::PickupCount) - 1u); this->systemManager->getEntityManager()->addEntity(this->pickupFiles.at(static_cast<PickupType>(pickupType))); auto deathPosition = this->systemManager->getEntityManager()->getComponent <PositionComponent>(entityID, Component::ID::Position)->getPosition(); auto* pickupPosition = this->systemManager->getEntityManager()->getComponent<PositionComponent> (this->systemManager->getEntityManager()->getCurrentEntityID() - 1u, Component::ID::Position); pickupPosition->setPosition(deathPosition); } }<commit_msg>Delete StateSystem.cpp<commit_after><|endoftext|>
<commit_before>#include <coincident/controller.hh> #include <coincident/coincident.h> #include <ptrace.hh> #include <utils.hh> #include <elf.hh> #include <thread.hh> #include <function.hh> #include <stdlib.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <map> #define N_THREADS 16 class DefaultThreadSelector : public IController::IThreadSelector { public: int selectThread(int curThread, int nThreads, uint64_t timeUs, const PtraceEvent *ev) { return rand() % nThreads; } }; class Controller : public IController, IElf::IFunctionListener { public: friend class Session; class ThreadData { public: ThreadData(int (*fn)(void *), void *priv) : m_fn(fn), m_priv(priv) { } int (*m_fn)(void *); void *m_priv; }; Controller(); virtual ~Controller(); void onFunction(IFunction &fn); void setThreadSelector(IThreadSelector *selector); bool addThread(int (*fn)(void *), void *priv); int lockScheduler(); void unlockScheduler(int level); bool run(); void setRuns(int nRuns); void setTimeLimit(int ms); void cleanup(); uint64_t getTimeStamp(uint64_t start); typedef std::map<void *, IFunction *> functionMap_t; typedef std::map<int, IFunction *> functionBreakpointMap_t; typedef std::map<void *, int> breakpointMap_t; int m_nThreads; ThreadData *m_threads[N_THREADS]; IThreadSelector *m_selector; functionMap_t m_functions; breakpointMap_t m_breakpoints; uint64_t m_startTimeStamp; int m_schedulerLock; int m_runLimit; uint64_t m_timeLimit; }; class Session { public: Session(Controller &owner, int nThreads, Controller::ThreadData **threads); ~Session(); void removeThread(int pid, int which); bool handleBreakpoint(const PtraceEvent &ev); bool continueExecution(); bool run(); // Thread exit handler (just a marker) static void threadExit(); Controller &m_owner; int m_nThreads; int m_curPid; int m_curThread; IThread **m_threads; }; Controller::Controller() { memset(m_threads, 0, sizeof(m_threads)); m_nThreads = 0; m_schedulerLock = 0; m_runLimit = 0; m_timeLimit = 0; m_selector = new DefaultThreadSelector(); m_startTimeStamp = getTimeStamp(0); IElf &elf = IElf::getInstance(); elf.setFile(this, "/proc/self/exe"); // Setup function breakpoints for (functionMap_t::iterator it = m_functions.begin(); it != m_functions.end(); it++) { IFunction *cur = it->second; if (cur->getSize() == 0 || cur->getEntry() == 0) continue; m_breakpoints[cur->getEntry()] = 1; } } Controller::~Controller() { cleanup(); } void Controller::onFunction(IFunction &fn) { m_functions[fn.getEntry()] = &fn; } void Controller::setThreadSelector(IThreadSelector *selector) { if (m_selector) delete m_selector; m_selector = selector; } bool Controller::addThread(int (*fn)(void *), void *priv) { int cur = m_nThreads; m_nThreads++; // Add the thread to the list m_threads[cur] = new ThreadData(fn, priv); return true; } int Controller::lockScheduler() { int out = m_schedulerLock; m_schedulerLock++; return out; } void Controller::unlockScheduler(int level) { m_schedulerLock = level; } bool Controller::run() { int runsLeft = -1; bool out; if (m_runLimit) runsLeft = m_runLimit; m_startTimeStamp = getTimeStamp(0); while (1) { Session cur(*this, m_nThreads, m_threads); out = cur.run(); if (!out) break; if (runsLeft > 0) { runsLeft--; if (runsLeft == 0) break; } if (m_timeLimit && getTimeStamp(m_startTimeStamp) > m_timeLimit) break; } return out; } void Controller::setRuns(int nRuns) { m_runLimit = nRuns; } void Controller::setTimeLimit(int ms) { m_timeLimit = ms * 1000; } void Controller::cleanup() { if (m_selector) delete m_selector; } uint64_t Controller::getTimeStamp(uint64_t start) { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_usec + tv.tv_sec * 1000 * 1000) - start; } Session::Session(Controller &owner, int nThreads, Controller::ThreadData **threads) : m_owner(owner), m_nThreads(nThreads) { m_threads = new IThread*[m_nThreads]; m_curThread = 0; m_curPid = 0; for (int i = 0; i < m_nThreads; i++) { Controller::ThreadData *p = threads[i]; m_threads[i] = &IThread::createThread(Session::threadExit, p->m_fn, p->m_priv); } } Session::~Session() { for (int i = 0; i < m_nThreads; i++) IThread::releaseThread(*m_threads[i]); delete[] m_threads; } // Thread exit handler (just a marker) void Session::threadExit() { } void Session::removeThread(int pid, int which) { if (m_nThreads < 1) return; IThread::releaseThread(*m_threads[which]); // Swap threads if (which != m_nThreads) m_threads[which] = m_threads[m_nThreads - 1]; m_nThreads--; if (which == m_curThread || m_curThread >= m_nThreads) m_curThread = 0; if (m_nThreads > 0) IPtrace::getInstance().loadRegisters(pid, m_threads[0]->getRegs()); } bool Session::handleBreakpoint(const PtraceEvent &ev) { IFunction *function = m_owner.m_functions[ev.addr]; IPtrace &ptrace = IPtrace::getInstance(); // Step to next instruction ptrace.singleStep(m_curPid); if (function && function->getEntry() == (void *)Session::threadExit) { removeThread(m_curPid, m_curThread); if (m_nThreads == 0) return true; // Re-select the thread } else if (function) { // Visited a function for the first time, setup breakpoints if (ptrace.clearBreakpoint(ev.eventId) == false) error("Can't clear function breakpoint???"); m_owner.m_breakpoints.erase(function->getEntry()); std::list<void *> refs = function->getMemoryRefs(); for (std::list<void *>::iterator it = refs.begin(); it != refs.end(); it++) { if (ptrace.setBreakpoint(*it) < 0) error("Can't set breakpoint???"); m_owner.m_breakpoints[*it] = 1; } return true; } // No reschedules if this is set if (m_owner.m_schedulerLock) return true; int nextThread; nextThread = m_owner.m_selector->selectThread(m_curThread, m_nThreads, m_owner.getTimeStamp(m_owner.m_startTimeStamp), &ev); // Perform the actual thread switch if (nextThread != m_curThread) { ptrace.saveRegisters(m_curPid, m_threads[m_curThread]->getRegs()); ptrace.loadRegisters(m_curPid, m_threads[nextThread]->getRegs()); m_curThread = nextThread; } return true; } bool Session::continueExecution() { const PtraceEvent ev = IPtrace::getInstance().continueExecution(m_curPid); switch (ev.type) { case ptrace_error: case ptrace_crash: case ptrace_exit: return false; case ptrace_syscall: return false; case ptrace_breakpoint: return handleBreakpoint(ev); } return false; } bool Session::run() { bool should_quit = false; IPtrace &ptrace = IPtrace::getInstance(); /* Fork the parent process of all test threads. All * other threads will be threads running in this * context. * * For each round in the test, this is forked again * to retain the original memory state. */ m_curPid = ptrace.forkAndAttach(); if (m_curPid < 0) { error("fork failed\n"); return false; } else if (m_curPid == 0) { // Hmm... Not sure what to do here exit(0); } else { // Parent bool should_quit; for (Controller::breakpointMap_t::iterator it = m_owner.m_breakpoints.begin(); it != m_owner.m_breakpoints.end(); it++) { void *p = it->first; int id = ptrace.setBreakpoint(p); if (id < 0) error("Can't set breakpoint!\n"); } // Select an initial thread and load its registers m_curThread = m_owner.m_selector->selectThread(0, m_nThreads, m_owner.getTimeStamp(m_owner.m_startTimeStamp), NULL); void *regs = m_threads[m_curThread]->getRegs(); IPtrace::getInstance().loadRegisters(m_curPid, regs); do { should_quit = !continueExecution(); // Quit if all threads have exited cleanly if (m_nThreads == 0) break; } while (!should_quit); ptrace.kill(m_curPid); m_curPid = -1; } return m_nThreads == 0; } IController &IController::getInstance() { static Controller *instance; if (!instance) instance = new Controller(); return *instance; } int coincident_add_thread(int (*fn)(void *), void *priv) { if (IController::getInstance().addThread(fn, priv) == false) return -1; // FIXME: Should return the thread ID! return 0; } void coincident_set_run_limit(int n_runs) { IController::getInstance().setRuns(n_runs); } void coincident_set_time_limit(int n_ms) { IController::getInstance().setTimeLimit(n_ms); } int coincident_run(void) { if (IController::getInstance().run() == false) return 1; return 0; } <commit_msg>controller: Rename map types<commit_after>#include <coincident/controller.hh> #include <coincident/coincident.h> #include <ptrace.hh> #include <utils.hh> #include <elf.hh> #include <thread.hh> #include <function.hh> #include <stdlib.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <map> #define N_THREADS 16 class DefaultThreadSelector : public IController::IThreadSelector { public: int selectThread(int curThread, int nThreads, uint64_t timeUs, const PtraceEvent *ev) { return rand() % nThreads; } }; class Controller : public IController, IElf::IFunctionListener { public: friend class Session; class ThreadData { public: ThreadData(int (*fn)(void *), void *priv) : m_fn(fn), m_priv(priv) { } int (*m_fn)(void *); void *m_priv; }; Controller(); virtual ~Controller(); void onFunction(IFunction &fn); void setThreadSelector(IThreadSelector *selector); bool addThread(int (*fn)(void *), void *priv); int lockScheduler(); void unlockScheduler(int level); bool run(); void setRuns(int nRuns); void setTimeLimit(int ms); void cleanup(); uint64_t getTimeStamp(uint64_t start); typedef std::map<void *, IFunction *> FunctionMap_t; typedef std::map<int, IFunction *> FunctionBreakpointMap_t; typedef std::map<void *, int> BreakpointMap_t; int m_nThreads; ThreadData *m_threads[N_THREADS]; IThreadSelector *m_selector; FunctionMap_t m_functions; BreakpointMap_t m_breakpoints; uint64_t m_startTimeStamp; int m_schedulerLock; int m_runLimit; uint64_t m_timeLimit; }; class Session { public: Session(Controller &owner, int nThreads, Controller::ThreadData **threads); ~Session(); void removeThread(int pid, int which); bool handleBreakpoint(const PtraceEvent &ev); bool continueExecution(); bool run(); // Thread exit handler (just a marker) static void threadExit(); Controller &m_owner; int m_nThreads; int m_curPid; int m_curThread; IThread **m_threads; }; Controller::Controller() { memset(m_threads, 0, sizeof(m_threads)); m_nThreads = 0; m_schedulerLock = 0; m_runLimit = 0; m_timeLimit = 0; m_selector = new DefaultThreadSelector(); m_startTimeStamp = getTimeStamp(0); IElf &elf = IElf::getInstance(); elf.setFile(this, "/proc/self/exe"); // Setup function breakpoints for (FunctionMap_t::iterator it = m_functions.begin(); it != m_functions.end(); it++) { IFunction *cur = it->second; if (cur->getSize() == 0 || cur->getEntry() == 0) continue; m_breakpoints[cur->getEntry()] = 1; } } Controller::~Controller() { cleanup(); } void Controller::onFunction(IFunction &fn) { m_functions[fn.getEntry()] = &fn; } void Controller::setThreadSelector(IThreadSelector *selector) { if (m_selector) delete m_selector; m_selector = selector; } bool Controller::addThread(int (*fn)(void *), void *priv) { int cur = m_nThreads; m_nThreads++; // Add the thread to the list m_threads[cur] = new ThreadData(fn, priv); return true; } int Controller::lockScheduler() { int out = m_schedulerLock; m_schedulerLock++; return out; } void Controller::unlockScheduler(int level) { m_schedulerLock = level; } bool Controller::run() { int runsLeft = -1; bool out; if (m_runLimit) runsLeft = m_runLimit; m_startTimeStamp = getTimeStamp(0); while (1) { Session cur(*this, m_nThreads, m_threads); out = cur.run(); if (!out) break; if (runsLeft > 0) { runsLeft--; if (runsLeft == 0) break; } if (m_timeLimit && getTimeStamp(m_startTimeStamp) > m_timeLimit) break; } return out; } void Controller::setRuns(int nRuns) { m_runLimit = nRuns; } void Controller::setTimeLimit(int ms) { m_timeLimit = ms * 1000; } void Controller::cleanup() { if (m_selector) delete m_selector; } uint64_t Controller::getTimeStamp(uint64_t start) { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_usec + tv.tv_sec * 1000 * 1000) - start; } Session::Session(Controller &owner, int nThreads, Controller::ThreadData **threads) : m_owner(owner), m_nThreads(nThreads) { m_threads = new IThread*[m_nThreads]; m_curThread = 0; m_curPid = 0; for (int i = 0; i < m_nThreads; i++) { Controller::ThreadData *p = threads[i]; m_threads[i] = &IThread::createThread(Session::threadExit, p->m_fn, p->m_priv); } } Session::~Session() { for (int i = 0; i < m_nThreads; i++) IThread::releaseThread(*m_threads[i]); delete[] m_threads; } // Thread exit handler (just a marker) void Session::threadExit() { } void Session::removeThread(int pid, int which) { if (m_nThreads < 1) return; IThread::releaseThread(*m_threads[which]); // Swap threads if (which != m_nThreads) m_threads[which] = m_threads[m_nThreads - 1]; m_nThreads--; if (which == m_curThread || m_curThread >= m_nThreads) m_curThread = 0; if (m_nThreads > 0) IPtrace::getInstance().loadRegisters(pid, m_threads[0]->getRegs()); } bool Session::handleBreakpoint(const PtraceEvent &ev) { IFunction *function = m_owner.m_functions[ev.addr]; IPtrace &ptrace = IPtrace::getInstance(); // Step to next instruction ptrace.singleStep(m_curPid); if (function && function->getEntry() == (void *)Session::threadExit) { removeThread(m_curPid, m_curThread); if (m_nThreads == 0) return true; // Re-select the thread } else if (function) { // Visited a function for the first time, setup breakpoints if (ptrace.clearBreakpoint(ev.eventId) == false) error("Can't clear function breakpoint???"); m_owner.m_breakpoints.erase(function->getEntry()); std::list<void *> refs = function->getMemoryRefs(); for (std::list<void *>::iterator it = refs.begin(); it != refs.end(); it++) { if (ptrace.setBreakpoint(*it) < 0) error("Can't set breakpoint???"); m_owner.m_breakpoints[*it] = 1; } return true; } // No reschedules if this is set if (m_owner.m_schedulerLock) return true; int nextThread; nextThread = m_owner.m_selector->selectThread(m_curThread, m_nThreads, m_owner.getTimeStamp(m_owner.m_startTimeStamp), &ev); // Perform the actual thread switch if (nextThread != m_curThread) { ptrace.saveRegisters(m_curPid, m_threads[m_curThread]->getRegs()); ptrace.loadRegisters(m_curPid, m_threads[nextThread]->getRegs()); m_curThread = nextThread; } return true; } bool Session::continueExecution() { const PtraceEvent ev = IPtrace::getInstance().continueExecution(m_curPid); switch (ev.type) { case ptrace_error: case ptrace_crash: case ptrace_exit: return false; case ptrace_syscall: return false; case ptrace_breakpoint: return handleBreakpoint(ev); } return false; } bool Session::run() { bool should_quit = false; IPtrace &ptrace = IPtrace::getInstance(); /* Fork the parent process of all test threads. All * other threads will be threads running in this * context. * * For each round in the test, this is forked again * to retain the original memory state. */ m_curPid = ptrace.forkAndAttach(); if (m_curPid < 0) { error("fork failed\n"); return false; } else if (m_curPid == 0) { // Hmm... Not sure what to do here exit(0); } else { // Parent bool should_quit; for (Controller::BreakpointMap_t::iterator it = m_owner.m_breakpoints.begin(); it != m_owner.m_breakpoints.end(); it++) { void *p = it->first; int id = ptrace.setBreakpoint(p); if (id < 0) error("Can't set breakpoint!\n"); } // Select an initial thread and load its registers m_curThread = m_owner.m_selector->selectThread(0, m_nThreads, m_owner.getTimeStamp(m_owner.m_startTimeStamp), NULL); void *regs = m_threads[m_curThread]->getRegs(); IPtrace::getInstance().loadRegisters(m_curPid, regs); do { should_quit = !continueExecution(); // Quit if all threads have exited cleanly if (m_nThreads == 0) break; } while (!should_quit); ptrace.kill(m_curPid); m_curPid = -1; } return m_nThreads == 0; } IController &IController::getInstance() { static Controller *instance; if (!instance) instance = new Controller(); return *instance; } int coincident_add_thread(int (*fn)(void *), void *priv) { if (IController::getInstance().addThread(fn, priv) == false) return -1; // FIXME: Should return the thread ID! return 0; } void coincident_set_run_limit(int n_runs) { IController::getInstance().setRuns(n_runs); } void coincident_set_time_limit(int n_ms) { IController::getInstance().setTimeLimit(n_ms); } int coincident_run(void) { if (IController::getInstance().run() == false) return 1; return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: itkImageToImageAffineNormalizedCorrelationRegistrationTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include "itkPhysicalImage.h" #include "itkSimpleImageRegionIterator.h" #include "itkImageToImageAffineNormalizedCorrelationRegistration.h" /** * This test uses two 2D-Gaussians (standard deviation RegionSize/2) * One is shifted by 10 pixels from the other. * therefore the solution of the registration is |-5 0| * This test uses LevenbergMarquart Optimizer but * conjugate gradient optimizer tolerances are also defined * in the itkImageToImageAffineNormalizedCorrelationRegistration.txx file * (you need to change the type of the optimizer in the header file * ie itkImageToImageAffineNormalizedCorrelationRegistration.h) */ int main() { /*Allocate Images*/ typedef itk::PhysicalImage<unsigned char,2> ReferenceType; typedef itk::PhysicalImage<unsigned char,2> TargetType; typedef itk::ImageToImageAffineNormalizedCorrelationRegistration<ReferenceType,TargetType> RegistrationType; ReferenceType::SizeType size = {{100,100}}; ReferenceType::IndexType index = {{0,0}}; ReferenceType::RegionType region; region.SetSize( size ); region.SetIndex( index ); ReferenceType::Pointer imgReference = ReferenceType::New(); imgReference->SetLargestPossibleRegion( region ); imgReference->SetBufferedRegion( region ); imgReference->SetRequestedRegion( region ); imgReference->Allocate(); TargetType::Pointer imgTarget = TargetType::New(); imgTarget->SetLargestPossibleRegion( region ); imgTarget->SetBufferedRegion( region ); imgTarget->SetRequestedRegion( region ); imgTarget->Allocate(); /* Fill images with a 2D gaussian*/ typedef itk::SimpleImageRegionIterator<ReferenceType> ReferenceIteratorType; typedef itk::SimpleImageRegionIterator<TargetType> TargetIteratorType; itk::Point<double,2> center; center[0] = (double)region.GetSize()[0]/2.0; center[1] = (double)region.GetSize()[1]/2.0; const double s = (double)region.GetSize()[0]/2.0; itk::Point<double,2> p; itk::Vector<double,2> d; /* Set the displacement */ itk::Vector<double,2> displacement; displacement[0] = 7; displacement[1] = 3; ReferenceIteratorType ri(imgReference,region); TargetIteratorType ti(imgTarget,region); ri.Begin(); while(!ri.IsAtEnd()) { p[0] = ri.GetIndex()[0]; p[1] = ri.GetIndex()[1]; d = p-center; d += displacement; const double x = d[0]; const double y = d[1]; ri.Set( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ); ++ri; } ti.Begin(); while(!ti.IsAtEnd()) { p[0] = ti.GetIndex()[0]; p[1] = ti.GetIndex()[1]; d = p-center; const double x = d[0]; const double y = d[1]; ti.Set( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ); ++ti; } RegistrationType::Pointer registrationMethod = RegistrationType::New(); registrationMethod->SetReference(imgReference); registrationMethod->SetTarget(imgTarget); registrationMethod->SetTranslationScale( 1e4 ); registrationMethod->StartRegistration(); std::cout << "The correct answer should be : " << std::endl; std::cout << " 1.0 0.0 0.0 1.0 "; std::cout << -displacement << std::endl; return EXIT_SUCCESS; } <commit_msg>ENH: renamed to include the optimization method name<commit_after><|endoftext|>
<commit_before><commit_msg>Add additional support for the next upcoming gnokii version (>= 0.6.13) All versions below that number are not binary compatible, which means, that users could never upgrade gnokii without recompiling this import/export filter. With 0.6.13 this should be fixed. No new strings added, just many duplicates.<commit_after><|endoftext|>
<commit_before>#include "NAFF.h" #include <iostream> extern "C" double tunenaff(double** x, double** xp, int* maxn, int* plane_idx, int* norm_flag) { // Note: Dropped the two last formal arguments "int* x_len, int* xp_len", // which can sometimes be recieved as formal/dummy arguments to the function, // as they cannot be trusted to make any sense at all. // I think they should technically be an Fortran array descriptor; // however their format is not actually standardized. // Therefore let's just ignore them... // Don't mix buffers with Fortran (make sure to flush before calling this code too) std::cout << std::flush; // For debugging of argument passing. /* std::cout << "**TUNENAFF**" << std::endl << std::flush; std::cout << "maxn = " << *maxn << std::endl << std::flush; std::cout << "plane_idx = " << *plane_idx << std::endl << std::flush; std::cout << "norm_flag = " << *norm_flag << std::endl << std::flush; //std::cout << "x_len = " << *x_len << std::endl << std::flush; //std::cout << "xp_len = " << *xp_len << std::endl << std::flush; std::cout << "x[0] = " << **x << std::endl << std::flush; std::cout << "xp[0] = " << **xp << std::endl << std::flush; */ // END debugging of argument passing // Input sanity checks if (maxn <= 0) { fprintf(stderr, "CRITICAL ERROR in double tunenaff_(...): maxn = %d <= 0", *maxn); exit(EXIT_FAILURE); } /* Dropped because reasons described above. if ((*x_len > 0 and *xp_len > 0) and (*x_len < *maxn or *xp_len < *maxn)) { //In some cases, no x_len and xp_len is passed (they are set to 0); //then just hope maxn is OK. If not, check the lengths! fprintf(stderr, "CRITICAL ERROR in double tunenaff_(...): maxn is bigger than x_len or xp_len."); exit(EXIT_FAILURE); } if (*x_len != *xp_len) { fprintf(stderr, "CRITICAL ERROR in double tunenaff_(...): x_len is different than xp_len."); exit(EXIT_FAILURE); } */ //Copy the data from the FORTRAN arrays and into the vector that will be passed to NAFF std::vector<double> data; data.reserve(*maxn); std::vector<double> data_prime; data_prime.reserve(*maxn); for( int i = 0; i < *maxn; i++ ) { //std::cout << "i=" << i << std::endl << std::flush; //std::cout << (*x)[i] << " " << (*xp)[i] << std::endl << std::flush; data.push_back((*x)[i]); data_prime.push_back((*xp)[i]); } //Call NAFF! NAFF naff; double tune = naff.get_f1(data,data_prime); // FFTW library returns tune from 0-0.5 if (tune<0.1) tune = 1.0-tune; //More Debugging stuff.. // std::cout << "tune = " << tune << std::endl; // Don't mix buffers with Fortran (make sure to flush before calling thus function) std::cout << std::flush; return tune; } <commit_msg>Cleanup<commit_after>#include "NAFF.h" #include <iostream> // C++ <-> Fortran interface for NAFF // K. Sjobak and S. Kostoglou (CERN) // August 2017 extern "C" double tunenaff(double** x, double** xp, int* maxn, int* plane_idx, int* norm_flag) { // NOTE: double** x and double** xp are actually pointers to Fortran array descriptors, // and the first 4 or 8 bytes (32- or 64-bit) of these contain the base address of the array. // Therefore, using (*x)[idx] is basically accessing the array as a normal 1D array. // // The complication is that GFORTRAN and IFORT do not use the same types of array descriptors; // for other compilers I don't know what the situation is. // // More information: // https://software.intel.com/en-us/node/691959 // https://gcc.gnu.org/wiki/ArrayDescriptorUpdate // // Note that Fortran will pass these for // (1) Allocatable or assumed-shape array // (2) Fortran array pointers // (3) Coarrays // (4) Class objects // in the case of an explicit INTERFACE block. // // A suitable interface block for this function is: // interface // REAL(C_DOUBLE) function tunenaff // & (x,xp,maxn,plane_idx,norm_flag) BIND(C) // use, intrinsic :: ISO_C_BINDING // IMPLICIT NONE // REAL(C_DOUBLE), dimension(:) :: x,xp // INTEGER(C_INT) :: maxn, plane_idx, norm_flag // end function // end interface // // It may be more portable to convert the array to a C-style array pointer // using C_LOC() from ISO_C_BINDING, and then pass that. // See also: https://stackoverflow.com/a/11935949/6603597 // Don't mix buffers with Fortran (make sure to flush before calling this code too) std::cout << std::flush; // For debugging of argument passing. /* std::cout << "**TUNENAFF**" << std::endl << std::flush; std::cout << "maxn = " << *maxn << std::endl << std::flush; std::cout << "plane_idx = " << *plane_idx << std::endl << std::flush; std::cout << "norm_flag = " << *norm_flag << std::endl << std::flush; //std::cout << "x_len = " << *x_len << std::endl << std::flush; //std::cout << "xp_len = " << *xp_len << std::endl << std::flush; std::cout << "x[0] = " << **x << std::endl << std::flush; std::cout << "xp[0] = " << **xp << std::endl << std::flush; for( int i = 0; i < *maxn; i++ ) { std::cout << "i=" << i << std::endl << std::flush; std::cout << (*x)[i] << " " << (*xp)[i] << std::endl << std::flush; } */ // END debugging of argument passing // Input sanity checks if (maxn <= 0) { fprintf(stderr, "CRITICAL ERROR in double tunenaff_(...): maxn = %d <= 0", *maxn); exit(EXIT_FAILURE); } //Copy the data from the FORTRAN arrays and into the vector that will be passed to NAFF std::vector<double> data; data.reserve(*maxn); std::vector<double> data_prime; data_prime.reserve(*maxn); for( int i = 0; i < *maxn; i++ ) { data.push_back((*x)[i]); data_prime.push_back((*xp)[i]); } //Call NAFF! NAFF naff; double tune = naff.get_f1(data,data_prime); // FFTW library returns tune from 0-0.5 if (tune<0.1) tune = 1.0-tune; //More Debugging stuff.. // std::cout << "tune = " << tune << std::endl; // Don't mix buffers with Fortran (make sure to flush before calling thus function) std::cout << std::flush; return tune; } <|endoftext|>
<commit_before>/*********************************************************************************************** * Pudir - A pusher of directory to Android * Version: 1.0 * Copyright 2015 eccard * MIT License ************************************************************************************************/ #include "headers/mainwindow.h" #include "ui_mainwindow.h" #include <QMenuBar> #include <QFileDialog> #include <QDebug> #include <QFile> #include <QMessageBox> #include <QStringListModel> #include <QProcess> #include <QPalette> #include "headers/aboutdialog.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); createActions(); createMenus(); settings = new QSettings("freesoft", "pudir"); loadComp(); } void MainWindow::loadComp(){ QPalette p = ui->plainTextEdit->palette(); p.setColor(QPalette::Active, QPalette::Base, Qt::black); p.setColor(QPalette::Inactive, QPalette::Base, Qt::black); p.setColor(QPalette::Text, Qt::green); ui->plainTextEdit->setPalette(p); ui->lineEdit_src_dir->setText(settings->value("sourcePath").toString()); ui->lineEdit_dest_dir->setText(settings->value("destDir").toString()); adbPath = settings->value("adbPath").toString(); if(adbPath.isEmpty()){ ui->btn_refresh->setEnabled(false); ui->btn_setsrcdir->setEnabled(false); ui->btn_push->setEnabled(false); QMessageBox msgBox; msgBox.setIcon(QMessageBox::Information); msgBox.setText("Android SDK location not set"); msgBox.setInformativeText("Please go to Option -> Set SDK"); msgBox.exec(); } } MainWindow::~MainWindow() { delete ui; } void MainWindow::createActions() { setSdkAct = new QAction(tr("&Set path Android SDK "),this); connect(setSdkAct, SIGNAL(triggered()), this, SLOT(setSdkLocation())); aboutAct = new QAction(tr("&About"),this); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); exitAct = new QAction(tr("&Exit"),this); connect(exitAct, SIGNAL(triggered()), this, SLOT(exit())); } void MainWindow::createMenus() { optionsMenu = menuBar()->addMenu(tr("&Options")); optionsMenu->addAction(setSdkAct); optionsMenu->addAction(aboutAct); optionsMenu->addAction(exitAct); } void MainWindow::setSdkLocation(){ QFileDialog dialog(this); dialog.setFileMode(QFileDialog::Directory); QStringList fileNames; if (dialog.exec()) fileNames = dialog.selectedFiles(); qDebug()<< fileNames; #ifdef __linux adbPath = fileNames.at(0)+"/platform-tools/adb"; #elif _WIN32 adbPath = fileNames.at(0)+"/platform-tools/adb.exe"; #elif __APPLE__ #endif QMessageBox msgBox; QFile *qfile = new QFile(adbPath); if(qfile->exists()){ adbPath = qfile->fileName(); settings->setValue("adbPath",adbPath); msgBox.setIcon(QMessageBox::Information); msgBox.setText("Ok"); msgBox.exec(); ui->btn_refresh->setEnabled(true); ui->btn_push->setEnabled(true); ui->btn_setsrcdir->setEnabled(true); } else{ adbPath = ""; settings->setValue("adbPath",adbPath); msgBox.setText("Wrong path"); msgBox.setIcon(QMessageBox::Critical); msgBox.exec(); setSdkLocation(); } } void MainWindow::about(){ AboutDialog aboutDial; aboutDial.exec(); } void MainWindow::exit(){ close(); } void MainWindow::on_btn_refresh_clicked() { QStringList result; QProcess process; process.start(adbPath+" devices"); process.waitForFinished(-1); QString sstdout = process.readAllStandardOutput(); QString sstderr = process.readAllStandardError(); ui->plainTextEdit->appendPlainText(sstdout); ui->plainTextEdit->appendPlainText(sstderr); qDebug() << "."+adbPath+" devices"; qDebug() << sstdout; QString aux; if(!sstdout.isEmpty()){ QStringList aux2 = sstdout.mid(sstdout.indexOf("\n")).split("\n"); foreach (const QString &str, aux2) { if (str.contains("device")){ int j = str.indexOf("\t"); result += str.left(j); } } if(result.isEmpty()) ui->btn_push->setEnabled(false); else ui->btn_push->setEnabled(true); } qDebug()<<"result"<<result; QStringListModel *typeModel = new QStringListModel(result, this); ui->comboBox->setModel(typeModel); } void MainWindow::on_btn_setsrcdir_clicked() { QFileDialog dialog(this); dialog.setFileMode(QFileDialog::Directory); QStringList fileNames; if (dialog.exec()) fileNames = dialog.selectedFiles(); qDebug()<< fileNames; settings->setValue("sourcePath",fileNames.at(0)); ui->lineEdit_src_dir->setText(fileNames.at(0)); } void MainWindow::on_btn_push_clicked() { QString destinationDirec = ui->lineEdit_dest_dir->text(); QString deviceid = ui->comboBox->currentText(); settings->setValue("destDir",destinationDirec); QString sstdout,sstderr; QString sourcePath = settings->value("sourcePath").toString(); QProcess process; process.start(adbPath+" -s "+deviceid +" shell rm -rf /sdcard/"+destinationDirec); process.waitForFinished(-1); ui->plainTextEdit->clear(); ui->plainTextEdit->appendPlainText(process.readAllStandardOutput()); ui->plainTextEdit->appendPlainText(process.readAllStandardError()); process.start(adbPath+" -s "+deviceid +" shell mkdir -p /sdcard/"+destinationDirec+"/default"); process.waitForFinished(-1); ui->plainTextEdit->appendPlainText(process.readAllStandardOutput()); ui->plainTextEdit->appendPlainText(process.readAllStandardError()); process.start(adbPath+" -s "+deviceid +" push \""+ sourcePath +"\" /sdcard/"+destinationDirec+"/default"); process.waitForFinished(-1); ui->plainTextEdit->appendPlainText(process.readAllStandardOutput()); ui->plainTextEdit->appendPlainText(process.readAllStandardError()); qDebug() << adbPath+" shell rm -r /sdcard/"+destinationDirec; qDebug() << adbPath+" shell shell mkdir -p /sdcard/"+destinationDirec+"/default"; qDebug() << adbPath+" push \""+ sourcePath +"\" /sdcard/"+destinationDirec+"/default"; qDebug() << sstdout; qDebug() << sstderr; } void MainWindow::on_pushButton_clicked() { ui->plainTextEdit->clear(); } <commit_msg>fix #2, e corrige bug da dialog de seleção de pasta origem, quando fechava sem selecionar nada.<commit_after>/*********************************************************************************************** * Pudir - A pusher of directory to Android * Version: 1.0 * Copyright 2015 eccard * MIT License ************************************************************************************************/ #include "headers/mainwindow.h" #include "ui_mainwindow.h" #include <QMenuBar> #include <QFileDialog> #include <QDebug> #include <QFile> #include <QMessageBox> #include <QStringListModel> #include <QProcess> #include <QPalette> #include "headers/aboutdialog.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); createActions(); createMenus(); settings = new QSettings("freesoft", "pudir"); loadComp(); } void MainWindow::loadComp(){ QPalette p = ui->plainTextEdit->palette(); p.setColor(QPalette::Active, QPalette::Base, Qt::black); p.setColor(QPalette::Inactive, QPalette::Base, Qt::black); p.setColor(QPalette::Text, Qt::green); ui->plainTextEdit->setPalette(p); ui->lineEdit_src_dir->setText(settings->value("sourcePath").toString()); ui->lineEdit_dest_dir->setText(settings->value("destDir").toString()); adbPath = settings->value("adbPath").toString(); if(adbPath.isEmpty()){ ui->btn_refresh->setEnabled(false); ui->btn_setsrcdir->setEnabled(false); ui->btn_push->setEnabled(false); QMessageBox msgBox; msgBox.setIcon(QMessageBox::Information); msgBox.setText("Android SDK location not set"); msgBox.setInformativeText("Please go to Option -> Set SDK"); msgBox.exec(); } } MainWindow::~MainWindow() { delete ui; } void MainWindow::createActions() { setSdkAct = new QAction(tr("&Set path Android SDK "),this); connect(setSdkAct, SIGNAL(triggered()), this, SLOT(setSdkLocation())); aboutAct = new QAction(tr("&About"),this); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); exitAct = new QAction(tr("&Exit"),this); connect(exitAct, SIGNAL(triggered()), this, SLOT(exit())); } void MainWindow::createMenus() { optionsMenu = menuBar()->addMenu(tr("&Options")); optionsMenu->addAction(setSdkAct); optionsMenu->addAction(aboutAct); optionsMenu->addAction(exitAct); } void MainWindow::setSdkLocation(){ QFileDialog dialog(this); dialog.setFileMode(QFileDialog::Directory); QStringList fileNames; if (dialog.exec()) fileNames = dialog.selectedFiles(); qDebug()<< fileNames; #ifdef __linux adbPath = fileNames.at(0)+"/platform-tools/adb"; #elif _WIN32 adbPath = fileNames.at(0)+"/platform-tools/adb.exe"; #elif __APPLE__ #endif QMessageBox msgBox; QFile *qfile = new QFile(adbPath); if(qfile->exists()){ adbPath = qfile->fileName(); settings->setValue("adbPath",adbPath); msgBox.setIcon(QMessageBox::Information); msgBox.setText("Ok"); msgBox.exec(); ui->btn_refresh->setEnabled(true); ui->btn_push->setEnabled(true); ui->btn_setsrcdir->setEnabled(true); } else{ adbPath = ""; settings->setValue("adbPath",adbPath); msgBox.setText("Wrong path"); msgBox.setIcon(QMessageBox::Critical); msgBox.exec(); setSdkLocation(); } } void MainWindow::about(){ AboutDialog aboutDial; aboutDial.exec(); } void MainWindow::exit(){ close(); } void MainWindow::on_btn_refresh_clicked() { QStringList result; QProcess process; process.start(adbPath+" devices"); process.waitForFinished(-1); QString sstdout = process.readAllStandardOutput(); QString sstderr = process.readAllStandardError(); ui->plainTextEdit->appendPlainText(sstdout); ui->plainTextEdit->appendPlainText(sstderr); qDebug() << "."+adbPath+" devices"; qDebug() << sstdout; QString aux; if(!sstdout.isEmpty()){ QStringList aux2 = sstdout.mid(sstdout.indexOf("\n")).split("\n"); foreach (const QString &str, aux2) { if (str.contains("device")){ int j = str.indexOf("\t"); result += str.left(j); } } if(result.isEmpty()) ui->btn_push->setEnabled(false); else ui->btn_push->setEnabled(true); } qDebug()<<"result"<<result; QStringListModel *typeModel = new QStringListModel(result, this); ui->comboBox->setModel(typeModel); } void MainWindow::on_btn_setsrcdir_clicked() { QFileDialog dialog(this); dialog.setFileMode(QFileDialog::Directory); if (!ui->lineEdit_src_dir->text().isEmpty()) dialog.setDirectory(ui->lineEdit_src_dir->text()); QStringList fileNames; if (dialog.exec()) fileNames = dialog.selectedFiles(); if (!fileNames.isEmpty()){ qDebug()<< fileNames; settings->setValue("sourcePath",fileNames.at(0)); ui->lineEdit_src_dir->setText(fileNames.at(0)); } } void MainWindow::on_btn_push_clicked() { QString destinationDirec = ui->lineEdit_dest_dir->text(); QString deviceid = ui->comboBox->currentText(); settings->setValue("destDir",destinationDirec); QString sstdout,sstderr; QString sourcePath = settings->value("sourcePath").toString(); QProcess process; process.start(adbPath+" -s "+deviceid +" shell rm -rf /sdcard/"+destinationDirec); process.waitForFinished(-1); ui->plainTextEdit->clear(); ui->plainTextEdit->appendPlainText(process.readAllStandardOutput()); ui->plainTextEdit->appendPlainText(process.readAllStandardError()); process.start(adbPath+" -s "+deviceid +" shell mkdir -p /sdcard/"+destinationDirec+"/default"); process.waitForFinished(-1); ui->plainTextEdit->appendPlainText(process.readAllStandardOutput()); ui->plainTextEdit->appendPlainText(process.readAllStandardError()); process.start(adbPath+" -s "+deviceid +" push \""+ sourcePath +"\" /sdcard/"+destinationDirec+"/default"); process.waitForFinished(-1); ui->plainTextEdit->appendPlainText(process.readAllStandardOutput()); ui->plainTextEdit->appendPlainText(process.readAllStandardError()); qDebug() << adbPath+" shell rm -r /sdcard/"+destinationDirec; qDebug() << adbPath+" shell shell mkdir -p /sdcard/"+destinationDirec+"/default"; qDebug() << adbPath+" push \""+ sourcePath +"\" /sdcard/"+destinationDirec+"/default"; qDebug() << sstdout; qDebug() << sstderr; } void MainWindow::on_pushButton_clicked() { ui->plainTextEdit->clear(); } <|endoftext|>
<commit_before>// Copyright 2015 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <chrono> #include <iostream> #include <stdexcept> #include <string> #include <gtest/gtest.h> #include <rclcpp/rclcpp.hpp> #include <test_rclcpp/msg/u_int32.hpp> #ifdef RMW_IMPLEMENTATION # define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX # define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX) #else # define CLASSNAME(NAME, SUFFIX) NAME #endif void callback(const test_rclcpp::msg::UInt32::SharedPtr /*msg*/) { throw std::runtime_error("Subscriber received a message and therefore didn't timeout!"); } TEST(CLASSNAME(test_timeout_subscriber, RMW_IMPLEMENTATION), timeout_subscriber) { rclcpp::init(0, nullptr); auto start = std::chrono::steady_clock::now(); auto node = rclcpp::Node::make_shared("test_timeout_subscriber"); rmw_qos_profile_t custom_qos_profile = rmw_qos_profile_default; custom_qos_profile.depth = 10; auto subscriber = node->create_subscription<test_rclcpp::msg::UInt32>( "test_message_timeout_uint32", custom_qos_profile, callback); rclcpp::executors::SingleThreadedExecutor executor; size_t num_cycles = 5; for (size_t i = 0; i < num_cycles; ++i) { auto tolerance = std::chrono::milliseconds(15); auto nonblocking_start = std::chrono::steady_clock::now(); executor.spin_node_once(node, std::chrono::milliseconds::zero()); auto nonblocking_end = std::chrono::steady_clock::now(); auto nonblocking_diff = nonblocking_end - nonblocking_start; EXPECT_LT(nonblocking_diff, tolerance); auto blocking_timeout = std::chrono::milliseconds(100); auto blocking_start = std::chrono::steady_clock::now(); executor.spin_node_once(node, blocking_timeout); auto blocking_end = std::chrono::steady_clock::now(); auto blocking_diff = blocking_end - blocking_start; EXPECT_LT(blocking_diff, blocking_timeout + tolerance); } auto end = std::chrono::steady_clock::now(); std::chrono::duration<float> diff = (end - start); std::cout << "subscribed for " << diff.count() << " seconds" << std::endl; } <commit_msg>update exception string and add comments<commit_after>// Copyright 2015 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <chrono> #include <iostream> #include <stdexcept> #include <string> #include <gtest/gtest.h> #include <rclcpp/rclcpp.hpp> #include <test_rclcpp/msg/u_int32.hpp> #ifdef RMW_IMPLEMENTATION # define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX # define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX) #else # define CLASSNAME(NAME, SUFFIX) NAME #endif void callback(const test_rclcpp::msg::UInt32::SharedPtr /*msg*/) { throw std::runtime_error("The subscriber received a message but there should be no publisher!"); } TEST(CLASSNAME(test_timeout_subscriber, RMW_IMPLEMENTATION), timeout_subscriber) { rclcpp::init(0, nullptr); auto start = std::chrono::steady_clock::now(); auto node = rclcpp::Node::make_shared("test_timeout_subscriber"); rmw_qos_profile_t custom_qos_profile = rmw_qos_profile_default; custom_qos_profile.depth = 10; auto subscriber = node->create_subscription<test_rclcpp::msg::UInt32>( "test_message_timeout_uint32", custom_qos_profile, callback); rclcpp::executors::SingleThreadedExecutor executor; size_t num_cycles = 5; for (size_t i = 0; i < num_cycles; ++i) { auto tolerance = std::chrono::milliseconds(15); // ensure that the non-blocking spin does return immediately auto nonblocking_start = std::chrono::steady_clock::now(); executor.spin_node_once(node, std::chrono::milliseconds::zero()); auto nonblocking_end = std::chrono::steady_clock::now(); auto nonblocking_diff = nonblocking_end - nonblocking_start; EXPECT_LT(nonblocking_diff, tolerance); // ensure that the blocking spin does return after the specified timeout auto blocking_timeout = std::chrono::milliseconds(100); auto blocking_start = std::chrono::steady_clock::now(); executor.spin_node_once(node, blocking_timeout); auto blocking_end = std::chrono::steady_clock::now(); auto blocking_diff = blocking_end - blocking_start; EXPECT_LT(blocking_diff, blocking_timeout + tolerance); } auto end = std::chrono::steady_clock::now(); std::chrono::duration<float> diff = (end - start); std::cout << "subscribed for " << diff.count() << " seconds" << std::endl; } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_FUNCTOR_MULTI_EXPRESSION_HPP #define STAN_MATH_PRIM_FUNCTOR_MULTI_EXPRESSION_HPP #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/err.hpp> #include <tuple> namespace stan { namespace math { namespace internal { constexpr int constexpr_sum() { return 0; } template <typename Arg0, typename... Args> constexpr int constexpr_sum(Arg0 arg0, Args... args) { return arg0 + constexpr_sum(args...); } //in rtools 3.5 g++ std::min is not constexpr //TODO(Tadej): delete this once we stop supporting rtools 3.5 constexpr int constexpr_min(int i){ return i; } template <typename Arg0, typename... Args> constexpr int constexpr_min(Arg0 arg0, Args... args) { int min_last = constexpr_min(args...); return arg0 < min_last : arg0 : min_last; } } // namespace internal /** * Represents multiple exprs that will be calculated in same loop. * @tparam T_expressions types of exprs */ template <typename... T_expressions> class eigen_expressions_ { public: /** * Constructor. * @param exprs expresions that will be calculated in same loop. * @throw invalid_argument expressions have different sizes (for row major * expressions rows and columns are swapped for the check) */ explicit eigen_expressions_(T_expressions&&... exprs) : exprs_(std::forward<T_expressions>(exprs)...) { index_apply<sizeof...(T_expressions) - 1>([&](auto... Is) { constexpr auto first_flags = Eigen::internal::evaluator<std::decay_t< std::tuple_element_t<0, std::tuple<T_expressions...>>>>::Flags; static_cast<void>(std::initializer_list<int>{ ((((Eigen::internal::evaluator<std::decay_t<std::tuple_element_t< Is + 1, std::tuple<T_expressions...>>>>::Flags ^ first_flags) & Eigen::RowMajorBit) ? check_matching_dims("eigen_expressions_.eigen_expressions_", "first expression", std::get<0>(exprs_), "transposed expression", std::get<Is + 1>(exprs_).transpose()) : check_matching_dims("eigen_expressions_.eigen_expressions_", "first expression", std::get<0>(exprs_), "expression", std::get<Is + 1>(exprs_))), 0)...}); }); } private: std::tuple<T_expressions...> exprs_; template <typename... T_results> friend class eigen_results_; }; /** * Deduces types for constructing \c expressions_ object. * @tparam T_expressions types of exprs * @param exprs exprs that will be used in same kernel. */ template <typename... T_expressions, require_all_eigen_t<T_expressions...>* = nullptr> eigen_expressions_<T_expressions...> eigen_expressions( T_expressions&&... exprs) { return eigen_expressions_<T_expressions...>( std::forward<T_expressions>(exprs)...); } /** * Represents results that will be calculated in same loop. * @tparam T_results types of results */ template <typename... T_results> class eigen_results_ { std::tuple<T_results...> results_; /** * Assign expressions to results using linear indexing. * @tparam Linear whether to use linear indexing * @tparam T_res_evals types of result evaluators * @tparam T_expr_evals types of expression evaluators * @param res_evals evaluators for results to assign to * @param expr_evals evaluators for expressions to assign * @param rows number of rows * @param cols number of cols */ template <bool Linear, typename... T_res_evals, typename... T_expr_evals, std::enable_if_t<Linear>* = nullptr> inline void assign(std::tuple<T_res_evals...>& res_evals, const std::tuple<T_expr_evals...>& expr_evals, Eigen::Index rows, Eigen::Index cols) { for (size_t i = 0; i < rows * cols; i++) { index_apply<sizeof...(T_results)>([&](auto... Is) { static_cast<void>( std::initializer_list<int>{(std::get<Is>(res_evals).coeffRef(i) = std::get<Is>(expr_evals).coeff(i), 0)...}); }); } } /** * Assign expressions to results using 2d indexing. * @tparam Linear whether to use linear indexing * @tparam T_res_evals types of result evaluators * @tparam T_expr_evals types of expression evaluators * @param res_evals evaluators for results to assign to * @param expr_evals evaluators for expressions to assign * @param rows number of rows * @param cols number of cols */ template <bool Linear, typename... T_res_evals, typename... T_expr_evals, std::enable_if_t<!Linear>* = nullptr> inline void assign(std::tuple<T_res_evals...>& res_evals, const std::tuple<T_expr_evals...>& expr_evals, Eigen::Index rows, Eigen::Index cols) { constexpr bool is_first_row_major = std::decay_t<decltype(std::get<0>(expr_evals))>::Flags & Eigen::RowMajorBit; const Eigen::Index outer_dimension = is_first_row_major ? rows : cols; const Eigen::Index inner_dimension = is_first_row_major ? cols : rows; for (size_t i = 0; i < outer_dimension; i++) { for (size_t j = 0; j < inner_dimension; j++) { index_apply<sizeof...(T_results)>([&](auto... Is) { static_cast<void>(std::initializer_list<int>{ ((std::decay_t<decltype(std::get<0>(expr_evals))>::Flags & Eigen::RowMajorBit ? std::get<Is>(res_evals).coeffRef(i, j) = std::get<Is>(expr_evals).coeff(i, j) : std::get<Is>(res_evals).coeffRef(j, i) = std::get<Is>(expr_evals).coeff(j, i)), 0)...}); }); } } } /** * Selects and calls appropriate `assign`. * @tparam T_expressions types of expressions * @param expressions expressions */ template <typename... T_expressions, std::enable_if_t<sizeof...(T_results) == sizeof...(T_expressions)>* = nullptr> void assign_select(const eigen_expressions_<T_expressions...>& expressions) { constexpr bool all_linear = internal::constexpr_min( {static_cast<bool>( Eigen::internal::evaluator<std::decay_t<T_expressions>>::Flags & Eigen::LinearAccessBit)..., static_cast<bool>( Eigen::internal::evaluator<std::decay_t<T_results>>::Flags & Eigen::LinearAccessBit)...}); constexpr int N_row_major = internal::constexpr_sum( static_cast<bool>( Eigen::internal::evaluator<std::decay_t<T_expressions>>::Flags & Eigen::RowMajorBit)..., static_cast<bool>( Eigen::internal::evaluator<std::decay_t<T_results>>::Flags & Eigen::RowMajorBit)...); constexpr int N_col_major = sizeof...(T_results) + sizeof...(T_expressions) - N_row_major; index_apply<sizeof...(T_results)>([&](auto... Is) { std::tuple<Eigen::internal::evaluator< std::decay_t<decltype(std::get<Is>(results_))>>...> result_evaluators(std::get<Is>(results_)...); std::tuple<Eigen::internal::evaluator< std::decay_t<decltype(std::get<Is>(expressions.exprs_))>>...> expression_evaluators(std::get<Is>(expressions.exprs_)...); assign<all_linear && (N_col_major == 0 || N_row_major == 0)>( result_evaluators, expression_evaluators, std::get<0>(expressions.exprs_).rows(), std::get<0>(expressions.exprs_).cols()); }); } public: /** * Constructor. * @param results results that will be calculated in same kernel */ explicit eigen_results_(T_results&&... results) : results_(std::forward<T_results>(results)...) {} /** * Assigning \c expressions_cl object to \c eigen_results_ object evals the * expressions into results. * @tparam T_expressions types of expressions * @param expressions expressions */ template <typename... T_expressions, std::enable_if_t<sizeof...(T_results) == sizeof...(T_expressions)>* = nullptr> void operator=(const eigen_expressions_<T_expressions...>& expressions) { index_apply<sizeof...(T_results)>([&, this](auto... Is) { static_cast<void>(std::initializer_list<int>{ (Eigen::internal::resize_if_allowed( std::get<Is>(results_), std::get<Is>(expressions.exprs_), Eigen::internal::assign_op<int, int>()), // types in the assign_op don't matter for the resizing 0)...}); }); assign_select(expressions); } /** * Add \c eigen_results_ to \c expressions_cl in place. * @tparam T_expressions types of expressions * @param expressions expressions */ template <typename... T_expressions, std::enable_if_t<sizeof...(T_results) == sizeof...(T_expressions)>* = nullptr> void operator+=(const eigen_expressions_<T_expressions...>& expressions) { index_apply<sizeof...(T_results)>([&, this](auto... Is) { this->assign_select(eigen_expressions(( std::get<Is>(this->results_) + std::get<Is>(expressions.exprs_))...)); }); } }; /** * Deduces types for constructing \c results_cl object. * @tparam T_results types of results * @param results results that will be calculated in same kernel. */ template <typename... T_results, require_all_eigen_t<T_results...>* = nullptr> eigen_results_<T_results...> eigen_results(T_results&&... results) { return eigen_results_<T_results...>(std::forward<T_results>(results)...); } } // namespace math } // namespace stan #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_PRIM_FUNCTOR_MULTI_EXPRESSION_HPP #define STAN_MATH_PRIM_FUNCTOR_MULTI_EXPRESSION_HPP #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/err.hpp> #include <tuple> namespace stan { namespace math { namespace internal { constexpr int constexpr_sum() { return 0; } template <typename Arg0, typename... Args> constexpr int constexpr_sum(Arg0 arg0, Args... args) { return arg0 + constexpr_sum(args...); } // in rtools 3.5 g++ std::min is not constexpr // TODO(Tadej): delete this once we stop supporting rtools 3.5 constexpr int constexpr_min(int i) { return i; } template <typename Arg0, typename... Args> constexpr int constexpr_min(Arg0 arg0, Args... args) { int min_last = constexpr_min(args...); return arg0 < min_last : arg0 : min_last; } } // namespace internal /** * Represents multiple exprs that will be calculated in same loop. * @tparam T_expressions types of exprs */ template <typename... T_expressions> class eigen_expressions_ { public: /** * Constructor. * @param exprs expresions that will be calculated in same loop. * @throw invalid_argument expressions have different sizes (for row major * expressions rows and columns are swapped for the check) */ explicit eigen_expressions_(T_expressions&&... exprs) : exprs_(std::forward<T_expressions>(exprs)...) { index_apply<sizeof...(T_expressions) - 1>([&](auto... Is) { constexpr auto first_flags = Eigen::internal::evaluator<std::decay_t< std::tuple_element_t<0, std::tuple<T_expressions...>>>>::Flags; static_cast<void>(std::initializer_list<int>{ ((((Eigen::internal::evaluator<std::decay_t<std::tuple_element_t< Is + 1, std::tuple<T_expressions...>>>>::Flags ^ first_flags) & Eigen::RowMajorBit) ? check_matching_dims("eigen_expressions_.eigen_expressions_", "first expression", std::get<0>(exprs_), "transposed expression", std::get<Is + 1>(exprs_).transpose()) : check_matching_dims("eigen_expressions_.eigen_expressions_", "first expression", std::get<0>(exprs_), "expression", std::get<Is + 1>(exprs_))), 0)...}); }); } private: std::tuple<T_expressions...> exprs_; template <typename... T_results> friend class eigen_results_; }; /** * Deduces types for constructing \c expressions_ object. * @tparam T_expressions types of exprs * @param exprs exprs that will be used in same kernel. */ template <typename... T_expressions, require_all_eigen_t<T_expressions...>* = nullptr> eigen_expressions_<T_expressions...> eigen_expressions( T_expressions&&... exprs) { return eigen_expressions_<T_expressions...>( std::forward<T_expressions>(exprs)...); } /** * Represents results that will be calculated in same loop. * @tparam T_results types of results */ template <typename... T_results> class eigen_results_ { std::tuple<T_results...> results_; /** * Assign expressions to results using linear indexing. * @tparam Linear whether to use linear indexing * @tparam T_res_evals types of result evaluators * @tparam T_expr_evals types of expression evaluators * @param res_evals evaluators for results to assign to * @param expr_evals evaluators for expressions to assign * @param rows number of rows * @param cols number of cols */ template <bool Linear, typename... T_res_evals, typename... T_expr_evals, std::enable_if_t<Linear>* = nullptr> inline void assign(std::tuple<T_res_evals...>& res_evals, const std::tuple<T_expr_evals...>& expr_evals, Eigen::Index rows, Eigen::Index cols) { for (size_t i = 0; i < rows * cols; i++) { index_apply<sizeof...(T_results)>([&](auto... Is) { static_cast<void>( std::initializer_list<int>{(std::get<Is>(res_evals).coeffRef(i) = std::get<Is>(expr_evals).coeff(i), 0)...}); }); } } /** * Assign expressions to results using 2d indexing. * @tparam Linear whether to use linear indexing * @tparam T_res_evals types of result evaluators * @tparam T_expr_evals types of expression evaluators * @param res_evals evaluators for results to assign to * @param expr_evals evaluators for expressions to assign * @param rows number of rows * @param cols number of cols */ template <bool Linear, typename... T_res_evals, typename... T_expr_evals, std::enable_if_t<!Linear>* = nullptr> inline void assign(std::tuple<T_res_evals...>& res_evals, const std::tuple<T_expr_evals...>& expr_evals, Eigen::Index rows, Eigen::Index cols) { constexpr bool is_first_row_major = std::decay_t<decltype(std::get<0>(expr_evals))>::Flags & Eigen::RowMajorBit; const Eigen::Index outer_dimension = is_first_row_major ? rows : cols; const Eigen::Index inner_dimension = is_first_row_major ? cols : rows; for (size_t i = 0; i < outer_dimension; i++) { for (size_t j = 0; j < inner_dimension; j++) { index_apply<sizeof...(T_results)>([&](auto... Is) { static_cast<void>(std::initializer_list<int>{ ((std::decay_t<decltype(std::get<0>(expr_evals))>::Flags & Eigen::RowMajorBit ? std::get<Is>(res_evals).coeffRef(i, j) = std::get<Is>(expr_evals).coeff(i, j) : std::get<Is>(res_evals).coeffRef(j, i) = std::get<Is>(expr_evals).coeff(j, i)), 0)...}); }); } } } /** * Selects and calls appropriate `assign`. * @tparam T_expressions types of expressions * @param expressions expressions */ template <typename... T_expressions, std::enable_if_t<sizeof...(T_results) == sizeof...(T_expressions)>* = nullptr> void assign_select(const eigen_expressions_<T_expressions...>& expressions) { constexpr bool all_linear = internal::constexpr_min( {static_cast<bool>( Eigen::internal::evaluator<std::decay_t<T_expressions>>::Flags & Eigen::LinearAccessBit)..., static_cast<bool>( Eigen::internal::evaluator<std::decay_t<T_results>>::Flags & Eigen::LinearAccessBit)...}); constexpr int N_row_major = internal::constexpr_sum( static_cast<bool>( Eigen::internal::evaluator<std::decay_t<T_expressions>>::Flags & Eigen::RowMajorBit)..., static_cast<bool>( Eigen::internal::evaluator<std::decay_t<T_results>>::Flags & Eigen::RowMajorBit)...); constexpr int N_col_major = sizeof...(T_results) + sizeof...(T_expressions) - N_row_major; index_apply<sizeof...(T_results)>([&](auto... Is) { std::tuple<Eigen::internal::evaluator< std::decay_t<decltype(std::get<Is>(results_))>>...> result_evaluators(std::get<Is>(results_)...); std::tuple<Eigen::internal::evaluator< std::decay_t<decltype(std::get<Is>(expressions.exprs_))>>...> expression_evaluators(std::get<Is>(expressions.exprs_)...); assign<all_linear && (N_col_major == 0 || N_row_major == 0)>( result_evaluators, expression_evaluators, std::get<0>(expressions.exprs_).rows(), std::get<0>(expressions.exprs_).cols()); }); } public: /** * Constructor. * @param results results that will be calculated in same kernel */ explicit eigen_results_(T_results&&... results) : results_(std::forward<T_results>(results)...) {} /** * Assigning \c expressions_cl object to \c eigen_results_ object evals the * expressions into results. * @tparam T_expressions types of expressions * @param expressions expressions */ template <typename... T_expressions, std::enable_if_t<sizeof...(T_results) == sizeof...(T_expressions)>* = nullptr> void operator=(const eigen_expressions_<T_expressions...>& expressions) { index_apply<sizeof...(T_results)>([&, this](auto... Is) { static_cast<void>(std::initializer_list<int>{ (Eigen::internal::resize_if_allowed( std::get<Is>(results_), std::get<Is>(expressions.exprs_), Eigen::internal::assign_op<int, int>()), // types in the assign_op don't matter for the resizing 0)...}); }); assign_select(expressions); } /** * Add \c eigen_results_ to \c expressions_cl in place. * @tparam T_expressions types of expressions * @param expressions expressions */ template <typename... T_expressions, std::enable_if_t<sizeof...(T_results) == sizeof...(T_expressions)>* = nullptr> void operator+=(const eigen_expressions_<T_expressions...>& expressions) { index_apply<sizeof...(T_results)>([&, this](auto... Is) { this->assign_select(eigen_expressions(( std::get<Is>(this->results_) + std::get<Is>(expressions.exprs_))...)); }); } }; /** * Deduces types for constructing \c results_cl object. * @tparam T_results types of results * @param results results that will be calculated in same kernel. */ template <typename... T_results, require_all_eigen_t<T_results...>* = nullptr> eigen_results_<T_results...> eigen_results(T_results&&... results) { return eigen_results_<T_results...>(std::forward<T_results>(results)...); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief binary-compatible std::complex faster implementation * * For some reason, the compilers are not inlining std::complex * operations, resulting in way slower code. This template is * binary-compatible so it can be reinterpreted as to one another * and its operations can be inlined easily. This results in much * faster code for FFT for instance. */ #pragma once namespace etl { /*! * \brief Complex number implementation * * This implementation is binary-compatible with std::complex. This * implementation is not opaque like std::complex and its operation can be * inlined. */ template <typename T> struct complex { using value_type = T; ///< The value type value_type real; ///< The real part value_type imag; ///< The imaginary part /*! * \brief Construct a complex number * \param re The real part * \param im The imaginary part */ constexpr complex(const T& re = T(), const T& im = T()) : real(re), imag(im) {} /*! * \brief Construct a complex number by copy * \param rhs The complex to copy from */ constexpr complex(const complex& rhs) : real(rhs.real), imag(rhs.imag) {} /*! * \brief Assign a real part to the complex number * \param rhs The real part * \return a reference to this */ complex& operator=(const T& rhs) noexcept { real = rhs; imag = 0.0; return *this; } /*! * \brief Assign a complex number by copy * \param rhs The complex number to copy * \return a reference to this */ complex& operator=(const complex& rhs) noexcept { real = rhs.real; imag = rhs.imag; return *this; } /*! * \brief Assign a complex number by copy * \param rhs The complex number to copy * \return a reference to this */ complex& operator=(const std::complex<T>& rhs) noexcept { real = rhs.real(); imag = rhs.imag(); return *this; } /*! * \brief Adds a complex number * \param rhs The complex number to add * \return a reference to this */ complex& operator+=(const complex& rhs) { real += rhs.real; imag += rhs.imag; return *this; } /*! * \brief Subtracts a complex number * \param rhs The complex number to add * \return a reference to this */ complex& operator-=(const complex& rhs) { real -= rhs.real; imag -= rhs.imag; return *this; } /*! * \brief Multipliies a complex number * \param rhs The complex number to add * \return a reference to this */ complex& operator*=(const complex& rhs) { T ac = real * rhs.real; T bd = imag * rhs.imag; T bc = imag * rhs.real; T ad = real * rhs.imag; real = ac - bd; imag = bc + ad; return *this; } /*! * \brief Divides a complex number * \param rhs The complex number to add * \return a reference to this */ complex& operator/=(const complex& rhs) { T ac = real * rhs.real; T bd = imag * rhs.imag; T bc = imag * rhs.real; T ad = real * rhs.imag; T frac = rhs.real * rhs.real + rhs.imag * rhs.imag; real = (ac + bd) / frac; imag = (bc - ad) / frac; return *this; } }; /*! * \brief Test two complex numbers for equality * \param lhs The left hand side complex * \param rhs The right hand side complex * \return true if the numbers are equals, false otherwise */ template <typename T> inline bool operator==(const complex<T>& lhs, const complex<T>& rhs) { return lhs.real == rhs.real && lhs.imag == rhs.imag; } /*! * \brief Test two complex numbers for inequality * \param lhs The left hand side complex * \param rhs The right hand side complex * \return true if the numbers are not equals, false otherwise */ template <typename T> inline bool operator!=(const complex<T>& lhs, const complex<T>& rhs) { return !(lhs == rhs); } /*! * \brief Returns a complex number with the value of -rhs * \param rhs The right hand side complex * \return a complex number with the value of -rhs */ template <typename T> inline complex<T> operator-(complex<T> rhs) { return {-rhs.real, -rhs.imag}; } /*! * \brief Computes the addition of two complex numbers * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the addition of the two complex numbers */ template <typename T> inline complex<T> operator+(const complex<T>& lhs, const complex<T>& rhs) { return {lhs.real + rhs.real, lhs.imag + rhs.imag}; } /*! * \brief Computes the subtraction of two complex numbers * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the subtraction of the two complex numbers */ template <typename T> inline complex<T> operator-(const complex<T>& lhs, const complex<T>& rhs) { return {lhs.real - rhs.real, lhs.imag - rhs.imag}; } /*! * \brief Computes the multiplication of two complex numbers * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the multiplication of the two complex numbers */ template <typename T> inline complex<T> operator*(const complex<T>& lhs, const complex<T>& rhs) { T ac = lhs.real * rhs.real; T bd = lhs.imag * rhs.imag; T bc = lhs.imag * rhs.real; T ad = lhs.real * rhs.imag; return {ac - bd, bc + ad}; } /*! * \brief Computes the multiplication of a complex number and a scalar * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the multiplication of a complex number and a scalar */ template <typename T> inline complex<T> operator*(const complex<T>& lhs, T rhs) { return {lhs.real * rhs, lhs.imag * rhs}; } /*! * \brief Computes the multiplication of a complex number and a scalar * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the multiplication of a complex number and a scalar */ template <typename T> inline complex<T> operator*(T lhs, const complex<T>& rhs) { return {lhs * rhs.real, lhs * rhs.imag}; } /*! * \brief Computes the division of a complex number and a scalar * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the multiplication of a complex number and a scalar */ template <typename T> inline complex<T> operator/(const complex<T>& lhs, T rhs) { return {lhs.real / rhs, lhs.imag / rhs}; } /*! * \brief Computes the division of two complex numbers * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the division of the two complex numbers */ template <typename T> inline complex<T> operator/(const complex<T>& lhs, const complex<T>& rhs) { T ac = lhs.real * rhs.real; T bd = lhs.imag * rhs.imag; T bc = lhs.imag * rhs.real; T ad = lhs.real * rhs.imag; T frac = rhs.real * rhs.real + rhs.imag * rhs.imag; return {(ac + bd) / frac, (bc - ad) / frac}; } /*! * \brief Returns the inverse of the complex number * \param x The complex number * \return The inverse of the complex number */ template <typename T> inline complex<T> inverse(complex<T> x) { return {x.imag, x.real}; } /*! * \brief Returns the inverse of the conjugate of the complex number * \param x The complex number * \return The inverse of the conjugate of the complex number */ template <typename T> inline complex<T> inverse_conj(complex<T> x) { return {-x.imag, x.real}; } /*! * \brief Returns the conjugate of the inverse of the complex number * \param x The complex number * \return The conjugate of the inverse of the complex number */ template <typename T> inline complex<T> conj_inverse(complex<T> x) { return {x.imag, -x.real}; } /*! * \brief Returns the conjugate of the complex number * \param c The complex number * \return The conjugate of the complex number */ template <typename T> inline complex<T> conj(const complex<T>& c) { return {c.real, -c.imag}; } /*! * \brief Returns the imaginary part of the given complex number * \param c The complex number * \return the imaginary part of the given complex number */ template <typename T> inline T get_imag(const std::complex<T>& c) { return c.imag(); } /*! * \brief Returns the imaginary part of the given complex number * \param c The complex number * \return the imaginary part of the given complex number */ template <typename T> inline T get_imag(const etl::complex<T>& c) { return c.imag; } /*! * \brief Returns the real part of the given complex number * \param c The complex number * \return the real part of the given complex number */ template <typename T> inline T get_real(const std::complex<T>& c) { return c.real(); } /*! * \brief Returns the real part of the given complex number * \param c The complex number * \return the real part of the given complex number */ template <typename T> inline T get_real(const etl::complex<T>& c) { return c.real; } /*! * \brief Returns the conjugate of the given complex number * \param c The complex number * \return the conjugate of the given complex number */ template <typename T> inline std::complex<T> get_conj(const std::complex<T>& c) { return std::conj(c); } /*! * \brief Returns the conjugate of the given complex number * \param c The complex number * \return the conjugate of the given complex number */ template <typename T> inline etl::complex<T> get_conj(const etl::complex<T>& c) { return {c.real, -c.imag}; } } //end of namespace etl <commit_msg>Add support for operator<< on etl::complex<commit_after>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief binary-compatible std::complex faster implementation * * For some reason, the compilers are not inlining std::complex * operations, resulting in way slower code. This template is * binary-compatible so it can be reinterpreted as to one another * and its operations can be inlined easily. This results in much * faster code for FFT for instance. */ #pragma once namespace etl { /*! * \brief Complex number implementation * * This implementation is binary-compatible with std::complex. This * implementation is not opaque like std::complex and its operation can be * inlined. */ template <typename T> struct complex { using value_type = T; ///< The value type value_type real; ///< The real part value_type imag; ///< The imaginary part /*! * \brief Construct a complex number * \param re The real part * \param im The imaginary part */ constexpr complex(const T& re = T(), const T& im = T()) : real(re), imag(im) {} /*! * \brief Construct a complex number by copy * \param rhs The complex to copy from */ constexpr complex(const complex& rhs) : real(rhs.real), imag(rhs.imag) {} /*! * \brief Assign a real part to the complex number * \param rhs The real part * \return a reference to this */ complex& operator=(const T& rhs) noexcept { real = rhs; imag = 0.0; return *this; } /*! * \brief Assign a complex number by copy * \param rhs The complex number to copy * \return a reference to this */ complex& operator=(const complex& rhs) noexcept { real = rhs.real; imag = rhs.imag; return *this; } /*! * \brief Assign a complex number by copy * \param rhs The complex number to copy * \return a reference to this */ complex& operator=(const std::complex<T>& rhs) noexcept { real = rhs.real(); imag = rhs.imag(); return *this; } /*! * \brief Adds a complex number * \param rhs The complex number to add * \return a reference to this */ complex& operator+=(const complex& rhs) { real += rhs.real; imag += rhs.imag; return *this; } /*! * \brief Subtracts a complex number * \param rhs The complex number to add * \return a reference to this */ complex& operator-=(const complex& rhs) { real -= rhs.real; imag -= rhs.imag; return *this; } /*! * \brief Multipliies a complex number * \param rhs The complex number to add * \return a reference to this */ complex& operator*=(const complex& rhs) { T ac = real * rhs.real; T bd = imag * rhs.imag; T bc = imag * rhs.real; T ad = real * rhs.imag; real = ac - bd; imag = bc + ad; return *this; } /*! * \brief Divides a complex number * \param rhs The complex number to add * \return a reference to this */ complex& operator/=(const complex& rhs) { T ac = real * rhs.real; T bd = imag * rhs.imag; T bc = imag * rhs.real; T ad = real * rhs.imag; T frac = rhs.real * rhs.real + rhs.imag * rhs.imag; real = (ac + bd) / frac; imag = (bc - ad) / frac; return *this; } }; /*! * \brief Test two complex numbers for equality * \param lhs The left hand side complex * \param rhs The right hand side complex * \return true if the numbers are equals, false otherwise */ template <typename T> inline bool operator==(const complex<T>& lhs, const complex<T>& rhs) { return lhs.real == rhs.real && lhs.imag == rhs.imag; } /*! * \brief Test two complex numbers for inequality * \param lhs The left hand side complex * \param rhs The right hand side complex * \return true if the numbers are not equals, false otherwise */ template <typename T> inline bool operator!=(const complex<T>& lhs, const complex<T>& rhs) { return !(lhs == rhs); } /*! * \brief Returns a complex number with the value of -rhs * \param rhs The right hand side complex * \return a complex number with the value of -rhs */ template <typename T> inline complex<T> operator-(complex<T> rhs) { return {-rhs.real, -rhs.imag}; } /*! * \brief Computes the addition of two complex numbers * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the addition of the two complex numbers */ template <typename T> inline complex<T> operator+(const complex<T>& lhs, const complex<T>& rhs) { return {lhs.real + rhs.real, lhs.imag + rhs.imag}; } /*! * \brief Computes the subtraction of two complex numbers * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the subtraction of the two complex numbers */ template <typename T> inline complex<T> operator-(const complex<T>& lhs, const complex<T>& rhs) { return {lhs.real - rhs.real, lhs.imag - rhs.imag}; } /*! * \brief Computes the multiplication of two complex numbers * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the multiplication of the two complex numbers */ template <typename T> inline complex<T> operator*(const complex<T>& lhs, const complex<T>& rhs) { T ac = lhs.real * rhs.real; T bd = lhs.imag * rhs.imag; T bc = lhs.imag * rhs.real; T ad = lhs.real * rhs.imag; return {ac - bd, bc + ad}; } /*! * \brief Computes the multiplication of a complex number and a scalar * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the multiplication of a complex number and a scalar */ template <typename T> inline complex<T> operator*(const complex<T>& lhs, T rhs) { return {lhs.real * rhs, lhs.imag * rhs}; } /*! * \brief Computes the multiplication of a complex number and a scalar * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the multiplication of a complex number and a scalar */ template <typename T> inline complex<T> operator*(T lhs, const complex<T>& rhs) { return {lhs * rhs.real, lhs * rhs.imag}; } /*! * \brief Computes the division of a complex number and a scalar * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the multiplication of a complex number and a scalar */ template <typename T> inline complex<T> operator/(const complex<T>& lhs, T rhs) { return {lhs.real / rhs, lhs.imag / rhs}; } /*! * \brief Computes the division of two complex numbers * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the division of the two complex numbers */ template <typename T> inline complex<T> operator/(const complex<T>& lhs, const complex<T>& rhs) { T ac = lhs.real * rhs.real; T bd = lhs.imag * rhs.imag; T bc = lhs.imag * rhs.real; T ad = lhs.real * rhs.imag; T frac = rhs.real * rhs.real + rhs.imag * rhs.imag; return {(ac + bd) / frac, (bc - ad) / frac}; } /*! * \brief Returns the inverse of the complex number * \param x The complex number * \return The inverse of the complex number */ template <typename T> inline complex<T> inverse(complex<T> x) { return {x.imag, x.real}; } /*! * \brief Returns the inverse of the conjugate of the complex number * \param x The complex number * \return The inverse of the conjugate of the complex number */ template <typename T> inline complex<T> inverse_conj(complex<T> x) { return {-x.imag, x.real}; } /*! * \brief Returns the conjugate of the inverse of the complex number * \param x The complex number * \return The conjugate of the inverse of the complex number */ template <typename T> inline complex<T> conj_inverse(complex<T> x) { return {x.imag, -x.real}; } /*! * \brief Returns the conjugate of the complex number * \param c The complex number * \return The conjugate of the complex number */ template <typename T> inline complex<T> conj(const complex<T>& c) { return {c.real, -c.imag}; } /*! * \brief Returns the imaginary part of the given complex number * \param c The complex number * \return the imaginary part of the given complex number */ template <typename T> inline T get_imag(const std::complex<T>& c) { return c.imag(); } /*! * \brief Returns the imaginary part of the given complex number * \param c The complex number * \return the imaginary part of the given complex number */ template <typename T> inline T get_imag(const etl::complex<T>& c) { return c.imag; } /*! * \brief Returns the real part of the given complex number * \param c The complex number * \return the real part of the given complex number */ template <typename T> inline T get_real(const std::complex<T>& c) { return c.real(); } /*! * \brief Returns the real part of the given complex number * \param c The complex number * \return the real part of the given complex number */ template <typename T> inline T get_real(const etl::complex<T>& c) { return c.real; } /*! * \brief Returns the conjugate of the given complex number * \param c The complex number * \return the conjugate of the given complex number */ template <typename T> inline std::complex<T> get_conj(const std::complex<T>& c) { return std::conj(c); } /*! * \brief Returns the conjugate of the given complex number * \param c The complex number * \return the conjugate of the given complex number */ template <typename T> inline etl::complex<T> get_conj(const etl::complex<T>& c) { return {c.real, -c.imag}; } /*! * \brief Outputs a textual representation of the complex number in the given stream * \param os The stream to output to * \param c The complex number to get representation from * \param return The output stream */ * template <typename T> std::ostream& operator<<(std::ostream& os, const etl::complex<T>& c){ return os << "C(" << c.real << "," << c.imag << ")"; } } //end of namespace etl <|endoftext|>
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004 - 2008 Olof Naessn and Per Larsson * * * Per Larsson a.k.a finalman * Olof Naessn a.k.a jansem/yakslem * * Visit: http://guichan.sourceforge.net * * License: (BSD) * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of Guichan nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GCN_KEY_HPP #define GCN_KEY_HPP #include "guichan/platform.hpp" // windows.h defines DELETE which breaks this file as we have a constant named // DELETE, hence we undefine DELETE if it is defined and hope people don't use // that windows define with Guichan. #if defined (_WIN32) && defined(DELETE) #undef DELETE #endif namespace gcn { /** * Represents a key or a character. */ class GCN_CORE_DECLSPEC Key { public: /** * Constructor. * * @param value The ascii or enum value for the key. */ Key(int value = 0); /** * Checks if a key is a character. * * @return True if the key is a letter, number or whitespace, * false otherwise. */ bool isCharacter() const; /** * Checks if a key is a number. * * @return True if the key is a number (0-9), * false otherwise. */ bool isNumber() const; /** * Checks if a key is a letter. * * @return True if the key is a letter (a-z,A-Z), * false otherwise. */ bool isLetter() const; /** * Gets the value of the key. If an ascii value exists it * will be returned. Otherwise an enum value will be returned. * * @return the value of the key. */ int getValue() const; /** * Compares to keys. * * @param key The key to compare this key with. * @return True if the keys are equal, false otherwise. */ bool operator==(const Key& key) const; /** * Compares to keys. * * @param key The key to compare this key with. * @return True if the keys are not equal, false otherwise. */ bool operator!=(const Key& key) const; /** * An enum with key values. */ enum { SPACE = ' ', TAB = '\t', ENTER = '\n', LEFT_ALT = 1000, RIGHT_ALT, LEFT_SHIFT, RIGHT_SHIFT, LEFT_CONTROL, RIGHT_CONTROL, LEFT_META, RIGHT_META, LEFT_SUPER, RIGHT_SUPER, INSERT, HOME, PAGE_UP, DELETE, END, PAGE_DOWN, ESCAPE, CAPS_LOCK, BACKSPACE, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, PRINT_SCREEN, SCROLL_LOCK, PAUSE, NUM_LOCK, ALT_GR, LEFT, RIGHT, UP, DOWN }; protected: /** * Holds the value of the key. It may be an ascii value * or an enum value. */ int mValue; }; } #endif // end GCN_KEY_HPP <commit_msg>Fix whitespace and two of the same typos<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004 - 2008 Olof Naessn and Per Larsson * * * Per Larsson a.k.a finalman * Olof Naessn a.k.a jansem/yakslem * * Visit: http://guichan.sourceforge.net * * License: (BSD) * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of Guichan nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GCN_KEY_HPP #define GCN_KEY_HPP #include "guichan/platform.hpp" // windows.h defines DELETE which breaks this file as we have a constant named // DELETE, hence we undefine DELETE if it is defined and hope people don't use // that windows define with Guichan. #if defined (_WIN32) && defined(DELETE) #undef DELETE #endif namespace gcn { /** * Represents a key or a character. */ class GCN_CORE_DECLSPEC Key { public: /** * Constructor. * * @param value The ascii or enum value for the key. */ Key(int value = 0); /** * Checks if a key is a character. * * @return True if the key is a letter, number or whitespace, * false otherwise. */ bool isCharacter() const; /** * Checks if a key is a number. * * @return True if the key is a number (0-9), * false otherwise. */ bool isNumber() const; /** * Checks if a key is a letter. * * @return True if the key is a letter (a-z,A-Z), * false otherwise. */ bool isLetter() const; /** * Gets the value of the key. If an ascii value exists it * will be returned. Otherwise an enum value will be returned. * * @return the value of the key. */ int getValue() const; /** * Compares two keys. * * @param key The key to compare this key with. * @return True if the keys are equal, false otherwise. */ bool operator==(const Key& key) const; /** * Compares two keys. * * @param key The key to compare this key with. * @return True if the keys are not equal, false otherwise. */ bool operator!=(const Key& key) const; /** * An enum with key values. */ enum { SPACE = ' ', TAB = '\t', ENTER = '\n', LEFT_ALT = 1000, RIGHT_ALT, LEFT_SHIFT, RIGHT_SHIFT, LEFT_CONTROL, RIGHT_CONTROL, LEFT_META, RIGHT_META, LEFT_SUPER, RIGHT_SUPER, INSERT, HOME, PAGE_UP, DELETE, END, PAGE_DOWN, ESCAPE, CAPS_LOCK, BACKSPACE, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, PRINT_SCREEN, SCROLL_LOCK, PAUSE, NUM_LOCK, ALT_GR, LEFT, RIGHT, UP, DOWN }; protected: /** * Holds the value of the key. It may be an ascii value * or an enum value. */ int mValue; }; } #endif // end GCN_KEY_HPP <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef DBN_IMAGE_UTILS_HPP #define DBN_IMAGE_UTILS_HPP template<typename T> typename std::enable_if<!std::numeric_limits<T>::is_signed, void>::type binarize(std::vector<T>& values){ auto middle = std::numeric_limits<T>::max() / 2; for(auto& v : values){ v = v > middle ? 1 : 0; } } template<typename T> typename std::enable_if<!std::numeric_limits<T>::is_signed, void>::type binarize_each(std::vector<std::vector<T>>& values){ for(auto& v : values){ binarize(v); } } #endif <commit_msg>Review binarization<commit_after>//======================================================================= // Copyright Baptiste Wicht 2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef DBN_IMAGE_UTILS_HPP #define DBN_IMAGE_UTILS_HPP template<typename T> typename std::enable_if<!std::numeric_limits<T>::is_signed, void>::type binarize(std::vector<T>& values){ auto middle = std::numeric_limits<T>::max() / 2; for(auto& v : values){ v = v > 10 ? 1 : 0; } } template<typename T> typename std::enable_if<!std::numeric_limits<T>::is_signed, void>::type binarize_each(std::vector<std::vector<T>>& values){ for(auto& v : values){ binarize(v); } } #endif <|endoftext|>
<commit_before>/* The MIT License (MIT) * * Copyright (c) 2014-2018 David Medina and Tim Warburton * * 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 */ #include <occa/core/base.hpp> #include <occa/mode.hpp> #include <occa/tools/env.hpp> #include <occa/tools/sys.hpp> #include <occa/tools/tls.hpp> namespace occa { //---[ Device Functions ]------------- device host() { static tls<device> tdev; device &dev = tdev.value(); if (!dev.isInitialized()) { dev = occa::device(newModeDevice("mode: 'Serial'")); dev.dontUseRefs(); } return dev; } device& getDevice() { static tls<device> tdev; device &dev = tdev.value(); if (!dev.isInitialized()) { dev = host(); } return dev; } void setDevice(device d) { getDevice() = d; } void setDevice(const occa::properties &props) { getDevice() = device(props); } const occa::properties& deviceProperties() { return getDevice().properties(); } void loadKernels(const std::string &library) { getDevice().loadKernels(library); } void finish() { getDevice().finish(); } void waitFor(streamTag tag) { getDevice().waitFor(tag); } double timeBetween(const streamTag &startTag, const streamTag &endTag) { return getDevice().timeBetween(startTag, endTag); } stream createStream(const occa::properties &props) { return getDevice().createStream(props); } stream getStream() { return getDevice().getStream(); } void setStream(stream s) { getDevice().setStream(s); } streamTag tagStream() { return getDevice().tagStream(); } //---[ Kernel Functions ]------------- kernel buildKernel(const std::string &filename, const std::string &kernelName, const occa::properties &props) { return getDevice().buildKernel(filename, kernelName, props); } kernel buildKernelFromString(const std::string &content, const std::string &kernelName, const occa::properties &props) { return getDevice().buildKernelFromString(content, kernelName, props); } kernel buildKernelFromBinary(const std::string &filename, const std::string &kernelName, const occa::properties &props) { return getDevice().buildKernelFromBinary(filename, kernelName, props); } //---[ Memory Functions ]------------- occa::memory malloc(const dim_t bytes, const void *src, const occa::properties &props) { return getDevice().malloc(bytes, src, props); } void* umalloc(const dim_t bytes, const void *src, const occa::properties &props) { return getDevice().umalloc(bytes, src, props); } void memcpy(void *dest, const void *src, const dim_t bytes, const occa::properties &props) { ptrRangeMap::iterator srcIt = uvaMap.find(const_cast<void*>(src)); ptrRangeMap::iterator destIt = uvaMap.find(dest); occa::modeMemory_t *srcMem = ((srcIt != uvaMap.end()) ? (srcIt->second) : NULL); occa::modeMemory_t *destMem = ((destIt != uvaMap.end()) ? (destIt->second) : NULL); const udim_t srcOff = (srcMem ? (((char*) src) - srcMem->uvaPtr) : 0); const udim_t destOff = (destMem ? (((char*) dest) - destMem->uvaPtr) : 0); const bool usingSrcPtr = (!srcMem || ((srcMem->isManaged() && !srcMem->inDevice()))); const bool usingDestPtr = (!destMem || ((destMem->isManaged() && !destMem->inDevice()))); if (usingSrcPtr && usingDestPtr) { udim_t bytes_ = bytes; if (bytes == -1) { OCCA_ERROR("Unable to determine bytes to copy", srcMem || destMem); bytes_ = (srcMem ? srcMem->size : destMem->size); } ::memcpy(dest, src, bytes_); return; } if (usingSrcPtr) { destMem->copyFrom(src, bytes, destOff, props); } else if (usingDestPtr) { srcMem->copyTo(dest, bytes, srcOff, props); } else { // Auto-detects peer-to-peer stuff occa::memory srcMemory(srcMem); occa::memory destMemory(destMem); destMemory.copyFrom(srcMemory, bytes, destOff, srcOff, props); } } void memcpy(memory dest, const void *src, const dim_t bytes, const dim_t offset, const occa::properties &props) { dest.copyFrom(src, bytes, offset, props); } void memcpy(void *dest, memory src, const dim_t bytes, const dim_t offset, const occa::properties &props) { src.copyTo(dest, bytes, offset, props); } void memcpy(memory dest, memory src, const dim_t bytes, const dim_t destOffset, const dim_t srcOffset, const occa::properties &props) { dest.copyFrom(src, bytes, destOffset, srcOffset, props); } void memcpy(void *dest, const void *src, const occa::properties &props) { memcpy(dest, src, -1, props); } void memcpy(memory dest, const void *src, const occa::properties &props) { memcpy(dest, src, -1, 0, props); } void memcpy(void *dest, memory src, const occa::properties &props) { memcpy(dest, src, -1, 0, props); } void memcpy(memory dest, memory src, const occa::properties &props) { memcpy(dest, src, -1, 0, 0, props); } //==================================== //---[ Free Functions ]--------------- void free(device d) { d.free(); } void free(stream s) { s.free(); } void free(kernel k) { k.free(); } void free(memory m) { m.free(); } //==================================== void printModeInfo() { strToModeMap &modes = modeMap(); strToModeMapIterator it = modes.begin(); styling::table table; int serialIdx = 0; int idx = 0; while (it != modes.end()) { if (it->first == "Serial") { serialIdx = idx; } table.add(it->second->getDescription()); ++it; ++idx; } styling::section serialSection = table.sections[serialIdx]; table.sections[serialIdx] = table.sections[0]; table.sections[0] = serialSection; std::cout << table; } } <commit_msg>[Core] Host wasn't initialized properly<commit_after>/* The MIT License (MIT) * * Copyright (c) 2014-2018 David Medina and Tim Warburton * * 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 */ #include <occa/core/base.hpp> #include <occa/mode.hpp> #include <occa/tools/env.hpp> #include <occa/tools/sys.hpp> #include <occa/tools/tls.hpp> namespace occa { //---[ Device Functions ]------------- device host() { static tls<device> tdev; device &dev = tdev.value(); if (!dev.isInitialized()) { dev = occa::device("mode: 'Serial'"); dev.dontUseRefs(); } return dev; } device& getDevice() { static tls<device> tdev; device &dev = tdev.value(); if (!dev.isInitialized()) { dev = host(); } return dev; } void setDevice(device d) { getDevice() = d; } void setDevice(const occa::properties &props) { getDevice() = device(props); } const occa::properties& deviceProperties() { return getDevice().properties(); } void loadKernels(const std::string &library) { getDevice().loadKernels(library); } void finish() { getDevice().finish(); } void waitFor(streamTag tag) { getDevice().waitFor(tag); } double timeBetween(const streamTag &startTag, const streamTag &endTag) { return getDevice().timeBetween(startTag, endTag); } stream createStream(const occa::properties &props) { return getDevice().createStream(props); } stream getStream() { return getDevice().getStream(); } void setStream(stream s) { getDevice().setStream(s); } streamTag tagStream() { return getDevice().tagStream(); } //---[ Kernel Functions ]------------- kernel buildKernel(const std::string &filename, const std::string &kernelName, const occa::properties &props) { return getDevice().buildKernel(filename, kernelName, props); } kernel buildKernelFromString(const std::string &content, const std::string &kernelName, const occa::properties &props) { return getDevice().buildKernelFromString(content, kernelName, props); } kernel buildKernelFromBinary(const std::string &filename, const std::string &kernelName, const occa::properties &props) { return getDevice().buildKernelFromBinary(filename, kernelName, props); } //---[ Memory Functions ]------------- occa::memory malloc(const dim_t bytes, const void *src, const occa::properties &props) { return getDevice().malloc(bytes, src, props); } void* umalloc(const dim_t bytes, const void *src, const occa::properties &props) { return getDevice().umalloc(bytes, src, props); } void memcpy(void *dest, const void *src, const dim_t bytes, const occa::properties &props) { ptrRangeMap::iterator srcIt = uvaMap.find(const_cast<void*>(src)); ptrRangeMap::iterator destIt = uvaMap.find(dest); occa::modeMemory_t *srcMem = ((srcIt != uvaMap.end()) ? (srcIt->second) : NULL); occa::modeMemory_t *destMem = ((destIt != uvaMap.end()) ? (destIt->second) : NULL); const udim_t srcOff = (srcMem ? (((char*) src) - srcMem->uvaPtr) : 0); const udim_t destOff = (destMem ? (((char*) dest) - destMem->uvaPtr) : 0); const bool usingSrcPtr = (!srcMem || ((srcMem->isManaged() && !srcMem->inDevice()))); const bool usingDestPtr = (!destMem || ((destMem->isManaged() && !destMem->inDevice()))); if (usingSrcPtr && usingDestPtr) { udim_t bytes_ = bytes; if (bytes == -1) { OCCA_ERROR("Unable to determine bytes to copy", srcMem || destMem); bytes_ = (srcMem ? srcMem->size : destMem->size); } ::memcpy(dest, src, bytes_); return; } if (usingSrcPtr) { destMem->copyFrom(src, bytes, destOff, props); } else if (usingDestPtr) { srcMem->copyTo(dest, bytes, srcOff, props); } else { // Auto-detects peer-to-peer stuff occa::memory srcMemory(srcMem); occa::memory destMemory(destMem); destMemory.copyFrom(srcMemory, bytes, destOff, srcOff, props); } } void memcpy(memory dest, const void *src, const dim_t bytes, const dim_t offset, const occa::properties &props) { dest.copyFrom(src, bytes, offset, props); } void memcpy(void *dest, memory src, const dim_t bytes, const dim_t offset, const occa::properties &props) { src.copyTo(dest, bytes, offset, props); } void memcpy(memory dest, memory src, const dim_t bytes, const dim_t destOffset, const dim_t srcOffset, const occa::properties &props) { dest.copyFrom(src, bytes, destOffset, srcOffset, props); } void memcpy(void *dest, const void *src, const occa::properties &props) { memcpy(dest, src, -1, props); } void memcpy(memory dest, const void *src, const occa::properties &props) { memcpy(dest, src, -1, 0, props); } void memcpy(void *dest, memory src, const occa::properties &props) { memcpy(dest, src, -1, 0, props); } void memcpy(memory dest, memory src, const occa::properties &props) { memcpy(dest, src, -1, 0, 0, props); } //==================================== //---[ Free Functions ]--------------- void free(device d) { d.free(); } void free(stream s) { s.free(); } void free(kernel k) { k.free(); } void free(memory m) { m.free(); } //==================================== void printModeInfo() { strToModeMap &modes = modeMap(); strToModeMapIterator it = modes.begin(); styling::table table; int serialIdx = 0; int idx = 0; while (it != modes.end()) { if (it->first == "Serial") { serialIdx = idx; } table.add(it->second->getDescription()); ++it; ++idx; } styling::section serialSection = table.sections[serialIdx]; table.sections[serialIdx] = table.sections[0]; table.sections[0] = serialSection; std::cout << table; } } <|endoftext|>
<commit_before>/* This file is part of solidity. solidity 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. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2016 * Code-generating part of inline assembly. */ #include <libsolidity/inlineasm/AsmCodeGen.h> #include <libsolidity/inlineasm/AsmParser.h> #include <libsolidity/inlineasm/AsmData.h> #include <libsolidity/inlineasm/AsmScope.h> #include <libsolidity/inlineasm/AsmAnalysis.h> #include <libsolidity/inlineasm/AsmAnalysisInfo.h> #include <libevmasm/Assembly.h> #include <libevmasm/SourceLocation.h> #include <libevmasm/Instruction.h> #include <libjulia/backends/AbstractAssembly.h> #include <libdevcore/CommonIO.h> #include <boost/range/adaptor/reversed.hpp> #include <boost/range/adaptor/map.hpp> #include <boost/range/algorithm/count_if.hpp> #include <memory> #include <functional> using namespace std; using namespace dev; using namespace dev::solidity; using namespace dev::solidity::assembly; struct GeneratorState { GeneratorState(ErrorList& _errors, AsmAnalysisInfo& _analysisInfo): errors(_errors), info(_analysisInfo) {} ErrorList& errors; AsmAnalysisInfo info; }; class EthAssemblyAdapter: public julia::AbstractAssembly { public: EthAssemblyAdapter(eth::Assembly& _assembly): m_assembly(_assembly) { } virtual void setSourceLocation(SourceLocation const& _location) override { m_assembly.setSourceLocation(_location); } virtual int stackHeight() const override { return m_assembly.deposit(); } virtual void appendInstruction(solidity::Instruction _instruction) override { m_assembly.append(_instruction); } virtual void appendConstant(u256 const& _constant) override { m_assembly.append(_constant); } /// Append a label. virtual void appendLabel(size_t _labelId) override { m_assembly.append(eth::AssemblyItem(eth::Tag, _labelId)); } /// Append a label reference. virtual void appendLabelReference(size_t _labelId) override { m_assembly.append(eth::AssemblyItem(eth::PushTag, _labelId)); } virtual size_t newLabelId() override { return assemblyTagToIdentifier(m_assembly.newTag()); } virtual void appendLinkerSymbol(std::string const& _linkerSymbol) override { m_assembly.appendLibraryAddress(_linkerSymbol); } private: size_t assemblyTagToIdentifier(eth::AssemblyItem const& _tag) { u256 id = _tag.data(); solAssert(id <= std::numeric_limits<size_t>::max(), "Tag id too large."); return size_t(id); } eth::Assembly& m_assembly; }; class CodeTransform: public boost::static_visitor<> { public: /// Create the code transformer which appends assembly to _state.assembly when called /// with parsed assembly data. /// @param _identifierAccess used to resolve identifiers external to the inline assembly explicit CodeTransform( GeneratorState& _state, julia::AbstractAssembly& _assembly, assembly::Block const& _block, assembly::ExternalIdentifierAccess const& _identifierAccess = assembly::ExternalIdentifierAccess() ): CodeTransform(_state, _assembly, _block, _identifierAccess, _assembly.stackHeight()) { } private: CodeTransform( GeneratorState& _state, julia::AbstractAssembly& _assembly, assembly::Block const& _block, assembly::ExternalIdentifierAccess const& _identifierAccess, int _initialStackHeight ): m_state(_state), m_assembly(_assembly), m_scope(*m_state.info.scopes.at(&_block)), m_identifierAccess(_identifierAccess), m_initialStackHeight(_initialStackHeight) { int blockStartStackHeight = m_assembly.stackHeight(); std::for_each(_block.statements.begin(), _block.statements.end(), boost::apply_visitor(*this)); m_assembly.setSourceLocation(_block.location); // pop variables for (auto const& identifier: m_scope.identifiers) if (identifier.second.type() == typeid(Scope::Variable)) m_assembly.appendInstruction(solidity::Instruction::POP); int deposit = m_assembly.stackHeight() - blockStartStackHeight; solAssert(deposit == 0, "Invalid stack height at end of block."); } public: void operator()(assembly::Instruction const& _instruction) { m_assembly.setSourceLocation(_instruction.location); m_assembly.appendInstruction(_instruction.instruction); checkStackHeight(&_instruction); } void operator()(assembly::Literal const& _literal) { m_assembly.setSourceLocation(_literal.location); if (_literal.kind == assembly::LiteralKind::Number) m_assembly.appendConstant(u256(_literal.value)); else if (_literal.kind == assembly::LiteralKind::Boolean) { if (_literal.value == "true") m_assembly.appendConstant(u256(1)); else m_assembly.appendConstant(u256(0)); } else { solAssert(_literal.value.size() <= 32, ""); m_assembly.appendConstant(u256(h256(_literal.value, h256::FromBinary, h256::AlignLeft))); } checkStackHeight(&_literal); } void operator()(assembly::Identifier const& _identifier) { m_assembly.setSourceLocation(_identifier.location); // First search internals, then externals. if (m_scope.lookup(_identifier.name, Scope::NonconstVisitor( [=](Scope::Variable& _var) { if (int heightDiff = variableHeightDiff(_var, _identifier.location, false)) m_assembly.appendInstruction(solidity::dupInstruction(heightDiff)); else // Store something to balance the stack m_assembly.appendConstant(u256(0)); }, [=](Scope::Label& _label) { assignLabelIdIfUnset(_label); m_assembly.appendLabelReference(*_label.id); }, [=](Scope::Function&) { solAssert(false, "Function not removed during desugaring."); } ))) { return; } solAssert( m_identifierAccess.generateCode, "Identifier not found and no external access available." ); m_identifierAccess.generateCode(_identifier, IdentifierContext::RValue, m_assembly); checkStackHeight(&_identifier); } void operator()(FunctionalInstruction const& _instr) { for (auto it = _instr.arguments.rbegin(); it != _instr.arguments.rend(); ++it) { int height = m_assembly.stackHeight(); boost::apply_visitor(*this, *it); expectDeposit(1, height); } (*this)(_instr.instruction); checkStackHeight(&_instr); } void operator()(assembly::FunctionCall const&) { solAssert(false, "Function call not removed during desugaring phase."); } void operator()(Label const& _label) { m_assembly.setSourceLocation(_label.location); solAssert(m_scope.identifiers.count(_label.name), ""); Scope::Label& label = boost::get<Scope::Label>(m_scope.identifiers.at(_label.name)); assignLabelIdIfUnset(label); m_assembly.appendLabel(*label.id); checkStackHeight(&_label); } void operator()(assembly::Assignment const& _assignment) { m_assembly.setSourceLocation(_assignment.location); generateAssignment(_assignment.variableName, _assignment.location); checkStackHeight(&_assignment); } void operator()(FunctionalAssignment const& _assignment) { int height = m_assembly.stackHeight(); boost::apply_visitor(*this, *_assignment.value); expectDeposit(1, height); m_assembly.setSourceLocation(_assignment.location); generateAssignment(_assignment.variableName, _assignment.location); checkStackHeight(&_assignment); } void operator()(assembly::VariableDeclaration const& _varDecl) { int height = m_assembly.stackHeight(); boost::apply_visitor(*this, *_varDecl.value); expectDeposit(1, height); auto& var = boost::get<Scope::Variable>(m_scope.identifiers.at(_varDecl.variable.name)); var.stackHeight = height; var.active = true; } void operator()(assembly::Block const& _block) { CodeTransform(m_state, m_assembly, _block, m_identifierAccess, m_initialStackHeight); checkStackHeight(&_block); } void operator()(assembly::FunctionDefinition const&) { solAssert(false, "Function definition not removed during desugaring phase."); } private: void generateAssignment(assembly::Identifier const& _variableName, SourceLocation const& _location) { auto var = m_scope.lookup(_variableName.name); if (var) { Scope::Variable const& _var = boost::get<Scope::Variable>(*var); if (int heightDiff = variableHeightDiff(_var, _location, true)) m_assembly.appendInstruction(solidity::swapInstruction(heightDiff - 1)); m_assembly.appendInstruction(solidity::Instruction::POP); } else { solAssert( m_identifierAccess.generateCode, "Identifier not found and no external access available." ); m_identifierAccess.generateCode(_variableName, IdentifierContext::LValue, m_assembly); } } /// Determines the stack height difference to the given variables. Automatically generates /// errors if it is not yet in scope or the height difference is too large. Returns 0 on /// errors and the (positive) stack height difference otherwise. int variableHeightDiff(Scope::Variable const& _var, SourceLocation const& _location, bool _forSwap) { int heightDiff = m_assembly.stackHeight() - _var.stackHeight; if (heightDiff <= (_forSwap ? 1 : 0) || heightDiff > (_forSwap ? 17 : 16)) { //@TODO move this to analysis phase. m_state.errors.push_back(make_shared<Error>( Error::Type::TypeError, "Variable inaccessible, too deep inside stack (" + boost::lexical_cast<string>(heightDiff) + ")", _location )); return 0; } else return heightDiff; } void expectDeposit(int _deposit, int _oldHeight) { solAssert(m_assembly.stackHeight() == _oldHeight + _deposit, "Invalid stack deposit."); } void checkStackHeight(void const* _astElement) { solAssert(m_state.info.stackHeightInfo.count(_astElement), "Stack height for AST element not found."); solAssert( m_state.info.stackHeightInfo.at(_astElement) == m_assembly.stackHeight() - m_initialStackHeight, "Stack height mismatch between analysis and code generation phase." ); } /// Assigns the label's id to a value taken from eth::Assembly if it has not yet been set. void assignLabelIdIfUnset(Scope::Label& _label) { if (!_label.id) _label.id.reset(m_assembly.newLabelId()); } GeneratorState& m_state; julia::AbstractAssembly& m_assembly; Scope& m_scope; ExternalIdentifierAccess m_identifierAccess; int const m_initialStackHeight; }; eth::Assembly assembly::CodeGenerator::assemble( Block const& _parsedData, AsmAnalysisInfo& _analysisInfo, ExternalIdentifierAccess const& _identifierAccess ) { eth::Assembly assembly; GeneratorState state(m_errors, _analysisInfo); EthAssemblyAdapter assemblyAdapter(assembly); CodeTransform(state, assemblyAdapter, _parsedData, _identifierAccess); return assembly; } void assembly::CodeGenerator::assemble( Block const& _parsedData, AsmAnalysisInfo& _analysisInfo, eth::Assembly& _assembly, ExternalIdentifierAccess const& _identifierAccess ) { GeneratorState state(m_errors, _analysisInfo); EthAssemblyAdapter assemblyAdapter(_assembly); CodeTransform(state, assemblyAdapter, _parsedData, _identifierAccess); } <commit_msg>Add const<commit_after>/* This file is part of solidity. solidity 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. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2016 * Code-generating part of inline assembly. */ #include <libsolidity/inlineasm/AsmCodeGen.h> #include <libsolidity/inlineasm/AsmParser.h> #include <libsolidity/inlineasm/AsmData.h> #include <libsolidity/inlineasm/AsmScope.h> #include <libsolidity/inlineasm/AsmAnalysis.h> #include <libsolidity/inlineasm/AsmAnalysisInfo.h> #include <libevmasm/Assembly.h> #include <libevmasm/SourceLocation.h> #include <libevmasm/Instruction.h> #include <libjulia/backends/AbstractAssembly.h> #include <libdevcore/CommonIO.h> #include <boost/range/adaptor/reversed.hpp> #include <boost/range/adaptor/map.hpp> #include <boost/range/algorithm/count_if.hpp> #include <memory> #include <functional> using namespace std; using namespace dev; using namespace dev::solidity; using namespace dev::solidity::assembly; struct GeneratorState { GeneratorState(ErrorList& _errors, AsmAnalysisInfo& _analysisInfo): errors(_errors), info(_analysisInfo) {} ErrorList& errors; AsmAnalysisInfo info; }; class EthAssemblyAdapter: public julia::AbstractAssembly { public: EthAssemblyAdapter(eth::Assembly& _assembly): m_assembly(_assembly) { } virtual void setSourceLocation(SourceLocation const& _location) override { m_assembly.setSourceLocation(_location); } virtual int stackHeight() const override { return m_assembly.deposit(); } virtual void appendInstruction(solidity::Instruction _instruction) override { m_assembly.append(_instruction); } virtual void appendConstant(u256 const& _constant) override { m_assembly.append(_constant); } /// Append a label. virtual void appendLabel(size_t _labelId) override { m_assembly.append(eth::AssemblyItem(eth::Tag, _labelId)); } /// Append a label reference. virtual void appendLabelReference(size_t _labelId) override { m_assembly.append(eth::AssemblyItem(eth::PushTag, _labelId)); } virtual size_t newLabelId() override { return assemblyTagToIdentifier(m_assembly.newTag()); } virtual void appendLinkerSymbol(std::string const& _linkerSymbol) override { m_assembly.appendLibraryAddress(_linkerSymbol); } private: size_t assemblyTagToIdentifier(eth::AssemblyItem const& _tag) const { u256 id = _tag.data(); solAssert(id <= std::numeric_limits<size_t>::max(), "Tag id too large."); return size_t(id); } eth::Assembly& m_assembly; }; class CodeTransform: public boost::static_visitor<> { public: /// Create the code transformer which appends assembly to _state.assembly when called /// with parsed assembly data. /// @param _identifierAccess used to resolve identifiers external to the inline assembly explicit CodeTransform( GeneratorState& _state, julia::AbstractAssembly& _assembly, assembly::Block const& _block, assembly::ExternalIdentifierAccess const& _identifierAccess = assembly::ExternalIdentifierAccess() ): CodeTransform(_state, _assembly, _block, _identifierAccess, _assembly.stackHeight()) { } private: CodeTransform( GeneratorState& _state, julia::AbstractAssembly& _assembly, assembly::Block const& _block, assembly::ExternalIdentifierAccess const& _identifierAccess, int _initialStackHeight ): m_state(_state), m_assembly(_assembly), m_scope(*m_state.info.scopes.at(&_block)), m_identifierAccess(_identifierAccess), m_initialStackHeight(_initialStackHeight) { int blockStartStackHeight = m_assembly.stackHeight(); std::for_each(_block.statements.begin(), _block.statements.end(), boost::apply_visitor(*this)); m_assembly.setSourceLocation(_block.location); // pop variables for (auto const& identifier: m_scope.identifiers) if (identifier.second.type() == typeid(Scope::Variable)) m_assembly.appendInstruction(solidity::Instruction::POP); int deposit = m_assembly.stackHeight() - blockStartStackHeight; solAssert(deposit == 0, "Invalid stack height at end of block."); } public: void operator()(assembly::Instruction const& _instruction) { m_assembly.setSourceLocation(_instruction.location); m_assembly.appendInstruction(_instruction.instruction); checkStackHeight(&_instruction); } void operator()(assembly::Literal const& _literal) { m_assembly.setSourceLocation(_literal.location); if (_literal.kind == assembly::LiteralKind::Number) m_assembly.appendConstant(u256(_literal.value)); else if (_literal.kind == assembly::LiteralKind::Boolean) { if (_literal.value == "true") m_assembly.appendConstant(u256(1)); else m_assembly.appendConstant(u256(0)); } else { solAssert(_literal.value.size() <= 32, ""); m_assembly.appendConstant(u256(h256(_literal.value, h256::FromBinary, h256::AlignLeft))); } checkStackHeight(&_literal); } void operator()(assembly::Identifier const& _identifier) { m_assembly.setSourceLocation(_identifier.location); // First search internals, then externals. if (m_scope.lookup(_identifier.name, Scope::NonconstVisitor( [=](Scope::Variable& _var) { if (int heightDiff = variableHeightDiff(_var, _identifier.location, false)) m_assembly.appendInstruction(solidity::dupInstruction(heightDiff)); else // Store something to balance the stack m_assembly.appendConstant(u256(0)); }, [=](Scope::Label& _label) { assignLabelIdIfUnset(_label); m_assembly.appendLabelReference(*_label.id); }, [=](Scope::Function&) { solAssert(false, "Function not removed during desugaring."); } ))) { return; } solAssert( m_identifierAccess.generateCode, "Identifier not found and no external access available." ); m_identifierAccess.generateCode(_identifier, IdentifierContext::RValue, m_assembly); checkStackHeight(&_identifier); } void operator()(FunctionalInstruction const& _instr) { for (auto it = _instr.arguments.rbegin(); it != _instr.arguments.rend(); ++it) { int height = m_assembly.stackHeight(); boost::apply_visitor(*this, *it); expectDeposit(1, height); } (*this)(_instr.instruction); checkStackHeight(&_instr); } void operator()(assembly::FunctionCall const&) { solAssert(false, "Function call not removed during desugaring phase."); } void operator()(Label const& _label) { m_assembly.setSourceLocation(_label.location); solAssert(m_scope.identifiers.count(_label.name), ""); Scope::Label& label = boost::get<Scope::Label>(m_scope.identifiers.at(_label.name)); assignLabelIdIfUnset(label); m_assembly.appendLabel(*label.id); checkStackHeight(&_label); } void operator()(assembly::Assignment const& _assignment) { m_assembly.setSourceLocation(_assignment.location); generateAssignment(_assignment.variableName, _assignment.location); checkStackHeight(&_assignment); } void operator()(FunctionalAssignment const& _assignment) { int height = m_assembly.stackHeight(); boost::apply_visitor(*this, *_assignment.value); expectDeposit(1, height); m_assembly.setSourceLocation(_assignment.location); generateAssignment(_assignment.variableName, _assignment.location); checkStackHeight(&_assignment); } void operator()(assembly::VariableDeclaration const& _varDecl) { int height = m_assembly.stackHeight(); boost::apply_visitor(*this, *_varDecl.value); expectDeposit(1, height); auto& var = boost::get<Scope::Variable>(m_scope.identifiers.at(_varDecl.variable.name)); var.stackHeight = height; var.active = true; } void operator()(assembly::Block const& _block) { CodeTransform(m_state, m_assembly, _block, m_identifierAccess, m_initialStackHeight); checkStackHeight(&_block); } void operator()(assembly::FunctionDefinition const&) { solAssert(false, "Function definition not removed during desugaring phase."); } private: void generateAssignment(assembly::Identifier const& _variableName, SourceLocation const& _location) { auto var = m_scope.lookup(_variableName.name); if (var) { Scope::Variable const& _var = boost::get<Scope::Variable>(*var); if (int heightDiff = variableHeightDiff(_var, _location, true)) m_assembly.appendInstruction(solidity::swapInstruction(heightDiff - 1)); m_assembly.appendInstruction(solidity::Instruction::POP); } else { solAssert( m_identifierAccess.generateCode, "Identifier not found and no external access available." ); m_identifierAccess.generateCode(_variableName, IdentifierContext::LValue, m_assembly); } } /// Determines the stack height difference to the given variables. Automatically generates /// errors if it is not yet in scope or the height difference is too large. Returns 0 on /// errors and the (positive) stack height difference otherwise. int variableHeightDiff(Scope::Variable const& _var, SourceLocation const& _location, bool _forSwap) { int heightDiff = m_assembly.stackHeight() - _var.stackHeight; if (heightDiff <= (_forSwap ? 1 : 0) || heightDiff > (_forSwap ? 17 : 16)) { //@TODO move this to analysis phase. m_state.errors.push_back(make_shared<Error>( Error::Type::TypeError, "Variable inaccessible, too deep inside stack (" + boost::lexical_cast<string>(heightDiff) + ")", _location )); return 0; } else return heightDiff; } void expectDeposit(int _deposit, int _oldHeight) { solAssert(m_assembly.stackHeight() == _oldHeight + _deposit, "Invalid stack deposit."); } void checkStackHeight(void const* _astElement) { solAssert(m_state.info.stackHeightInfo.count(_astElement), "Stack height for AST element not found."); solAssert( m_state.info.stackHeightInfo.at(_astElement) == m_assembly.stackHeight() - m_initialStackHeight, "Stack height mismatch between analysis and code generation phase." ); } /// Assigns the label's id to a value taken from eth::Assembly if it has not yet been set. void assignLabelIdIfUnset(Scope::Label& _label) { if (!_label.id) _label.id.reset(m_assembly.newLabelId()); } GeneratorState& m_state; julia::AbstractAssembly& m_assembly; Scope& m_scope; ExternalIdentifierAccess m_identifierAccess; int const m_initialStackHeight; }; eth::Assembly assembly::CodeGenerator::assemble( Block const& _parsedData, AsmAnalysisInfo& _analysisInfo, ExternalIdentifierAccess const& _identifierAccess ) { eth::Assembly assembly; GeneratorState state(m_errors, _analysisInfo); EthAssemblyAdapter assemblyAdapter(assembly); CodeTransform(state, assemblyAdapter, _parsedData, _identifierAccess); return assembly; } void assembly::CodeGenerator::assemble( Block const& _parsedData, AsmAnalysisInfo& _analysisInfo, eth::Assembly& _assembly, ExternalIdentifierAccess const& _identifierAccess ) { GeneratorState state(m_errors, _analysisInfo); EthAssemblyAdapter assemblyAdapter(_assembly); CodeTransform(state, assemblyAdapter, _parsedData, _identifierAccess); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, 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. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ //TESTED_COMPONENT=src/multimedia #include <QtTest/QtTest> #include <QDebug> #include <QTimer> #include <qabstractmediaobject.h> #include <qabstractmediacontrol.h> #include <qradioservice.h> #include <qradioplayercontrol.h> #include <qradioplayer.h> QT_USE_NAMESPACE class MockProvider : public QRadioPlayerControl { Q_OBJECT public: MockProvider(QObject *parent): QRadioPlayerControl(parent), m_searching(false),m_muted(false),m_stereo(true), m_volume(100),m_signal(0),m_frequency(0), m_duration(0),m_band(QRadioPlayer::FM) {} QRadioPlayer::Band band() const { return m_band; } void setBand(QRadioPlayer::Band b) { m_band = b; emit bandChanged(m_band); } bool isSupportedBand(QRadioPlayer::Band b) const { if(b == QRadioPlayer::FM || b == QRadioPlayer::AM) return true; return false; } int frequency() const { return m_frequency; } void setFrequency(int frequency) { m_frequency = frequency; emit frequencyChanged(m_frequency); //NOTE: for testing emit duration change on freq set // this would normally be done on a time interval from the backend. m_duration+=1000; // add 1 sec emit durationChanged(m_duration); } bool isStereo() const { return m_stereo; } void setStereo(bool stereo) { m_stereo = stereo; emit stereoStatusChanged(m_stereo); } int signalStrength() const { return m_signal; } qint64 duration() const { return m_duration; } int volume() const { return m_volume; } void setVolume(int volume) { m_volume = volume; emit volumeChanged(m_volume); } bool isMuted() const { return m_muted; } void setMuted(bool muted) { m_muted = muted; emit mutedChanged(m_muted); } bool isSearching() const { return m_searching; } void searchForward() { m_searching = true; emit searchingChanged(m_searching); } void searchBackward() { m_searching = true; emit searchingChanged(m_searching); } void cancelSearch() { m_searching = false; emit searchingChanged(m_searching); } public: bool m_searching; bool m_muted; bool m_stereo; int m_volume; int m_signal; int m_frequency; qint64 m_duration; QRadioPlayer::Band m_band; }; class MockService : public QRadioService { Q_OBJECT public: MockService(QObject *parent, QAbstractMediaControl *control): QRadioService(parent), mockControl(control) {} QAbstractMediaControl* control(const char *) const { return mockControl; } QAbstractMediaControl *mockControl; }; class MockObject : public QAbstractMediaObject { Q_OBJECT public: MockObject(QObject *parent, QAbstractMediaControl *control): QAbstractMediaObject(parent), mockService(new MockService(this, control)) { } bool isValid() const { return true; } QRadioService* service() const { return mockService; } QRadioService *mockService; }; class tst_QRadioPlayer: public QObject { Q_OBJECT public slots: void init(); void cleanup(); private slots: void testBand(); void testFrequency(); void testStereo(); void testMute(); void testSearch(); void testVolume(); void testSignal(); void testDuration(); private: MockObject *object; MockProvider *mock; QRadioPlayer *radio; }; void tst_QRadioPlayer::init() { mock = new MockProvider(this); object = new MockObject(this, mock); radio = new QRadioPlayer(0,object->service()); QVERIFY(radio->service() != 0); QVERIFY(radio->isValid()); } void tst_QRadioPlayer::cleanup() { delete radio; } void tst_QRadioPlayer::testBand() { QVERIFY(radio->isSupportedBand(QRadioPlayer::FM)); QVERIFY(!radio->isSupportedBand(QRadioPlayer::SW)); if(radio->isSupportedBand(QRadioPlayer::AM)) { QSignalSpy readSignal(radio, SIGNAL(bandChanged(QRadioPlayer::Band))); radio->setBand(QRadioPlayer::AM); QTestEventLoop::instance().enterLoop(1); QVERIFY(radio->band() == QRadioPlayer::AM); QVERIFY(readSignal.count() == 1); } } void tst_QRadioPlayer::testFrequency() { QSignalSpy readSignal(radio, SIGNAL(frequencyChanged(int))); radio->setFrequency(104500000); QTestEventLoop::instance().enterLoop(1); QVERIFY(radio->frequency() == 104500000); QVERIFY(readSignal.count() == 1); } void tst_QRadioPlayer::testStereo() { QSignalSpy readSignal(radio, SIGNAL(stereoStatusChanged(bool))); radio->setStereo(false); QTestEventLoop::instance().enterLoop(1); QVERIFY(!radio->isStereo()); QVERIFY(readSignal.count() == 1); } void tst_QRadioPlayer::testMute() { QSignalSpy readSignal(radio, SIGNAL(mutedChanged(bool))); radio->setMuted(true); QTestEventLoop::instance().enterLoop(1); QVERIFY(radio->isMuted()); QVERIFY(readSignal.count() == 1); } void tst_QRadioPlayer::testSearch() { QSignalSpy readSignal(radio, SIGNAL(searchingChanged(bool))); QVERIFY(!radio->isSearching()); radio->searchForward(); QTestEventLoop::instance().enterLoop(1); QVERIFY(radio->isSearching()); QVERIFY(readSignal.count() == 1); radio->cancelSearch(); QTestEventLoop::instance().enterLoop(1); QVERIFY(!radio->isSearching()); QVERIFY(readSignal.count() == 2); radio->searchBackward(); QTestEventLoop::instance().enterLoop(1); QVERIFY(radio->isSearching()); QVERIFY(readSignal.count() == 3); radio->cancelSearch(); QVERIFY(!radio->isSearching()); } void tst_QRadioPlayer::testVolume() { QVERIFY(radio->volume() == 100); QSignalSpy readSignal(radio, SIGNAL(volumeChanged(int))); radio->setVolume(50); QTestEventLoop::instance().enterLoop(1); QVERIFY(radio->volume() == 50); QVERIFY(readSignal.count() == 1); } void tst_QRadioPlayer::testSignal() { QVERIFY(radio->signalStrength() == 0); // There is no set of this only a get, do nothing else. } void tst_QRadioPlayer::testDuration() { QVERIFY(radio->duration() == 0); QSignalSpy readSignal(radio, SIGNAL(durationChanged(qint64))); radio->setFrequency(104500000); QTestEventLoop::instance().enterLoop(2); QVERIFY(readSignal.count() > 0); QVERIFY(radio->duration() > 0); } QTEST_MAIN(tst_QRadioPlayer) #include "tst_qradioplayer.moc" <commit_msg>Remove broken qradioplayer test<commit_after><|endoftext|>
<commit_before>#pragma once #include <ventura/write_file.hpp> #include <ventura/read_file.hpp> #include <ventura/open.hpp> #include <boost/range/algorithm/equal.hpp> namespace warpcoil { inline bool update_generated_file(char const *file, Si::memory_range new_content, std::ostream &log) { Si::os_string const file_name = Si::to_os_string(file); return Si::visit<bool>( ventura::read_file(ventura::safe_c_str(file_name)), [&](std::vector<char> old_content) -> bool { if (boost::range::equal(old_content, new_content)) { log << "Generated file does not change\n"; return true; } boost::system::error_code const error = ventura::write_file( ventura::safe_c_str(file_name), new_content); if (!!error) { log << "Could not open " << file_name << "\n" << error << '\n'; return false; } return true; }, [&](boost::system::error_code error) { log << "Could not read " << file_name << "\n" << error << '\n'; error = ventura::write_file(ventura::safe_c_str(file_name), new_content); if (!!error) { log << "Could not open " << file_name << "\n" << error << '\n'; return false; } return true; }, [&](ventura::read_file_problem const problem) { switch (problem) { case ventura::read_file_problem::concurrent_write_detected: log << "Someone seems to have access " << file_name << " concurrently.\n"; return false; case ventura::read_file_problem::file_too_large_for_memory: log << "Could not be loaded into memory: " << file_name << "\n"; return false; } SILICIUM_UNREACHABLE(); }); } } <commit_msg>fix Win32 build<commit_after>#pragma once #include <ventura/write_file.hpp> #include <ventura/read_file.hpp> #include <ventura/open.hpp> #include <boost/range/algorithm/equal.hpp> namespace warpcoil { inline bool update_generated_file(char const *file, Si::memory_range new_content, std::ostream &log) { Si::os_string const file_name = Si::to_os_string(file); return Si::visit<bool>( ventura::read_file(ventura::safe_c_str(file_name)), [&](std::vector<char> old_content) -> bool { if (boost::range::equal(old_content, new_content)) { log << "Generated file does not change\n"; return true; } boost::system::error_code const error = ventura::write_file( ventura::safe_c_str(file_name), new_content); if (!!error) { log << "Could not open " << file << "\n" << error << '\n'; return false; } return true; }, [&](boost::system::error_code error) { log << "Could not read " << file << "\n" << error << '\n'; error = ventura::write_file(ventura::safe_c_str(file_name), new_content); if (!!error) { log << "Could not open " << file << "\n" << error << '\n'; return false; } return true; }, [&](ventura::read_file_problem const problem) { switch (problem) { case ventura::read_file_problem::concurrent_write_detected: log << "Someone seems to have access " << file << " concurrently.\n"; return false; case ventura::read_file_problem::file_too_large_for_memory: log << "Could not be loaded into memory: " << file << "\n"; return false; } SILICIUM_UNREACHABLE(); }); } } <|endoftext|>
<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <hspp/Cards/Character.h> #include <hspp/Commons/Macros.h> namespace Hearthstonepp { Character::Character(Card& card) : Entity(card) { if (card.health > 0) { #ifndef HEARTHSTONEPP_MACOSX attack = card.attack.has_value() ? card.attack.value() : 0; health = card.health.has_value() ? card.health.value() : 0; #else attack = (card.attack != std::experimental::nullopt) ? card.attack : 0; health = card.health != std::experimental::nullopt) ? card.health : 0; #endif maxHealth = health; } } Character::Character(const Character& c) : Entity(c) { attack = c.attack; attackableCount = c.attackableCount; health = c.health; maxHealth = c.maxHealth; } Character& Character::operator=(const Character& c) { if (this == &c) { return *this; } attack = c.attack; attackableCount = c.attackableCount; health = c.health; maxHealth = c.maxHealth; return *this; } Character* Character::Clone() const { return new Character(*this); } } // namespace Hearthstonepp<commit_msg>fix: Compile error on macOS (optional)<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <hspp/Cards/Character.h> #include <hspp/Commons/Macros.h> namespace Hearthstonepp { Character::Character(Card& card) : Entity(card) { if (!card.id.empty()) { #ifndef HEARTHSTONEPP_MACOSX attack = card.attack.has_value() ? card.attack.value() : 0; health = card.health.has_value() ? card.health.value() : 0; #else attack = (card.attack != std::experimental::nullopt) ? card.attack : 0; health = card.health != std::experimental::nullopt) ? card.health : 0; #endif maxHealth = health; } } Character::Character(const Character& c) : Entity(c) { attack = c.attack; attackableCount = c.attackableCount; health = c.health; maxHealth = c.maxHealth; } Character& Character::operator=(const Character& c) { if (this == &c) { return *this; } attack = c.attack; attackableCount = c.attackableCount; health = c.health; maxHealth = c.maxHealth; return *this; } Character* Character::Clone() const { return new Character(*this); } } // namespace Hearthstonepp<|endoftext|>
<commit_before>#include <climits> #include <cstdint> #include <cstdlib> #include <iostream> #include <string> #include <vector> #include "snarkfront.hpp" using namespace snarkfront; using namespace std; void printUsage(const char* exeName) { const string AES = " -b 128|192|256", KEY = " -k key_in_hex", MODE = " -e|-d", ENC = " -e", DEC = " -d", INPUT = " -i hex_text", PAIR = " -p BN128|Edwards"; cout << "encrypt: " << exeName << PAIR << AES << KEY << ENC << INPUT << endl << "decrypt: " << exeName << PAIR << AES << KEY << DEC << INPUT << endl; exit(EXIT_FAILURE); } template <typename FR> bool runTest(const bool encMode, const vector<uint8_t>& keyOctets, const vector<uint8_t>& inOctets) { typename zk::AES<FR>::BlockType zkOut; typename eval::AES::BlockType evalOut; const auto keySize = keyOctets.size() * CHAR_BIT; if (128 == keySize) { // AES-128 zkOut = cipher(zk::AES128<FR>(), !encMode, inOctets, keyOctets); evalOut = cipher(eval::AES128(), !encMode, inOctets, keyOctets); } else if (192 == keySize) { // AES-192 zkOut = cipher(zk::AES192<FR>(), !encMode, inOctets, keyOctets); evalOut = cipher(eval::AES192(), !encMode, inOctets, keyOctets); } else if (256 == keySize) { // AES-256 zkOut = cipher(zk::AES256<FR>(), !encMode, inOctets, keyOctets); evalOut = cipher(eval::AES256(), !encMode, inOctets, keyOctets); } assert_true(zkOut == evalOut); DataBuffer<PrintHex> hexpr(cout, false); bool ok = true; // compare output blocks for (size_t i = 0; i < zkOut.size(); ++i) { if (zkOut[i]->value() != evalOut[i]) { ok = false; cout << "output[" << i << "] error zk: "; hexpr.push(zkOut[i]->value()); cout << " eval: "; hexpr.push(evalOut[i]); cout << endl; } } if (ok) cout << "output: " << asciiHex(evalOut) << endl; return ok; } template <typename PAIRING> bool runTest(const vector<uint8_t>& keyOctets, const bool encMode, const vector<uint8_t>& inOctets) { reset<PAIRING>(); typedef typename PAIRING::Fr FR; const bool valueOK = runTest<FR>(encMode, keyOctets, inOctets); cout << "variable count " << variable_count<PAIRING>() << endl; GenericProgressBar progress1(cerr), progress2(cerr, 50); cerr << "generate key pair"; const auto key = keypair<PAIRING>(progress2); cerr << endl; const auto in = input<PAIRING>(); cerr << "generate proof"; const auto p = proof(key, progress2); cerr << endl; cerr << "verify proof "; const bool proofOK = verify(key, in, p, progress1); cerr << endl; return valueOK && proofOK; } int main(int argc, char *argv[]) { Getopt cmdLine(argc, argv, "pki", "b", "ed"); if (!cmdLine || cmdLine.empty()) printUsage(argv[0]); const auto pairing = cmdLine.getString('p'), keyText = cmdLine.getString('k'), inText = cmdLine.getString('i'); const auto aesBits = cmdLine.getNumber('b'); const auto encMode = cmdLine.getFlag('e'), decMode = cmdLine.getFlag('d'); if (!validPairingName(pairing) || !validAESName(aesBits) || !(encMode ^ decMode)) printUsage(argv[0]); vector<uint8_t> keyOctets; if (!asciiHexToVector(keyText, keyOctets)) { cerr << "error: malformed key" << endl; exit(EXIT_FAILURE); } const auto keySize = keyOctets.size() * CHAR_BIT; if (aesBits != keySize) { cerr << "error: key size is " << keySize << " bits" << endl; exit(EXIT_FAILURE); } vector<uint8_t> inOctets; if (!asciiHexToVector(inText, inOctets)) { cerr << "error: malformed input" << endl; exit(EXIT_FAILURE); } const auto inSize = inOctets.size() * CHAR_BIT; if (128 != inSize) { cerr << "error: input size is " << inSize << " bits" << endl; exit(EXIT_FAILURE); } bool result; if (pairingBN128(pairing)) { // Barreto-Naehrig 128 bits init_BN128(); result = runTest<BN128_PAIRING>(keyOctets, encMode, inOctets); } else if (pairingEdwards(pairing)) { // Edwards 80 bits init_Edwards(); result = runTest<EDWARDS_PAIRING>(keyOctets, encMode, inOctets); } cout << "test " << (result ? "passed" : "failed") << endl; return EXIT_SUCCESS; } <commit_msg>AES in cryptl<commit_after>#include <climits> #include <cstdint> #include <cstdlib> #include <iostream> #include <string> #include <vector> #include "snarkfront.hpp" using namespace snarkfront; using namespace cryptl; using namespace std; void printUsage(const char* exeName) { const string AES = " -b 128|192|256", KEY = " -k key_in_hex", ENC = " -e", DEC = " -d", INPUT = " -i hex_text", PAIR = " -p BN128|Edwards"; cout << "encrypt: " << exeName << PAIR << AES << KEY << ENC << INPUT << endl << "decrypt: " << exeName << PAIR << AES << KEY << DEC << INPUT << endl; exit(EXIT_FAILURE); } template <typename A, typename B> bool runTest(A dummyA, B dummyB, const vector<uint8_t>& key, const vector<uint8_t>& in) { // A typename A::KeyType keyA; for (size_t i = 0; i < keyA.size(); ++i) keyA[i] = key[i]; const auto& inA = in; const auto outA = ECB(dummyA, keyA, inA); // B typename B::KeyType keyB; for (size_t i = 0; i < keyB.size(); ++i) bless(keyB[i], key[i]); vector<typename B::VarType> inB(in.size()); bless(inB, in); const auto outB = ECB(dummyB, keyB, inB); typename A::BlockType blockA; typename B::BlockType blockB; for (size_t i = 0; i < outA.size() / blockA.size(); ++i) { const size_t offset = i * blockA.size(); for (size_t j = 0; j < blockA.size(); ++j) { blockA[j] = outA[j + offset]; blockB[j] = outB[j + offset]; } assert_true(blockA == blockB); } DataPusher<PrintHex<false>> hexpr(cout); bool ok = true; // compare output blocks for (size_t i = 0; i < outB.size(); ++i) { if (outB[i]->value() != outA[i]) { ok = false; cout << "output[" << i << "] error "; hexpr.push(outB[i]->value()); cout << " != "; hexpr.push(outA[i]); cout << endl; } } if (ok) cout << "output: " << asciiHex(outA) << endl; return ok; } template <typename FR> bool runTest(const bool encMode, const vector<uint8_t>& key, const vector<uint8_t>& in) { switch (key.size() * CHAR_BIT) { case (128) : return encMode ? runTest(cryptl::AES128(), snarkfront::AES128<FR>(), key, in) : runTest(cryptl::UNAES128(), snarkfront::UNAES128<FR>(), key, in); case (192) : return encMode ? runTest(cryptl::AES192(), snarkfront::AES192<FR>(), key, in) : runTest(cryptl::UNAES192(), snarkfront::UNAES192<FR>(), key, in); case (256) : return encMode ? runTest(cryptl::AES256(), snarkfront::AES256<FR>(), key, in) : runTest(cryptl::UNAES256(), snarkfront::UNAES256<FR>(), key, in); } return false; } template <typename PAIRING> bool runTest(const vector<uint8_t>& keyOctets, const bool encMode, const vector<uint8_t>& inOctets) { reset<PAIRING>(); const bool valueOK = runTest<typename PAIRING::Fr>(encMode, keyOctets, inOctets); cout << "variable count " << variable_count<PAIRING>() << endl; GenericProgressBar progress1(cerr), progress2(cerr, 50); cerr << "generate key pair"; const auto key = keypair<PAIRING>(progress2); cerr << endl; const auto inp = input<PAIRING>(); cerr << "generate proof"; const auto prf = proof(key, progress2); cerr << endl; cerr << "verify proof "; const bool proofOK = verify(key, inp, prf, progress1); cerr << endl; return valueOK && proofOK; } int main(int argc, char *argv[]) { Getopt cmdLine(argc, argv, "pki", "b", "ed"); if (!cmdLine || cmdLine.empty()) printUsage(argv[0]); const auto pairing = cmdLine.getString('p'), keyText = cmdLine.getString('k'), inText = cmdLine.getString('i'); const auto aesBits = cmdLine.getNumber('b'); const auto encMode = cmdLine.getFlag('e'), decMode = cmdLine.getFlag('d'); if (!validPairingName(pairing) || !validAESName(aesBits) || !(encMode ^ decMode)) printUsage(argv[0]); vector<uint8_t> key; if (!asciiHexToVector(keyText, key) || (aesBits != key.size() * CHAR_BIT)) { cerr << "error: malformed key " << keyText << endl; exit(EXIT_FAILURE); } vector<uint8_t> in; if (!asciiHexToVector(inText, in) || (128 != in.size() * CHAR_BIT)) { cerr << "error: malformed input " << inText << endl; exit(EXIT_FAILURE); } bool result; if (pairingBN128(pairing)) { // Barreto-Naehrig 128 bits init_BN128(); result = runTest<BN128_PAIRING>(key, encMode, in); } else if (pairingEdwards(pairing)) { // Edwards 80 bits init_Edwards(); result = runTest<EDWARDS_PAIRING>(key, encMode, in); } cout << "test " << (result ? "passed" : "failed") << endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "rosout_list_control.h" #include "rosout_generated.h" #include <ros/assert.h> #include <wx/imaglist.h> #include <wx/artprov.h> #include <sstream> namespace rxtools { RosoutListControl::RosoutListControl(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name) : wxListCtrl(parent, id, pos, size, style, validator, name), selection_(-1) { wxListItem item; item.SetText(wxT("Message")); item.SetWidth(600); InsertColumn(columns::Message, item); item.SetText(wxT("Severity")); item.SetWidth(100); InsertColumn(columns::Severity, item); item.SetText(wxT("Node")); item.SetWidth(200); InsertColumn(columns::Node, item); item.SetText(wxT("Time")); item.SetWidth(200); InsertColumn(columns::Time, item); item.SetText(wxT("Topics")); item.SetWidth(200); InsertColumn(columns::Topics, item); item.SetText(wxT("File")); item.SetWidth(200); InsertColumn(columns::File, item); item.SetText(wxT("Line")); item.SetWidth(200); InsertColumn(columns::Line, item); item.SetText(wxT("Function")); item.SetWidth(200); InsertColumn(columns::Function, item); wxImageList* image_list = new wxImageList(16, 16); fatal_image_id_ = image_list->Add(wxArtProvider::GetIcon(wxART_CROSS_MARK, wxART_OTHER, wxSize(16, 16))); error_image_id_ = image_list->Add(wxArtProvider::GetIcon(wxART_ERROR, wxART_OTHER, wxSize(16, 16))); warning_image_id_ = image_list->Add(wxArtProvider::GetIcon(wxART_WARNING, wxART_OTHER, wxSize(16, 16))); info_image_id_ = image_list->Add(wxArtProvider::GetIcon(wxART_INFORMATION, wxART_OTHER, wxSize(16, 16))); debug_image_id_ = image_list->Add(wxArtProvider::GetIcon(wxART_HELP, wxART_OTHER, wxSize(16, 16))); AssignImageList(image_list, wxIMAGE_LIST_SMALL); Connect(wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler(RosoutListControl::onItemActivated), NULL, this); Connect(wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler(RosoutListControl::onItemSelected), NULL, this); } RosoutListControl::~RosoutListControl() { Disconnect(wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler(RosoutListControl::onItemActivated), NULL, this); Disconnect(wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler(RosoutListControl::onItemSelected), NULL, this); } void RosoutListControl::setMessageFunction(const MessageFunc& func) { message_func_ = func; } wxString RosoutListControl::getSeverityText(const roslib::LogConstPtr& message) const { switch (message->level) { case roslib::Log::DEBUG: return wxT("Debug"); case roslib::Log::INFO: return wxT("Info"); case roslib::Log::WARN: return wxT("Warn"); case roslib::Log::ERROR: return wxT("Error"); case roslib::Log::FATAL: return wxT("Fatal"); } return wxT("Unknown"); } int RosoutListControl::OnGetItemImage(long item) const { ROS_ASSERT(message_func_ != 0); roslib::LogConstPtr message = message_func_(item); if (!message) { return -1; } switch (message->level) { case roslib::Log::DEBUG: return debug_image_id_; case roslib::Log::INFO: return info_image_id_; case roslib::Log::WARN: return warning_image_id_; case roslib::Log::ERROR: return error_image_id_; case roslib::Log::FATAL: return fatal_image_id_; } ROS_BREAK(); return -1; } wxListItemAttr * RosoutListControl::OnGetItemAttr(long item) const { #if 0 ROS_ASSERT( message_func_ != 0 ); const roslib::Log& message = message_func_( item ); switch( message->level ) { case roslib::Log::DEBUG: attr_.SetBackgroundColour( wxColour( 204, 255, 204 ) ); break; case roslib::Log::INFO: attr_.SetBackgroundColour( *wxWHITE ); break; case roslib::Log::WARN: attr_.SetBackgroundColour( wxColour( 255, 255, 153 ) ); break; case roslib::Log::ERROR: attr_.SetBackgroundColour( wxColour( 255, 153, 0 ) ); break; case roslib::Log::FATAL: attr_.SetBackgroundColour( *wxRED ); break; default: ROS_BREAK(); } #endif return &attr_; } wxString RosoutListControl::OnGetItemText(long item, long column) const { ROS_ASSERT(message_func_ != 0); roslib::LogConstPtr message = message_func_(item); if (!message) { return wxString(); } switch (column) { case columns::Severity: { return getSeverityText(message); } break; case columns::Time: { std::stringstream ss; ss << message->header.stamp; return wxString::FromAscii(ss.str().c_str()); } case columns::Message: { std::string msg = message->msg; size_t pos = std::string::npos; while (true) { pos = msg.find('\n'); if (pos == std::string::npos) { break; } msg.replace(pos, 1, "\\n"); } while (true) { pos = msg.find('\r'); if (pos == std::string::npos) { break; } msg.replace(pos, 1, "\\r"); } return wxString::FromAscii(msg.c_str()); } case columns::Topics: { std::stringstream ss; typedef std::vector<std::string> V_string; V_string::const_iterator it = message->topics.begin(); V_string::const_iterator end = message->topics.end(); for (; it != end; ++it) { if (it != message->topics.begin()) { ss << ", "; } ss << *it; } return wxString::FromAscii(ss.str().c_str()); } case columns::File: { return wxString::FromAscii(message->file.c_str()); } case columns::Line: { wxString str; str << message->line; return str; } case columns::Function: { return wxString::FromAscii(message->function.c_str()); } case columns::Node: { return wxString::FromAscii(message->name.c_str()); } } ROS_BREAK(); return wxT("Unknown Column"); } void RosoutListControl::onItemActivated(wxListEvent& event) { ROS_ASSERT(message_func_ != 0); roslib::LogConstPtr message = message_func_(event.GetIndex()); if (!message) { return; } std::stringstream ss; ss << "Node: " << message->name << std::endl; ss << "Time: " << message->header.stamp << std::endl; ss << "Severity: " << (const char*) getSeverityText(message).fn_str() << std::endl; ss << "Message:\n" << message->msg << "\n\n"; ss << "File: " << message->file << std::endl; ss << "Line: " << message->line << std::endl; ss << "Function: " << message->function << std::endl; ss << "Published topics:\n"; typedef std::vector<std::string> V_string; V_string::const_iterator it = message->topics.begin(); V_string::const_iterator end = message->topics.end(); for (; it != end; ++it) { ss << "\t" << *it << std::endl;; } TextboxDialog* dialog = new TextboxDialog(this, wxID_ANY); dialog->text_control_->SetValue(wxString::FromAscii(ss.str().c_str())); dialog->Show(); } void RosoutListControl::onItemSelected(wxListEvent& event) { selection_ = event.GetIndex(); } } // namespace rxtools <commit_msg>Remove invalid breakpoint<commit_after>/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "rosout_list_control.h" #include "rosout_generated.h" #include <ros/assert.h> #include <wx/imaglist.h> #include <wx/artprov.h> #include <sstream> namespace rxtools { RosoutListControl::RosoutListControl(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name) : wxListCtrl(parent, id, pos, size, style, validator, name), selection_(-1) { wxListItem item; item.SetText(wxT("Message")); item.SetWidth(600); InsertColumn(columns::Message, item); item.SetText(wxT("Severity")); item.SetWidth(100); InsertColumn(columns::Severity, item); item.SetText(wxT("Node")); item.SetWidth(200); InsertColumn(columns::Node, item); item.SetText(wxT("Time")); item.SetWidth(200); InsertColumn(columns::Time, item); item.SetText(wxT("Topics")); item.SetWidth(200); InsertColumn(columns::Topics, item); item.SetText(wxT("File")); item.SetWidth(200); InsertColumn(columns::File, item); item.SetText(wxT("Line")); item.SetWidth(200); InsertColumn(columns::Line, item); item.SetText(wxT("Function")); item.SetWidth(200); InsertColumn(columns::Function, item); wxImageList* image_list = new wxImageList(16, 16); fatal_image_id_ = image_list->Add(wxArtProvider::GetIcon(wxART_CROSS_MARK, wxART_OTHER, wxSize(16, 16))); error_image_id_ = image_list->Add(wxArtProvider::GetIcon(wxART_ERROR, wxART_OTHER, wxSize(16, 16))); warning_image_id_ = image_list->Add(wxArtProvider::GetIcon(wxART_WARNING, wxART_OTHER, wxSize(16, 16))); info_image_id_ = image_list->Add(wxArtProvider::GetIcon(wxART_INFORMATION, wxART_OTHER, wxSize(16, 16))); debug_image_id_ = image_list->Add(wxArtProvider::GetIcon(wxART_HELP, wxART_OTHER, wxSize(16, 16))); AssignImageList(image_list, wxIMAGE_LIST_SMALL); Connect(wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler(RosoutListControl::onItemActivated), NULL, this); Connect(wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler(RosoutListControl::onItemSelected), NULL, this); } RosoutListControl::~RosoutListControl() { Disconnect(wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler(RosoutListControl::onItemActivated), NULL, this); Disconnect(wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler(RosoutListControl::onItemSelected), NULL, this); } void RosoutListControl::setMessageFunction(const MessageFunc& func) { message_func_ = func; } wxString RosoutListControl::getSeverityText(const roslib::LogConstPtr& message) const { switch (message->level) { case roslib::Log::DEBUG: return wxT("Debug"); case roslib::Log::INFO: return wxT("Info"); case roslib::Log::WARN: return wxT("Warn"); case roslib::Log::ERROR: return wxT("Error"); case roslib::Log::FATAL: return wxT("Fatal"); } return wxT("Unknown"); } int RosoutListControl::OnGetItemImage(long item) const { ROS_ASSERT(message_func_ != 0); roslib::LogConstPtr message = message_func_(item); if (!message) { return -1; } switch (message->level) { case roslib::Log::DEBUG: return debug_image_id_; case roslib::Log::INFO: return info_image_id_; case roslib::Log::WARN: return warning_image_id_; case roslib::Log::ERROR: return error_image_id_; case roslib::Log::FATAL: return fatal_image_id_; } return -1; } wxListItemAttr * RosoutListControl::OnGetItemAttr(long item) const { #if 0 ROS_ASSERT( message_func_ != 0 ); const roslib::Log& message = message_func_( item ); switch( message->level ) { case roslib::Log::DEBUG: attr_.SetBackgroundColour( wxColour( 204, 255, 204 ) ); break; case roslib::Log::INFO: attr_.SetBackgroundColour( *wxWHITE ); break; case roslib::Log::WARN: attr_.SetBackgroundColour( wxColour( 255, 255, 153 ) ); break; case roslib::Log::ERROR: attr_.SetBackgroundColour( wxColour( 255, 153, 0 ) ); break; case roslib::Log::FATAL: attr_.SetBackgroundColour( *wxRED ); break; default: ROS_BREAK(); } #endif return &attr_; } wxString RosoutListControl::OnGetItemText(long item, long column) const { ROS_ASSERT(message_func_ != 0); roslib::LogConstPtr message = message_func_(item); if (!message) { return wxString(); } switch (column) { case columns::Severity: { return getSeverityText(message); } break; case columns::Time: { std::stringstream ss; ss << message->header.stamp; return wxString::FromAscii(ss.str().c_str()); } case columns::Message: { std::string msg = message->msg; size_t pos = std::string::npos; while (true) { pos = msg.find('\n'); if (pos == std::string::npos) { break; } msg.replace(pos, 1, "\\n"); } while (true) { pos = msg.find('\r'); if (pos == std::string::npos) { break; } msg.replace(pos, 1, "\\r"); } return wxString::FromAscii(msg.c_str()); } case columns::Topics: { std::stringstream ss; typedef std::vector<std::string> V_string; V_string::const_iterator it = message->topics.begin(); V_string::const_iterator end = message->topics.end(); for (; it != end; ++it) { if (it != message->topics.begin()) { ss << ", "; } ss << *it; } return wxString::FromAscii(ss.str().c_str()); } case columns::File: { return wxString::FromAscii(message->file.c_str()); } case columns::Line: { wxString str; str << message->line; return str; } case columns::Function: { return wxString::FromAscii(message->function.c_str()); } case columns::Node: { return wxString::FromAscii(message->name.c_str()); } } ROS_BREAK(); return wxT("Unknown Column"); } void RosoutListControl::onItemActivated(wxListEvent& event) { ROS_ASSERT(message_func_ != 0); roslib::LogConstPtr message = message_func_(event.GetIndex()); if (!message) { return; } std::stringstream ss; ss << "Node: " << message->name << std::endl; ss << "Time: " << message->header.stamp << std::endl; ss << "Severity: " << (const char*) getSeverityText(message).fn_str() << std::endl; ss << "Message:\n" << message->msg << "\n\n"; ss << "File: " << message->file << std::endl; ss << "Line: " << message->line << std::endl; ss << "Function: " << message->function << std::endl; ss << "Published topics:\n"; typedef std::vector<std::string> V_string; V_string::const_iterator it = message->topics.begin(); V_string::const_iterator end = message->topics.end(); for (; it != end; ++it) { ss << "\t" << *it << std::endl;; } TextboxDialog* dialog = new TextboxDialog(this, wxID_ANY); dialog->text_control_->SetValue(wxString::FromAscii(ss.str().c_str())); dialog->Show(); } void RosoutListControl::onItemSelected(wxListEvent& event) { selection_ = event.GetIndex(); } } // namespace rxtools <|endoftext|>
<commit_before>/*********************************************************************** filename: SVGData.cpp created: 30th July 2013 author: Lukas Meindl *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/svg/SVGData.h" #include "CEGUI/svg/SVGBasicShape.h" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// SVGData::SVGData() { } //----------------------------------------------------------------------------// SVGData::~SVGData() { destroyShapes(); } //----------------------------------------------------------------------------// void SVGData::addShape(SVGBasicShape* svg_shape) { d_svgBasicShapes.push_back(svg_shape); } //----------------------------------------------------------------------------// void SVGData::destroyShapes() { const unsigned int shape_count = d_svgBasicShapes.size(); for(unsigned int i = 0; i < shape_count; ++i) delete d_svgBasicShapes[i]; d_svgBasicShapes.clear(); } //----------------------------------------------------------------------------// const std::vector<SVGBasicShape*>& SVGData::getShapes() const { return d_svgBasicShapes; } //----------------------------------------------------------------------------// } <commit_msg>MOD: cosmetic fix<commit_after>/*********************************************************************** filename: SVGData.cpp created: 30th July 2013 author: Lukas Meindl *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/svg/SVGData.h" #include "CEGUI/svg/SVGBasicShape.h" namespace CEGUI { //----------------------------------------------------------------------------// SVGData::SVGData() { } //----------------------------------------------------------------------------// SVGData::~SVGData() { destroyShapes(); } //----------------------------------------------------------------------------// void SVGData::addShape(SVGBasicShape* svg_shape) { d_svgBasicShapes.push_back(svg_shape); } //----------------------------------------------------------------------------// void SVGData::destroyShapes() { const unsigned int shape_count = d_svgBasicShapes.size(); for (unsigned int i = 0; i < shape_count; ++i) delete d_svgBasicShapes[i]; d_svgBasicShapes.clear(); } //----------------------------------------------------------------------------// const std::vector<SVGBasicShape*>& SVGData::getShapes() const { return d_svgBasicShapes; } //----------------------------------------------------------------------------// } <|endoftext|>
<commit_before>// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard // U.S. Geological Survey // // <LicenseText> // // ---------------------------------------------------------------------- // #include <portinfo> #include <Python.h> #include "geolocalconverter.h" #include "spatialdata/geocoords/GeoLocalConverter.h" #include <stdexcept> // USES std::exception #include "journal/firewall.h" // USES FIREWALL #include "pythiautil/FireWallUtil.h" // USES FIREWALL #include "pythiautil/bindings.h" // USES BindingsTUtil // ---------------------------------------------------------------------- // CppGeoLocalConverter char pyspatialdata_geocoords_CppGeoLocalConverter__doc__[] = ""; char pyspatialdata_geocoords_CppGeoLocalConverter__name__[] = "CppGeoLocalConverter"; static char pyspatialdata_geocoords_CppGeoLocalConverter_note[] = "spatialdata geocoords python module: U.S. Geological Survey"; PyObject* pyspatialdata_geocoords_CppGeoLocalConverter(PyObject*, PyObject* args) { // CppGeoLocalConverter PyObject* pyCoordSys = 0; int ok = PyArg_ParseTuple(args, "O:CppGeoLocalConverter_localOrigin", &pyCoordSys); if (!ok) { PyErr_SetString(PyExc_TypeError, "C++ bindings error: " "Could not parse tuple for arguments."); return 0; } // if spatialdata::GeoCoordSys* pCoordSys = pythiautil::BindingsTUtil<spatialdata::GeoCoordSys*>::GetCObj(pyCoordSys, "GeoCoordSys*", "Python handle to GeoCoordSys*"); FIREWALL(0 != pCoordSys); return PyCObject_FromVoidPtr((void*) new spatialdata::GeoLocalConverter(*pCoordSys), pythiautil::BindingsTUtil<spatialdata::GeoLocalConverter>::DeleteObj); } // CppGeoLocalConverter // ---------------------------------------------------------------------- // CppGeoLocalConverter_localOrigin char pyspatialdata_geocoords_CppGeoLocalConverter_localOrigin__doc__[] = ""; char pyspatialdata_geocoords_CppGeoLocalConverter_localOrigin__name__[] = "CppGeoLocalConverter_localOrigin"; static char pyspatialdata_geocoords_CppGeoLocalConverter_localOrigin_note[] = "spatialdata geocoords python module: U.S. Geological Survey"; PyObject* pyspatialdata_geocoords_CppGeoLocalConverter_localOrigin(PyObject*, PyObject* args) { // CppGeoLocalConverter_localOrigin PyObject* pyConverter = 0; double lon = 0; double lat = 0; double elev = 0; int ok = PyArg_ParseTuple(args, "Oddd:CppGeoLocalConverter_localOrigin", &pyConverter, &lon, &lat, &elev); if (!ok) { PyErr_SetString(PyExc_TypeError, "C++ bindings error: " "Could not parse tuple for arguments."); return 0; } // if try { spatialdata::GeoLocalConverter* pConverter = pythiautil::BindingsTUtil<spatialdata::GeoLocalConverter*>::GetCObj(pyConverter, "GeoLocalConverter*", "Python handle to GeoLocalConverter*"); FIREWALL(0 != pConverter); pConverter->localOrigin(lon, lat, elev); } // try catch (const std::exception& err) { PyErr_SetString(PyExc_RuntimeError, const_cast<char*>(err.what())); return 0; } catch (...) { PyErr_SetString(PyExc_RuntimeError, "Caught unknown C++ exception."); return 0; } // catch Py_INCREF(Py_None); return Py_None; } // CppGeoLocalConverter_localOrigin // ---------------------------------------------------------------------- // CppGeoLocalConverter_convert char pyspatialdata_geocoords_CppGeoLocalConverter_convert__doc__[] = ""; char pyspatialdata_geocoords_CppGeoLocalConverter_convert__name__[] = "CppGeoLocalConverter_convert"; static char pyspatialdata_geocoords_CppGeoLocalConverter_convert_note[] = "spatialdata geocoords python module: U.S. Geological Survey"; PyObject* pyspatialdata_geocoords_CppGeoLocalConverter_convert(PyObject*, PyObject* args) { // CppGeoLocalConverter_convert PyObject* pyConverter = 0; PyObject* pyCoords = 0; int numLocs = 0; int numCoords = 0; int invertFlag = 0; int ok = PyArg_ParseTuple(args, "OOiii:CppGeoLocalConverter_convert", &pyConverter, &pyCoords, &numLocs, &numCoords, &invertFlag); if (!ok) { PyErr_SetString(PyExc_TypeError, "C++ bindings error: " "Could not parse tuple for arguments."); return 0; } // if try { spatialdata::GeoLocalConverter* pConverter = pythiautil::BindingsTUtil<spatialdata::GeoLocalConverter*>::GetCObj(pyConverter, "GeoLocalConverter*", "Python handle to GeoLocalConverter*"); FIREWALL(0 != pConverter); double* pCoords = pythiautil::BindingsTUtil<double*>::GetCObj(pyCoords, "double*", "Python handle to double*"); FIREWALL(0 != pCoords); const bool invert = invertFlag; if (3 != numCoords) { PyErr_SetString(PyExc_ValueError, "C++ bindings error: " "Number of coordinates per location must be 3."); return 0; } pConverter->convert(&pCoords, numLocs, invert); } // try catch (const std::exception& err) { PyErr_SetString(PyExc_RuntimeError, const_cast<char*>(err.what())); return 0; } catch (...) { PyErr_SetString(PyExc_RuntimeError, "Caught unknown C++ exception."); return 0; } // catch Py_INCREF(Py_None); return Py_None; } // CppGeoLocalConverter_convert // version // $Id: geolocalconverter.cc,v 1.1 2005/06/01 23:56:09 baagaard Exp $ // End of file <commit_msg>Fixed bugs related to convert args. Updated to reflect use of converting elevation to meters.<commit_after>// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard // U.S. Geological Survey // // <LicenseText> // // ---------------------------------------------------------------------- // #include <portinfo> #include <Python.h> #include "geolocalconverter.h" #include "spatialdata/geocoords/GeoLocalConverter.h" #include <stdexcept> // USES std::exception #include "journal/firewall.h" // USES FIREWALL #include "pythiautil/FireWallUtil.h" // USES FIREWALL #include "pythiautil/bindings.h" // USES BindingsTUtil // ---------------------------------------------------------------------- // CppGeoLocalConverter char pyspatialdata_geocoords_CppGeoLocalConverter__doc__[] = ""; char pyspatialdata_geocoords_CppGeoLocalConverter__name__[] = "CppGeoLocalConverter"; static char pyspatialdata_geocoords_CppGeoLocalConverter_note[] = "spatialdata geocoords python module: U.S. Geological Survey"; PyObject* pyspatialdata_geocoords_CppGeoLocalConverter(PyObject*, PyObject* args) { // CppGeoLocalConverter PyObject* pyCoordSys = 0; int ok = PyArg_ParseTuple(args, "O:CppGeoLocalConverter_localOrigin", &pyCoordSys); if (!ok) { PyErr_SetString(PyExc_TypeError, "C++ bindings error: " "Could not parse tuple for arguments."); return 0; } // if spatialdata::GeoCoordSys* pCoordSys = pythiautil::BindingsTUtil<spatialdata::GeoCoordSys*>::GetCObj(pyCoordSys, "GeoCoordSys*", "Python handle to GeoCoordSys*"); FIREWALL(0 != pCoordSys); return PyCObject_FromVoidPtr((void*) new spatialdata::GeoLocalConverter(*pCoordSys), pythiautil::BindingsTUtil<spatialdata::GeoLocalConverter>::DeleteObj); } // CppGeoLocalConverter // ---------------------------------------------------------------------- // CppGeoLocalConverter_localOrigin char pyspatialdata_geocoords_CppGeoLocalConverter_localOrigin__doc__[] = ""; char pyspatialdata_geocoords_CppGeoLocalConverter_localOrigin__name__[] = "CppGeoLocalConverter_localOrigin"; static char pyspatialdata_geocoords_CppGeoLocalConverter_localOrigin_note[] = "spatialdata geocoords python module: U.S. Geological Survey"; PyObject* pyspatialdata_geocoords_CppGeoLocalConverter_localOrigin(PyObject*, PyObject* args) { // CppGeoLocalConverter_localOrigin PyObject* pyConverter = 0; double lon = 0; double lat = 0; double elev = 0; int ok = PyArg_ParseTuple(args, "Oddd:CppGeoLocalConverter_localOrigin", &pyConverter, &lon, &lat, &elev); if (!ok) { PyErr_SetString(PyExc_TypeError, "C++ bindings error: " "Could not parse tuple for arguments."); return 0; } // if try { spatialdata::GeoLocalConverter* pConverter = pythiautil::BindingsTUtil<spatialdata::GeoLocalConverter*>::GetCObj(pyConverter, "GeoLocalConverter*", "Python handle to GeoLocalConverter*"); FIREWALL(0 != pConverter); pConverter->localOrigin(lon, lat, elev); } // try catch (const std::exception& err) { PyErr_SetString(PyExc_RuntimeError, const_cast<char*>(err.what())); return 0; } catch (...) { PyErr_SetString(PyExc_RuntimeError, "Caught unknown C++ exception."); return 0; } // catch Py_INCREF(Py_None); return Py_None; } // CppGeoLocalConverter_localOrigin // ---------------------------------------------------------------------- // CppGeoLocalConverter_convert char pyspatialdata_geocoords_CppGeoLocalConverter_convert__doc__[] = ""; char pyspatialdata_geocoords_CppGeoLocalConverter_convert__name__[] = "CppGeoLocalConverter_convert"; static char pyspatialdata_geocoords_CppGeoLocalConverter_convert_note[] = "spatialdata geocoords python module: U.S. Geological Survey"; PyObject* pyspatialdata_geocoords_CppGeoLocalConverter_convert(PyObject*, PyObject* args) { // CppGeoLocalConverter_convert PyObject* pyConverter = 0; PyObject* pyCoords = 0; int numLocs = 0; int numCoords = 0; double elevToMeters = 1.0; int invertFlag = 0; int ok = PyArg_ParseTuple(args, "OOiidi:CppGeoLocalConverter_convert", &pyConverter, &pyCoords, &numLocs, &numCoords, &elevToMeters, &invertFlag); if (!ok) { PyErr_SetString(PyExc_TypeError, "C++ bindings error: " "Could not parse tuple for arguments."); return 0; } // if try { spatialdata::GeoLocalConverter* pConverter = pythiautil::BindingsTUtil<spatialdata::GeoLocalConverter*>::GetCObj(pyConverter, "GeoLocalConverter*", "Python handle to GeoLocalConverter*"); FIREWALL(0 != pConverter); double* pCoords = pythiautil::BindingsTUtil<double*>::GetCObj(pyCoords, "double*", "Python handle to double*"); FIREWALL(0 != pCoords); const bool invert = invertFlag; if (3 != numCoords) { PyErr_SetString(PyExc_ValueError, "C++ bindings error: " "Number of coordinates per location must be 3."); return 0; } pConverter->convert(&pCoords, numLocs, elevToMeters, invert); } // try catch (const std::exception& err) { PyErr_SetString(PyExc_RuntimeError, const_cast<char*>(err.what())); return 0; } catch (...) { PyErr_SetString(PyExc_RuntimeError, "Caught unknown C++ exception."); return 0; } // catch Py_INCREF(Py_None); return Py_None; } // CppGeoLocalConverter_convert // version // $Id: geolocalconverter.cc,v 1.2 2005/06/02 21:36:16 baagaard Exp $ // End of file <|endoftext|>
<commit_before>// // LODDlg.cpp // // Copyright (c) 2005-2007 Virtual Terrain Project // Free for all uses, see license.txt for details. // // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #include "vtlib/vtlib.h" #include "vtlib/core/TiledGeom.h" #include "LODDlg.h" #include "EnviroFrame.h" #include "mini.h" #include "miniload.hpp" #include "datacloud.hpp" // WDR: class implementations //---------------------------------------------------------------------------- // LODDlg //---------------------------------------------------------------------------- // WDR: event table for LODDlg BEGIN_EVENT_TABLE(LODDlg,wxDialog) EVT_SPIN_UP( ID_TARGET, LODDlg::OnSpinTargetUp ) EVT_SPIN_DOWN( ID_TARGET, LODDlg::OnSpinTargetDown ) END_EVENT_TABLE() LODDlg::LODDlg( wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style ) : wxDialog( parent, id, title, position, size, style ) { // WDR: dialog function LODDialogFunc for LODDlg LODDialogFunc( this, TRUE ); GetTileStatus()->SetValue(_T("No paging threads")); m_iTarget = 0; } void LODDlg::Refresh(float res0, float res, float res1, int target, int count, int cache_size, int cache_used, int disk_loads, int cache_hits) { // don't bother updating if window isn't shown if (!IsShown()) return; wxString str; if (target != m_iTarget) { m_iTarget = target; str.Printf(_T("%d"), m_iTarget); GetTarget()->SetValue(str); } str.Printf(_T("%d"), count); GetCurrent()->SetValue(str); if (cache_size != m_iCacheSize || cache_used != m_iCacheUsed) { m_iCacheSize = cache_size; m_iCacheUsed = cache_used; if (m_iCacheSize == -1) str = _T("n/a"); else str.Printf(_T("%d / %d"), m_iCacheUsed/1024, m_iCacheSize/1024); GetCacheUsed()->SetValue(str); } if (disk_loads != m_iDiskLoads) { m_iDiskLoads = disk_loads; if (m_iDiskLoads == -1) str = _T("n/a"); else str.Printf(_T("%d"), m_iDiskLoads); GetTileLoads()->SetValue(str); } if (cache_hits != m_iCacheHits) { m_iCacheHits = cache_hits; if (m_iCacheHits == -1) str = _T("n/a"); else str.Printf(_T("%d"), m_iCacheHits); GetTileHits()->SetValue(str); } // Now draw the chart DrawChart(res0, res, res1, target, count); } void LODDlg::DrawChart(float res0, float res, float res1, int target, int count) { int ires = (int) res; int imax = target * 2; int itarget = target * 300 / imax; int icount = count * 300 / imax; int range = (target / 10); int irange1 = (target-range) * 300 / imax; int irange2 = (target+range) * 300 / imax; wxPanel *panel = GetPanel1(); wxClientDC dc(panel); PrepareDC(dc); dc.Clear(); if (res0 != -1) { int ires0 = (int) res0; int ires1 = (int) res1; wxPen pen1(wxColour(255,0,0), 1, wxSOLID); // red dc.SetPen(pen1); dc.DrawLine(ires0-10, 0, ires0, 10); dc.DrawLine(ires0, 10, ires0-10, 20); dc.DrawLine(ires1+10, 0, ires1, 10); dc.DrawLine(ires1, 10, ires1+10, 20); } wxPen pen2(wxColour(0,0,255), 3, wxSOLID); // blue dc.SetPen(pen2); dc.DrawLine(ires, 0, ires, 20); wxPen pen3(wxColour(0,128,0), 1, wxSOLID); // green dc.SetPen(pen3); dc.DrawLine(irange1-10, 20, irange1, 30); dc.DrawLine(irange1, 30, irange1-10, 40); dc.DrawLine(itarget, 20, itarget, 40); dc.DrawLine(irange2+10, 20, irange2, 30); dc.DrawLine(irange2, 30, irange2+10, 40); dc.DrawLine(irange1, 30, irange2, 30); wxPen pen4(wxColour(255,0,255), 3, wxSOLID); // purple dc.SetPen(pen4); dc.DrawLine(icount, 20, icount, 40); } void LODDlg::DrawTilesetState(vtTiledGeom *tg, vtCamera *cam) { wxPanel *panel = GetPanel2(); wxClientDC dc(panel); PrepareDC(dc); dc.Clear(); //wxPen pen3(wxColour(0,128,0), 1, wxSOLID); // green //dc.SetPen(pen3); wxBrush b1(wxColour(255,0,0), wxSOLID); wxBrush b2(wxColour(255,128,0), wxSOLID); wxBrush b3(wxColour(255,255,0), wxSOLID); wxBrush b4(wxColour(0,255,0), wxSOLID); wxBrush b5(wxColour(0,255,255), wxSOLID); wxBrush b6(wxColour(0,0,255), wxSOLID); wxBrush b7(wxColour(255,0,255), wxSOLID); wxBrush bwhite(wxColour(255,255,255), wxSOLID); wxPen p1(wxColour(255,0,0), 2, wxSOLID); wxPen p2(wxColour(255,128,0), 2, wxSOLID); wxPen p3(wxColour(255,255,0), 2, wxSOLID); wxPen p4(wxColour(0,255,0), 2, wxSOLID); wxPen p5(wxColour(0,255,255), 2, wxSOLID); wxPen p6(wxColour(0,0,255), 2, wxSOLID); wxPen p7(wxColour(255,0,255), 2, wxSOLID); wxPen pwhite(wxColour(255,255,255), 2, wxSOLID); wxPen pblack(wxColour(0,0,0), 1, wxSOLID); // draw rectangles for texture state minitile *mt = tg->GetMiniTile(); wxSize size = panel->GetSize(); int border = 20; int sx = (size.x - border*2) / tg->cols; int sy = (size.y - border*2) / tg->rows; for (int i = 0; i < tg->cols; i++) { for (int j = 0; j < tg->rows; j++) { int t = mt->gettexw(i,j); switch (t) { case 64: dc.SetBrush(b1); break; case 128: dc.SetBrush(b2); break; case 256: dc.SetBrush(b3); break; case 512: dc.SetBrush(b4); break; case 1024: dc.SetBrush(b5); break; case 2048: dc.SetBrush(b6); break; default: dc.SetBrush(bwhite); break; } /* int s = mt->getsize(i,j); switch (s) { case 65: dc.SetPen(p1); break; case 129: dc.SetPen(p2); break; case 257: dc.SetPen(p3); break; case 513: dc.SetPen(p4); break; case 1025: dc.SetPen(p5); break; case 2049: dc.SetPen(p6); break; default: dc.SetPen(pwhite); break; } */ dc.DrawRectangle(border + i*sx, border + j*sy, sx-1, sy-1); } } // draw camera FOV FPoint3 p = cam->GetTrans(); float fx = p.x / tg->coldim; float fy = tg->rows + (p.z / tg->coldim); int csx = border + fx * sx; int csy = border + fy * sy; dc.SetPen(pblack); dc.DrawLine(csx - 10, csy, csx + 10, csy); dc.DrawLine(csx, csy - 10, csx, csy + 10); datacloud *cloud = tg->GetDataCloud(); if (cloud) { double mem = cloud->getmem(); wxString str; str.Printf(_T("Mem %.1f MB, Total %d, Pending %d, Visible %d, Active %d, Missing %d"), mem, cloud->gettotal(), cloud->getpending(), cloud->getvisible(), cloud->getactive(), cloud->getmissing()); GetTileStatus()->SetValue(str); } } // WDR: handler implementations for LODDlg void LODDlg::OnSpinTargetUp( wxSpinEvent &event ) { m_pFrame->ChangeTerrainDetail(true); event.Veto(); } void LODDlg::OnSpinTargetDown( wxSpinEvent &event ) { m_pFrame->ChangeTerrainDetail(false); event.Veto(); } <commit_msg>tweak dbg calls<commit_after>// // LODDlg.cpp // // Copyright (c) 2005-2007 Virtual Terrain Project // Free for all uses, see license.txt for details. // // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #include "vtlib/vtlib.h" #include "vtlib/core/TiledGeom.h" #include "LODDlg.h" #include "EnviroFrame.h" #include "mini.h" #include "miniload.hpp" #include "datacloud.hpp" // WDR: class implementations //---------------------------------------------------------------------------- // LODDlg //---------------------------------------------------------------------------- // WDR: event table for LODDlg BEGIN_EVENT_TABLE(LODDlg,wxDialog) EVT_SPIN_UP( ID_TARGET, LODDlg::OnSpinTargetUp ) EVT_SPIN_DOWN( ID_TARGET, LODDlg::OnSpinTargetDown ) END_EVENT_TABLE() LODDlg::LODDlg( wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style ) : wxDialog( parent, id, title, position, size, style ) { // WDR: dialog function LODDialogFunc for LODDlg LODDialogFunc( this, TRUE ); GetTileStatus()->SetValue(_T("No paging threads")); m_iTarget = 0; } void LODDlg::Refresh(float res0, float res, float res1, int target, int count, int cache_size, int cache_used, int disk_loads, int cache_hits) { // don't bother updating if window isn't shown if (!IsShown()) return; wxString str; if (target != m_iTarget) { m_iTarget = target; str.Printf(_T("%d"), m_iTarget); GetTarget()->SetValue(str); } str.Printf(_T("%d"), count); GetCurrent()->SetValue(str); if (cache_size != m_iCacheSize || cache_used != m_iCacheUsed) { m_iCacheSize = cache_size; m_iCacheUsed = cache_used; if (m_iCacheSize == -1) str = _T("n/a"); else str.Printf(_T("%d / %d"), m_iCacheUsed/1024, m_iCacheSize/1024); GetCacheUsed()->SetValue(str); } if (disk_loads != m_iDiskLoads) { m_iDiskLoads = disk_loads; if (m_iDiskLoads == -1) str = _T("n/a"); else str.Printf(_T("%d"), m_iDiskLoads); GetTileLoads()->SetValue(str); } if (cache_hits != m_iCacheHits) { m_iCacheHits = cache_hits; if (m_iCacheHits == -1) str = _T("n/a"); else str.Printf(_T("%d"), m_iCacheHits); GetTileHits()->SetValue(str); } // Now draw the chart DrawChart(res0, res, res1, target, count); } void LODDlg::DrawChart(float res0, float res, float res1, int target, int count) { int ires = (int) res; int imax = target * 2; int itarget = target * 300 / imax; int icount = count * 300 / imax; int range = (target / 10); int irange1 = (target-range) * 300 / imax; int irange2 = (target+range) * 300 / imax; wxPanel *panel = GetPanel1(); wxClientDC dc(panel); PrepareDC(dc); dc.Clear(); if (res0 != -1) { int ires0 = (int) res0; int ires1 = (int) res1; wxPen pen1(wxColour(255,0,0), 1, wxSOLID); // red dc.SetPen(pen1); dc.DrawLine(ires0-10, 0, ires0, 10); dc.DrawLine(ires0, 10, ires0-10, 20); dc.DrawLine(ires1+10, 0, ires1, 10); dc.DrawLine(ires1, 10, ires1+10, 20); } wxPen pen2(wxColour(0,0,255), 3, wxSOLID); // blue dc.SetPen(pen2); dc.DrawLine(ires, 0, ires, 20); wxPen pen3(wxColour(0,128,0), 1, wxSOLID); // green dc.SetPen(pen3); dc.DrawLine(irange1-10, 20, irange1, 30); dc.DrawLine(irange1, 30, irange1-10, 40); dc.DrawLine(itarget, 20, itarget, 40); dc.DrawLine(irange2+10, 20, irange2, 30); dc.DrawLine(irange2, 30, irange2+10, 40); dc.DrawLine(irange1, 30, irange2, 30); wxPen pen4(wxColour(255,0,255), 3, wxSOLID); // purple dc.SetPen(pen4); dc.DrawLine(icount, 20, icount, 40); } void LODDlg::DrawTilesetState(vtTiledGeom *tg, vtCamera *cam) { wxPanel *panel = GetPanel2(); wxClientDC dc(panel); PrepareDC(dc); dc.Clear(); //wxPen pen3(wxColour(0,128,0), 1, wxSOLID); // green //dc.SetPen(pen3); wxBrush b1(wxColour(255,0,0), wxSOLID); wxBrush b2(wxColour(255,128,0), wxSOLID); wxBrush b3(wxColour(255,255,0), wxSOLID); wxBrush b4(wxColour(0,255,0), wxSOLID); wxBrush b5(wxColour(0,255,255), wxSOLID); wxBrush b6(wxColour(0,0,255), wxSOLID); wxBrush b7(wxColour(255,0,255), wxSOLID); wxBrush bwhite(wxColour(255,255,255), wxSOLID); wxPen p1(wxColour(255,0,0), 2, wxSOLID); wxPen p2(wxColour(255,128,0), 2, wxSOLID); wxPen p3(wxColour(255,255,0), 2, wxSOLID); wxPen p4(wxColour(0,255,0), 2, wxSOLID); wxPen p5(wxColour(0,255,255), 2, wxSOLID); wxPen p6(wxColour(0,0,255), 2, wxSOLID); wxPen p7(wxColour(255,0,255), 2, wxSOLID); wxPen pwhite(wxColour(255,255,255), 2, wxSOLID); wxPen pblack(wxColour(0,0,0), 1, wxSOLID); // draw rectangles for texture state minitile *mt = tg->GetMiniTile(); wxSize size = panel->GetSize(); int border = 20; int sx = (size.x - border*2) / tg->cols; int sy = (size.y - border*2) / tg->rows; for (int i = 0; i < tg->cols; i++) { for (int j = 0; j < tg->rows; j++) { int t = mt->gettexw(i,j); switch (t) { case 64: dc.SetBrush(b1); break; case 128: dc.SetBrush(b2); break; case 256: dc.SetBrush(b3); break; case 512: dc.SetBrush(b4); break; case 1024: dc.SetBrush(b5); break; case 2048: dc.SetBrush(b6); break; default: dc.SetBrush(bwhite); break; } /* int s = mt->getsize(i,j); switch (s) { case 65: dc.SetPen(p1); break; case 129: dc.SetPen(p2); break; case 257: dc.SetPen(p3); break; case 513: dc.SetPen(p4); break; case 1025: dc.SetPen(p5); break; case 2049: dc.SetPen(p6); break; default: dc.SetPen(pwhite); break; } */ dc.DrawRectangle(border + i*sx, border + j*sy, sx-1, sy-1); } } // draw camera FOV FPoint3 p = cam->GetTrans(); float fx = p.x / tg->coldim; float fy = tg->rows + (p.z / tg->coldim); int csx = border + fx * sx; int csy = border + fy * sy; dc.SetPen(pblack); dc.DrawLine(csx - 10, csy, csx + 10, csy); dc.DrawLine(csx, csy - 10, csx, csy + 10); datacloud *cloud = tg->GetDataCloud(); if (cloud) { double mem = cloud->getmem(); wxString str; str.Printf(_T("Mem %.1f MB, Total %d, Pending %d, Visible %d, Active %d, Missing %d"), mem, cloud->gettotal(), cloud->getpending(), cloud->getvisible(), cloud->getactive(), cloud->getmissing()); GetTileStatus()->SetValue(str); } // These always return the whole extents, for some reason int left = mt->getvisibleleft(); int right = mt->getvisibleright(); int bottom = mt->getvisiblebottom(); int top = mt->getvisibletop(); } // WDR: handler implementations for LODDlg void LODDlg::OnSpinTargetUp( wxSpinEvent &event ) { m_pFrame->ChangeTerrainDetail(true); event.Veto(); } void LODDlg::OnSpinTargetDown( wxSpinEvent &event ) { m_pFrame->ChangeTerrainDetail(false); event.Veto(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <mitkRenderWindow.h> #include <mitkVtkRenderWindow.h> #include <mitkNativeRenderWindowInteractor.h> #include <mitkOpenGLRenderer.h> #include <vtkConeSource.h> #include <vtkPolyDataMapper.h> #include <vtkActor.h> #include <vtkRenderer.h> #include <vtkRenderWindowInteractor.h> #include <fstream> int mitkRenderWindowTest(int /*argc*/, char* /*argv*/[]) { //Create a (native) mitk::RenderWindow std::cout << "Testing creation of RenderWindow: "; mitk::RenderWindow* renderwindow = new mitk::RenderWindow("the render window"); std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing InitRenderer(): "; renderwindow->InitRenderer(); std::cout<<"[PASSED]"<<std::endl; // use a source to create a vtkPolyData with a cone vtkConeSource * cone = vtkConeSource::New(); // creating the visualization objects (mapper, actor) vtkPolyDataMapper * coneMapper = vtkPolyDataMapper::New(); coneMapper->SetInput(cone->GetOutput()); vtkActor * coneActor = vtkActor::New(); coneActor->SetMapper(coneMapper); std::cout << "Testing whether GetRenderer() returns an mitk::OpenGLRenderer: "; mitk::OpenGLRenderer* glrenderer = dynamic_cast<mitk::OpenGLRenderer*>(renderwindow->GetRenderer()); if(glrenderer==NULL) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing glrenderer->GetVtkRenderer()==NULL: "; if(glrenderer->GetVtkRenderer()!=NULL) { std::cout<<"[FAILED] - Not really a failure! Event better like that it is now != NULL! " << std::endl << "In former times it was NULL without presence of a vtk-based Mapper." <<std::endl << "Please remove this part of the test and check, whether the rest of the test show reasonable results." << std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; vtkRenderer * ownvtkrenderer = vtkRenderer::New(); renderwindow->GetVtkRenderWindow()->AddRenderer(ownvtkrenderer); // assign the actor to the rendering environment #if (VTK_MAJOR_VERSION < 5) ownvtkrenderer->AddProp(coneActor); #else ownvtkrenderer->AddViewProp(coneActor); #endif // interact with data mitk::NativeRenderWindowInteractor::Pointer iren = mitk::NativeRenderWindowInteractor::New(); iren->SetMitkRenderWindow(renderwindow); renderwindow->RequestUpdate(); // iren->Start(); cone->Delete(); coneMapper->Delete(); coneActor->Delete(); delete renderwindow; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } <commit_msg>FIX: removed instance check of vtkRenderer<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <mitkRenderWindow.h> #include <mitkVtkRenderWindow.h> #include <mitkNativeRenderWindowInteractor.h> #include <mitkOpenGLRenderer.h> #include <vtkConeSource.h> #include <vtkPolyDataMapper.h> #include <vtkActor.h> #include <vtkRenderer.h> #include <vtkRenderWindowInteractor.h> #include <fstream> int mitkRenderWindowTest(int /*argc*/, char* /*argv*/[]) { //Create a (native) mitk::RenderWindow std::cout << "Testing creation of RenderWindow: "; mitk::RenderWindow* renderwindow = new mitk::RenderWindow("the render window"); std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing InitRenderer(): "; renderwindow->InitRenderer(); std::cout<<"[PASSED]"<<std::endl; // use a source to create a vtkPolyData with a cone vtkConeSource * cone = vtkConeSource::New(); // creating the visualization objects (mapper, actor) vtkPolyDataMapper * coneMapper = vtkPolyDataMapper::New(); coneMapper->SetInput(cone->GetOutput()); vtkActor * coneActor = vtkActor::New(); coneActor->SetMapper(coneMapper); std::cout << "Testing whether GetRenderer() returns an mitk::OpenGLRenderer: "; mitk::OpenGLRenderer* glrenderer = dynamic_cast<mitk::OpenGLRenderer*>(renderwindow->GetRenderer()); if(glrenderer==NULL) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; vtkRenderer * ownvtkrenderer = vtkRenderer::New(); renderwindow->GetVtkRenderWindow()->AddRenderer(ownvtkrenderer); // assign the actor to the rendering environment #if (VTK_MAJOR_VERSION < 5) ownvtkrenderer->AddProp(coneActor); #else ownvtkrenderer->AddViewProp(coneActor); #endif // interact with data mitk::NativeRenderWindowInteractor::Pointer iren = mitk::NativeRenderWindowInteractor::New(); iren->SetMitkRenderWindow(renderwindow); renderwindow->RequestUpdate(); // iren->Start(); cone->Delete(); coneMapper->Delete(); coneActor->Delete(); delete renderwindow; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>//================================== // PEDUMP - Matt Pietrek 1994-2001 // FILE: PEDUMP.CPP //================================== #include "stdafx.h" #include <windows.h> #include <stdio.h> #include <conio.h> #include "objdump.h" #include "exedump.h" #include "dbgdump.h" #include "libdump.h" #include "romimage.h" #include "common.h" #include "extrnvar.h" #include "resdump.h" // Global variables set here, and used elsewhere in the program BOOL fShowRelocations = TRUE; BOOL fShowRawSectionData = TRUE; BOOL fShowSymbolTable = TRUE; BOOL fShowLineNumbers = TRUE; BOOL fShowIATentries = TRUE; BOOL fShowPDATA = TRUE; BOOL fShowResources = TRUE; PBYTE g_pMappedFileBase = 0; ULARGE_INTEGER g_FileSize = {{0,0}}; PIMAGE_NT_HEADERS32 gpNTHeader32 = NULL; PIMAGE_NT_HEADERS64 gpNTHeader64 = NULL; bool g_bIs64Bit = false; bool g_bUPXed = false; /* char HelpText[] = "PEDUMP - Win32/Win64 EXE/OBJ/LIB/DBG file dumper - 2001 Matt Pietrek\n\n" "Syntax: PEDUMP [switches] filename\n\n" " /A include everything in dump\n" " /B show base relocations\n" " /H include hex dump of sections\n" " /I include Import Address Table thunk addresses\n" " /L include line number information\n" " /P include PDATA (runtime functions)\n" " /R include detailed resources (stringtables and dialogs)\n" " /S show symbol table\n"; */ // // Open up a file, memory map it, and call the appropriate dumping routine // bool DumpFile(MPanelItem* pRoot, LPCTSTR filename, bool abForceDetect) { bool lbSucceeded = false; HANDLE hFile; HANDLE hFileMapping; PIMAGE_DOS_HEADER dosHeader; gpNTHeader32 = NULL; gpNTHeader64 = NULL; g_bIs64Bit = false; g_bUPXed = false; // ! //g_pStrResEntries = 0; g_pDlgResEntries = 0; //g_cStrResEntries = 0; g_cDlgResEntries = 0; g_pMiscDebugInfo = 0; g_pCVHeader = 0; g_pCOFFHeader = 0; g_pCOFFSymbolTable = 0; PszLongnames = 0; // hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if ( hFile == INVALID_HANDLE_VALUE ) hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if ( hFile == INVALID_HANDLE_VALUE ) { merror(_T("Couldn't open file with CreateFile()\n")); return false; } g_FileSize.LowPart = GetFileSize(hFile, &g_FileSize.HighPart); if (!abForceDetect) { MEMORYSTATUSEX mem = {sizeof(MEMORYSTATUSEX)}; GlobalMemoryStatusEx(&mem); if (g_FileSize.HighPart || (g_FileSize.LowPart > mem.ullAvailPhys && g_FileSize.LowPart > mem.ullAvailPageFile)) { // , abForceDetect == false // Too large file CloseHandle(hFile); return false; } } hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL); if ( hFileMapping == 0 ) { CloseHandle(hFile); merror(_T("Couldn't open file mapping with CreateFileMapping()\n")); return false; } g_pMappedFileBase = (PBYTE)MapViewOfFile(hFileMapping,FILE_MAP_READ,0,0,0); if ( g_pMappedFileBase == 0 ) { CloseHandle(hFileMapping); CloseHandle(hFile); merror(_T("Couldn't map view of file with MapViewOfFile()\n")); return false; } pRoot->AddText(_T("Dump of file ")); pRoot->AddText(filename); pRoot->AddText(_T("\n\n")); dosHeader = (PIMAGE_DOS_HEADER)g_pMappedFileBase; PIMAGE_FILE_HEADER pImgFileHdr = (PIMAGE_FILE_HEADER)g_pMappedFileBase; __try { if ( dosHeader->e_magic == IMAGE_DOS_SIGNATURE ) { lbSucceeded = DumpExeFile( pRoot, dosHeader ); } else if ( dosHeader->e_magic == IMAGE_SEPARATE_DEBUG_SIGNATURE ) { lbSucceeded = DumpDbgFile( pRoot, (PIMAGE_SEPARATE_DEBUG_HEADER)g_pMappedFileBase ); } else if ( IsValidMachineType(pImgFileHdr->Machine) ) { if ( 0 == pImgFileHdr->SizeOfOptionalHeader ) // 0 optional header { lbSucceeded = DumpObjFile( pRoot, pImgFileHdr ); // means it's an OBJ } else if ( pImgFileHdr->SizeOfOptionalHeader == IMAGE_SIZEOF_ROM_OPTIONAL_HEADER ) { lbSucceeded = DumpROMImage( pRoot, (PIMAGE_ROM_HEADERS)pImgFileHdr ); } } else if ( 0 == strncmp((char *)g_pMappedFileBase, IMAGE_ARCHIVE_START, IMAGE_ARCHIVE_START_SIZE) ) { lbSucceeded = DumpLibFile( pRoot, g_pMappedFileBase ); } else { if (abForceDetect) merror(_T("Unrecognized file format\n")); lbSucceeded = false; } }__except(EXCEPTION_EXECUTE_HANDLER){ pRoot->AddText(_T("\n\n!!! Exception !!!\n")); if (abForceDetect) merror(_T("Exception, while dumping\n")); lbSucceeded = false; } UnmapViewOfFile(g_pMappedFileBase); CloseHandle(hFileMapping); CloseHandle(hFile); return lbSucceeded; } // // process all the command line arguments and return a pointer to // the filename argument. // /* PSTR ProcessCommandLine(int argc, char *argv[]) { int i; for ( i=1; i < argc; i++ ) { _strupr(argv[i]); // Is it a switch character? if ( (argv[i][0] == '-') || (argv[i][0] == '/') ) { if ( argv[i][1] == 'A' ) { fShowRelocations = TRUE; fShowRawSectionData = TRUE; fShowSymbolTable = TRUE; fShowLineNumbers = TRUE; fShowIATentries = TRUE; fShowPDATA = TRUE; fShowResources = TRUE; } else if ( argv[i][1] == 'H' ) fShowRawSectionData = TRUE; else if ( argv[i][1] == 'L' ) fShowLineNumbers = TRUE; else if ( argv[i][1] == 'P' ) fShowPDATA = TRUE; else if ( argv[i][1] == 'B' ) fShowRelocations = TRUE; else if ( argv[i][1] == 'S' ) fShowSymbolTable = TRUE; else if ( argv[i][1] == 'I' ) fShowIATentries = TRUE; else if ( argv[i][1] == 'R' ) fShowResources = TRUE; } else // Not a switch character. Must be the filename { return argv[i]; } } return NULL; } */ /* int main(int argc, char *argv[]) { PSTR filename; if ( argc == 1 ) { printf( HelpText ); return 1; } filename = ProcessCommandLine(argc, argv); if ( filename ) DumpFile( filename ); #ifdef _DEBUG if (IsDebuggerPresent()) { printf("Press any key..."); _getch(); } #endif return 0; } */ <commit_msg>ImpEx. Verbose error information if file open failed<commit_after>//================================== // PEDUMP - Matt Pietrek 1994-2001 // FILE: PEDUMP.CPP //================================== #include "stdafx.h" #include <windows.h> #include <stdio.h> #include <conio.h> #include "objdump.h" #include "exedump.h" #include "dbgdump.h" #include "libdump.h" #include "romimage.h" #include "common.h" #include "extrnvar.h" #include "resdump.h" // Global variables set here, and used elsewhere in the program BOOL fShowRelocations = TRUE; BOOL fShowRawSectionData = TRUE; BOOL fShowSymbolTable = TRUE; BOOL fShowLineNumbers = TRUE; BOOL fShowIATentries = TRUE; BOOL fShowPDATA = TRUE; BOOL fShowResources = TRUE; PBYTE g_pMappedFileBase = 0; ULARGE_INTEGER g_FileSize = {{0,0}}; PIMAGE_NT_HEADERS32 gpNTHeader32 = NULL; PIMAGE_NT_HEADERS64 gpNTHeader64 = NULL; bool g_bIs64Bit = false; bool g_bUPXed = false; /* char HelpText[] = "PEDUMP - Win32/Win64 EXE/OBJ/LIB/DBG file dumper - 2001 Matt Pietrek\n\n" "Syntax: PEDUMP [switches] filename\n\n" " /A include everything in dump\n" " /B show base relocations\n" " /H include hex dump of sections\n" " /I include Import Address Table thunk addresses\n" " /L include line number information\n" " /P include PDATA (runtime functions)\n" " /R include detailed resources (stringtables and dialogs)\n" " /S show symbol table\n"; */ // // Open up a file, memory map it, and call the appropriate dumping routine // bool DumpFile(MPanelItem* pRoot, LPCTSTR filename, bool abForceDetect) { bool lbSucceeded = false; HANDLE hFile; HANDLE hFileMapping; PIMAGE_DOS_HEADER dosHeader; gpNTHeader32 = NULL; gpNTHeader64 = NULL; g_bIs64Bit = false; g_bUPXed = false; // ! //g_pStrResEntries = 0; g_pDlgResEntries = 0; //g_cStrResEntries = 0; g_cDlgResEntries = 0; g_pMiscDebugInfo = 0; g_pCVHeader = 0; g_pCOFFHeader = 0; g_pCOFFSymbolTable = 0; PszLongnames = 0; // hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if ( hFile == INVALID_HANDLE_VALUE ) hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if ( hFile == INVALID_HANDLE_VALUE ) { merror(_T("Couldn't open file with CreateFile()\n%s\nErrCode=%u"), filename, GetLastError()); return false; } g_FileSize.LowPart = GetFileSize(hFile, &g_FileSize.HighPart); if (!abForceDetect) { MEMORYSTATUSEX mem = {sizeof(MEMORYSTATUSEX)}; GlobalMemoryStatusEx(&mem); if (g_FileSize.HighPart || (g_FileSize.LowPart > mem.ullAvailPhys && g_FileSize.LowPart > mem.ullAvailPageFile)) { // , abForceDetect == false // Too large file CloseHandle(hFile); return false; } } hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL); if ( hFileMapping == 0 ) { CloseHandle(hFile); merror(_T("Couldn't open file mapping with CreateFileMapping()\n%s\nErrCode=%u"), filename, GetLastError()); return false; } g_pMappedFileBase = (PBYTE)MapViewOfFile(hFileMapping,FILE_MAP_READ,0,0,0); if ( g_pMappedFileBase == 0 ) { CloseHandle(hFileMapping); CloseHandle(hFile); merror(_T("Couldn't map view of file with MapViewOfFile()\n%s\nErrCode=%u"), filename, GetLastError()); return false; } pRoot->AddText(_T("Dump of file ")); pRoot->AddText(filename); pRoot->AddText(_T("\n\n")); dosHeader = (PIMAGE_DOS_HEADER)g_pMappedFileBase; PIMAGE_FILE_HEADER pImgFileHdr = (PIMAGE_FILE_HEADER)g_pMappedFileBase; __try { if ( dosHeader->e_magic == IMAGE_DOS_SIGNATURE ) { lbSucceeded = DumpExeFile( pRoot, dosHeader ); } else if ( dosHeader->e_magic == IMAGE_SEPARATE_DEBUG_SIGNATURE ) { lbSucceeded = DumpDbgFile( pRoot, (PIMAGE_SEPARATE_DEBUG_HEADER)g_pMappedFileBase ); } else if ( IsValidMachineType(pImgFileHdr->Machine) ) { if ( 0 == pImgFileHdr->SizeOfOptionalHeader ) // 0 optional header { lbSucceeded = DumpObjFile( pRoot, pImgFileHdr ); // means it's an OBJ } else if ( pImgFileHdr->SizeOfOptionalHeader == IMAGE_SIZEOF_ROM_OPTIONAL_HEADER ) { lbSucceeded = DumpROMImage( pRoot, (PIMAGE_ROM_HEADERS)pImgFileHdr ); } } else if ( 0 == strncmp((char *)g_pMappedFileBase, IMAGE_ARCHIVE_START, IMAGE_ARCHIVE_START_SIZE) ) { lbSucceeded = DumpLibFile( pRoot, g_pMappedFileBase ); } else { if (abForceDetect) merror(_T("Unrecognized file format\n")); lbSucceeded = false; } }__except(EXCEPTION_EXECUTE_HANDLER){ pRoot->AddText(_T("\n\n!!! Exception !!!\n")); if (abForceDetect) merror(_T("Exception, while dumping\n")); lbSucceeded = false; } UnmapViewOfFile(g_pMappedFileBase); CloseHandle(hFileMapping); CloseHandle(hFile); return lbSucceeded; } // // process all the command line arguments and return a pointer to // the filename argument. // /* PSTR ProcessCommandLine(int argc, char *argv[]) { int i; for ( i=1; i < argc; i++ ) { _strupr(argv[i]); // Is it a switch character? if ( (argv[i][0] == '-') || (argv[i][0] == '/') ) { if ( argv[i][1] == 'A' ) { fShowRelocations = TRUE; fShowRawSectionData = TRUE; fShowSymbolTable = TRUE; fShowLineNumbers = TRUE; fShowIATentries = TRUE; fShowPDATA = TRUE; fShowResources = TRUE; } else if ( argv[i][1] == 'H' ) fShowRawSectionData = TRUE; else if ( argv[i][1] == 'L' ) fShowLineNumbers = TRUE; else if ( argv[i][1] == 'P' ) fShowPDATA = TRUE; else if ( argv[i][1] == 'B' ) fShowRelocations = TRUE; else if ( argv[i][1] == 'S' ) fShowSymbolTable = TRUE; else if ( argv[i][1] == 'I' ) fShowIATentries = TRUE; else if ( argv[i][1] == 'R' ) fShowResources = TRUE; } else // Not a switch character. Must be the filename { return argv[i]; } } return NULL; } */ /* int main(int argc, char *argv[]) { PSTR filename; if ( argc == 1 ) { printf( HelpText ); return 1; } filename = ProcessCommandLine(argc, argv); if ( filename ) DumpFile( filename ); #ifdef _DEBUG if (IsDebuggerPresent()) { printf("Press any key..."); _getch(); } #endif return 0; } */ <|endoftext|>
<commit_before>#include "config.h" #include <rule/rules.hpp> #include <rule/Literal.hpp> #include <rule/Optional.hpp> #include <rule/Discard.hpp> #include <rule/Multiple.hpp> #include <rule/Predicate.hpp> #include <rule/Proxy.hpp> #include <rule/Alternative.hpp> #include <rule/Lazy.hpp> #include <rule/Reduce.hpp> #include <StreamIterator.hpp> #include <QString> #include <QChar> #include <QTextStream> #include <QRegExp> #include <QElapsedTimer> #ifdef HAVE_BOOST #include <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #endif #include <iostream> #include <cassert> using namespace sprout; const int RUNS = 1e5; template <class Runner> void runBenchmark(const char* name, Runner runner) { QElapsedTimer timer; timer.start(); for (int i = 0; i < RUNS; ++i) { runner(); } std::cout << name << " took " << timer.elapsed() << " ms\n"; } int main() { using namespace rule; auto fastWhitespace = whitespace<QString>(); auto whitespace = discard( multiple(predicate<QChar, QString>([](const QChar& input, QString&) { return input.isSpace(); })) ); auto name = aggregate<QString>( multiple(simplePredicate<QChar>([](const QChar& input) { return input.isLetter() || input == '_'; })), [](QString& aggregate, const QChar& c) { aggregate += c; } ); auto fastName = [](Cursor<QChar>& orig, Result<QString>& result) { auto iter = orig; QString aggr; while (iter) { auto input = *iter++; if (input.isLetter() || input == '_') { aggr += input; } else { break; } } if (aggr.isNull()) { return false; } result.insert(aggr); orig = iter; return true; }; std::cout << "Running " << RUNS << " iteration" << (RUNS == 1 ? "" : "s") << "\n"; std::cout << std::endl; { std::cout << "=== Parser Benchmarks ===\n"; const QString inputString("var bar"); const QString targetString("bar"); { QRegExp re("^var\\s+(\\w+)"); runBenchmark("RegExp", [&]() { assert(re.indexIn(inputString, 0) == 0); assert(re.cap(1) == targetString); }); } { auto benchmark = proxySequence<QChar, QString>( discard(OrderedLiteral<QChar, QString>("var")), whitespace, name ); runBenchmark("Sprout", [&]() { auto cursor = makeCursor<QChar>(&inputString); Result<QString> results; assert(benchmark(cursor, results)); assert(targetString == *results); }); } { auto benchmark = proxySequence<QChar, QString>( discard(OrderedLiteral<QChar, QString>("var")), fastWhitespace, fastName ); runBenchmark("Spfast", [&]() { auto cursor = makeCursor<QChar>(&inputString); Result<QString> results; assert(benchmark(cursor, results)); assert(targetString == *results); }); } { runBenchmark("Inline", [&]() { QString result; if (!inputString.startsWith("var")) { assert(false); } int mark = 3; while (mark < inputString.size() && inputString.at(mark).isSpace()) { ++mark; } QString aggr; while (mark < inputString.size() && inputString.at(mark).isLetter()) { aggr += inputString.at(mark++); } assert(aggr == targetString); }); } std::cout << std::endl; } { std::cout << "=== Direct Match Benchmarks ===\n"; const QString inputString("var"); const QString targetString("var"); { QRegExp re("^var"); runBenchmark("RegExp", [&]() { assert(re.indexIn(inputString, 0) == 0); assert(re.cap(0) == targetString); }); } { auto benchmark = OrderedLiteral<QChar, QString>("var", "var"); runBenchmark("Sprout", [&]() { auto cursor = makeCursor<QChar>(&inputString); Result<QString> results; assert(benchmark(cursor, results)); assert(*results == targetString); }); } { QString varStr("var"); auto benchmark = [&](Cursor<QChar>& orig, Result<QString>& results) { auto iter = orig; for (int i = 0; i < varStr.size(); ++i) { if (!iter || *iter++ != varStr.at(i)) { return false; } } orig = iter; results.insert(varStr); return true; }; runBenchmark("Spfast", [&]() { auto cursor = makeCursor<QChar>(&inputString); Result<QString> results; assert(benchmark(cursor, results)); assert(*results == targetString); }); } #ifdef HAVE_BOOST { std::string input("varbar"); std::string target("bar"); runBenchmark("Booost", [&]() { namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; namespace phoenix = boost::phoenix; using qi::_1; std::string word; auto result = qi::phrase_parse( input.begin(), input.end(), ( "var" >> qi::string("bar")[phoenix::ref(word) = "bar"] ), ascii::space ); assert(result); assert(word == target); }); } #endif std::cout << std::endl; } { std::cout << "=== Aggregating Match Benchmarks ===\n"; const QString inputString("varbar"); const QString targetString("bar"); { QRegExp re("^var(\\w+)"); runBenchmark("RegExp", [&]() { assert(re.indexIn(inputString, 0) == 0); assert(re.cap(1) == targetString); }); } { auto benchmark = proxySequence<QChar, QString>( discard(OrderedLiteral<QChar, QString>("var")), name ); runBenchmark("Sprout", [&]() { auto cursor = makeCursor<QChar>(&inputString); Result<QString> results; assert(benchmark(cursor, results)); assert(*results == targetString); }); } { auto benchmark = proxySequence<QChar, QString>( discard(OrderedLiteral<QChar, QString>("var")), fastName ); runBenchmark("Spfast", [&]() { auto cursor = makeCursor<QChar>(&inputString); Result<QString> results; assert(benchmark(cursor, results)); assert(*results == targetString); }); } #ifdef HAVE_BOOST { std::string inputString = "varbar"; std::string targetString = "bar"; runBenchmark("Booost", [&]() { namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; namespace phoenix = boost::phoenix; using qi::double_; using qi::_1; std::vector<char> letters; auto result = qi::phrase_parse( inputString.begin(), inputString.end(), ( "var" >> (+ascii::char_)[phoenix::ref(letters) = _1] ), ascii::space ); std::string word(letters.begin(), letters.end()); assert(result); assert(word == targetString); }); } #endif std::cout << std::endl; } { std::cout << "=== Whitespace Match Benchmarks ===\n"; const QString inputString(" foo"); const QString targetString("foo"); { QRegExp re("^\\s+(foo)"); runBenchmark("RegExp", [&]() { assert(re.indexIn(inputString, 0) == 0); assert(re.cap(1) == targetString); }); } { auto benchmark = proxySequence<QChar, QString>( whitespace, OrderedLiteral<QChar, QString>("foo", "foo") ); runBenchmark("Sprout", [&]() { auto cursor = makeCursor<QChar>(&inputString); Result<QString> results; assert(benchmark(cursor, results)); assert(*results == targetString); }); } { auto benchmark = proxySequence<QChar, QString>( fastWhitespace, OrderedLiteral<QChar, QString>("foo", "foo") ); runBenchmark("Spfast", [&]() { auto cursor = makeCursor<QChar>(&inputString); Result<QString> results; assert(benchmark(cursor, results)); assert(*results == targetString); }); } #ifdef HAVE_BOOST { std::string input(" foo"); std::string target("foo"); runBenchmark("Booost", [&]() { namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; namespace phoenix = boost::phoenix; using qi::_1; std::string word; auto result = qi::phrase_parse( input.begin(), input.end(), ( *ascii::space >> qi::string("foo")[phoenix::ref(word) = "foo"] ), ascii::space ); assert(result); assert(word == target); }); } #endif std::cout << std::endl; } { std::cout << "=== Lazy Match Benchmarks ===\n"; const QString inputString("foo #notime"); const QString targetString("foo"); { QRegExp re("^(foo)\\s*(#.*)?$"); runBenchmark("RegExp", [&]() { assert(re.indexIn(inputString, 0) == 0); assert(re.cap(1) == targetString); }); } { auto benchmark = proxySequence<QChar, QString>( OrderedLiteral<QChar, QString>("foo", "foo"), rule::discard(rule::whitespace<QString>()), discard(proxySequence<QChar, QString>( OrderedLiteral<QChar, QString>("#"), proxyLazy<QChar, QString>( rule::any<QChar, QString>(), proxyAlternative<QChar, QString>( OrderedLiteral<QChar, QString>("\n"), rule::end<QChar, QString>() ) ) )) ); runBenchmark("Sprout", [&]() { auto cursor = makeCursor<QChar>(&inputString); Result<QString> results; assert(benchmark(cursor, results)); assert(*results == targetString); }); } { auto benchmark = proxySequence<QChar, QString>( OrderedLiteral<QChar, QString>("foo", "foo"), discard(optional(fastWhitespace)), [](Cursor<QChar>& iter, Result<QString>& result) { if (!iter || *iter != '#') { return false; } while (iter && *iter != '\n') { // Skip commented characters ++iter; } return true; } ); runBenchmark("Spfast", [&]() { auto cursor = makeCursor<QChar>(&inputString); Result<QString> results; assert(benchmark(cursor, results)); assert(*results == targetString); }); } #ifdef HAVE_BOOST { auto input = inputString.toStdString(); auto target = targetString.toStdString(); runBenchmark("Booost", [&]() { namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; namespace phoenix = boost::phoenix; using qi::double_; using qi::_1; std::string word; auto result = qi::phrase_parse( input.begin(), input.end(), ( qi::string("foo")[phoenix::ref(word) = "foo"] >> *ascii::space >> -("#" >> *ascii::char_) ), ascii::space ); assert(result); assert(word == target); }); } #endif std::cout << std::endl; } { std::cout << "=== Cursor Benchmarks ===\n"; { QString target("var foo"); QString str("var foo"); runBenchmark("Sprout", [&]() { auto cursor = makeCursor<QChar>(&str); for (int j = 0; j < target.size(); ++j) { if (target.at(j) != *cursor++) { assert(false); } } }); } { QString target("var foo"); QString str("var foo"); runBenchmark("Inline", [&]() { QString result; auto cursor = makeCursor<QChar>(&str); result = "foo"; for (int j = 0; j < target.size(); ++j) { if (target.at(j) != str.at(j)) { result = ""; } } }); } } return 0; } // vim: set ts=4 sw=4 : <commit_msg>Update benchmarks to be a bit faster<commit_after>#include "config.h" #include <rule/rules.hpp> #include <rule/Literal.hpp> #include <rule/Optional.hpp> #include <rule/Discard.hpp> #include <rule/Multiple.hpp> #include <rule/Predicate.hpp> #include <rule/Alternative.hpp> #include <rule/Lazy.hpp> #include <rule/Reduce.hpp> #include <StreamIterator.hpp> #include <QString> #include <QChar> #include <QTextStream> #include <QRegExp> #include <QElapsedTimer> #ifdef HAVE_BOOST #include <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #endif #include <iostream> #include <cassert> using namespace sprout; const int RUNS = 1e5; template <class Runner> void runBenchmark(const char* name, Runner runner) { QElapsedTimer timer; timer.start(); for (int i = 0; i < RUNS; ++i) { runner(); } std::cout << name << " took " << timer.elapsed() << " ms\n"; } int main() { using namespace rule; auto name = aggregate<QString>( multiple(simplePredicate<QChar>([](const QChar& input) { return input.isLetter() || input == '_'; })), [](QString& aggregate, const QChar& c) { aggregate += c; } ); auto fastName = [](Cursor<QChar>& orig, Result<QString>& result) { auto iter = orig; QString aggr; while (iter) { auto input = *iter++; if (input.isLetter() || input == '_') { aggr += input; } else { break; } } if (aggr.isNull()) { return false; } result.insert(aggr); orig = iter; return true; }; std::cout << "Running " << RUNS << " iteration" << (RUNS == 1 ? "" : "s") << "\n"; std::cout << std::endl; { std::cout << "=== Parser Benchmarks ===\n"; const QString inputString("var bar"); const QString targetString("bar"); { QRegExp re("^var\\s+(\\w+)"); runBenchmark("RegExp", [&]() { assert(re.indexIn(inputString, 0) == 0); assert(re.cap(1) == targetString); }); } { auto benchmark = tupleSequence<QChar, QString>( discard(OrderedLiteral<QChar, QString>("var")), rule::whitespace<QString>(), name ); auto orig = makeCursor<QChar>(&inputString); Result<QString> results; auto head = results.head(); runBenchmark("Sprout", [&]() { results.moveHead(head); auto iter = orig; assert(benchmark(iter, results)); assert(targetString == *results); }); } { auto benchmark = tupleSequence<QChar, QString>( discard(OrderedLiteral<QChar, QString>("var")), rule::whitespace<QString>(), fastName ); auto orig = makeCursor<QChar>(&inputString); Result<QString> results; auto head = results.head(); runBenchmark("Spfast", [&]() { results.moveHead(head); auto iter = orig; assert(benchmark(iter, results)); assert(targetString == results.get()); }); } { runBenchmark("Inline", [&]() { QString result; if (!inputString.startsWith("var")) { assert(false); } int mark = 3; while (mark < inputString.size() && inputString.at(mark).isSpace()) { ++mark; } QString aggr; while (mark < inputString.size() && inputString.at(mark).isLetter()) { aggr += inputString.at(mark++); } assert(aggr == targetString); }); } std::cout << std::endl; } { std::cout << "=== Direct Match Benchmarks ===\n"; const QString inputString("var"); const QString targetString("var"); { QRegExp re("^var"); runBenchmark("RegExp", [&]() { assert(re.indexIn(inputString, 0) == 0); assert(re.cap(0) == targetString); }); } { auto benchmark = OrderedLiteral<QChar, QString>("var", "var"); auto orig = makeCursor<QChar>(&inputString); Result<QString> results; auto head = results.head(); runBenchmark("Sprout", [&]() { results.moveHead(head); auto iter = orig; assert(benchmark(iter, results)); assert(results.get() == targetString); }); } { QString varStr("var"); auto benchmark = [&](Cursor<QChar>& orig, Result<QString>& results) { auto iter = orig; for (int i = 0; i < varStr.size(); ++i) { if (!iter || *iter++ != varStr.at(i)) { return false; } } orig = iter; results.insert(varStr); return true; }; auto orig = makeCursor<QChar>(&inputString); Result<QString> results; auto head = results.head(); runBenchmark("Spfast", [&]() { auto iter = orig; results.moveHead(head); assert(benchmark(iter, results)); assert(results.get() == targetString); }); } #ifdef HAVE_BOOST { std::string input("varbar"); std::string target("bar"); runBenchmark("Booost", [&]() { namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; namespace phoenix = boost::phoenix; using qi::_1; std::string word; auto result = qi::phrase_parse( input.begin(), input.end(), ( "var" >> qi::string("bar")[phoenix::ref(word) = "bar"] ), ascii::space ); assert(result); assert(word == target); }); } #endif std::cout << std::endl; } { std::cout << "=== Aggregating Match Benchmarks ===\n"; const QString inputString("varbar"); const QString targetString("bar"); { QRegExp re("^var(\\w+)"); runBenchmark("RegExp", [&]() { assert(re.indexIn(inputString, 0) == 0); assert(re.cap(1) == targetString); }); } { auto benchmark = tupleSequence<QChar, QString>( discard(OrderedLiteral<QChar, QString>("var")), name ); auto orig = makeCursor<QChar>(&inputString); Result<QString> results; auto head = results.head(); runBenchmark("Sprout", [&]() { results.moveHead(head); auto iter = orig; assert(benchmark(iter, results)); assert(results.get() == targetString); }); } { auto benchmark = tupleSequence<QChar, QString>( discard(OrderedLiteral<QChar, QString>("var")), fastName ); auto orig = makeCursor<QChar>(&inputString); Result<QString> results; auto head = results.head(); runBenchmark("Spfast", [&]() { results.moveHead(head); auto iter = orig; assert(benchmark(iter, results)); assert(results.get() == targetString); }); } #ifdef HAVE_BOOST { std::string inputString = "varbar"; std::string targetString = "bar"; runBenchmark("Booost", [&]() { namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; namespace phoenix = boost::phoenix; using qi::double_; using qi::_1; std::vector<char> letters; auto result = qi::phrase_parse( inputString.begin(), inputString.end(), ( "var" >> (+ascii::char_)[phoenix::ref(letters) = _1] ), ascii::space ); std::string word(letters.begin(), letters.end()); assert(result); assert(word == targetString); }); } #endif std::cout << std::endl; } { std::cout << "=== Whitespace Match Benchmarks ===\n"; const QString inputString(" foo"); const QString targetString("foo"); { QRegExp re("^\\s+(foo)"); runBenchmark("RegExp", [&]() { assert(re.indexIn(inputString, 0) == 0); assert(re.cap(1) == targetString); }); } { auto benchmark = tupleSequence<QChar, QString>( discard( multiple(predicate<QChar, QString>([](const QChar& input, QString&) { return input.isSpace(); })) ), OrderedLiteral<QChar, QString>("foo", "foo") ); auto orig = makeCursor<QChar>(&inputString); Result<QString> results; auto head = results.head(); runBenchmark("Sprout", [&]() { auto iter = orig; results.moveHead(head); assert(benchmark(iter, results)); assert(results.get() == targetString); }); } { auto benchmark = tupleSequence<QChar, QString>( rule::whitespace<QString>(), OrderedLiteral<QChar, QString>("foo", "foo") ); Result<QString> results; auto head = results.head(); auto orig = makeCursor<QChar>(&inputString); runBenchmark("Spfast", [&]() { results.moveHead(head); auto iter = orig; assert(benchmark(iter, results)); assert(*results == targetString); }); } #ifdef HAVE_BOOST { std::string input(" foo"); std::string target("foo"); runBenchmark("Booost", [&]() { namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; namespace phoenix = boost::phoenix; using qi::_1; std::string word; auto result = qi::phrase_parse( input.begin(), input.end(), ( *ascii::space >> qi::string("foo")[phoenix::ref(word) = "foo"] ), ascii::space ); assert(result); assert(word == target); }); } #endif std::cout << std::endl; } { std::cout << "=== Lazy Match Benchmarks ===\n"; const QString inputString("foo #notime"); const QString targetString("foo"); { QRegExp re("^(foo)\\s*(#.*)?$"); runBenchmark("RegExp", [&]() { assert(re.indexIn(inputString, 0) == 0); assert(re.cap(1) == targetString); }); } { auto benchmark = tupleSequence<QChar, QString>( OrderedLiteral<QChar, QString>("foo", "foo"), rule::discard(rule::whitespace<QString>()), rule::discard(tupleSequence<QChar, QString>( OrderedLiteral<QChar, QString>("#"), rule::lazy<QChar, QString>( rule::any<QChar, QString>(), tupleAlternative<QChar, QString>( OrderedLiteral<QChar, QString>("\n"), rule::end<QChar, QString>() ) ) )) ); auto orig = makeCursor<QChar>(&inputString); Result<QString> results; auto head = results.head(); runBenchmark("Sprout", [&]() { results.moveHead(head); auto iter = orig; assert(benchmark(iter, results)); assert(results.get() == targetString); }); } { auto benchmark = tupleSequence<QChar, QString>( OrderedLiteral<QChar, QString>("foo", "foo"), discard(optional(rule::whitespace<QString>())), [](Cursor<QChar>& iter, Result<QString>& result) { if (!iter || *iter != '#') { return false; } while (iter && *iter != '\n') { // Skip commented characters ++iter; } return true; } ); auto orig = makeCursor<QChar>(&inputString); Result<QString> results; auto head = results.head(); runBenchmark("Spfast", [&]() { auto iter = orig; results.moveHead(head); assert(benchmark(iter, results)); assert(results.get() == targetString); }); } #ifdef HAVE_BOOST { auto input = inputString.toStdString(); auto target = targetString.toStdString(); runBenchmark("Booost", [&]() { namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; namespace phoenix = boost::phoenix; using qi::double_; using qi::_1; std::string word; auto result = qi::phrase_parse( input.begin(), input.end(), ( qi::string("foo")[phoenix::ref(word) = "foo"] >> *ascii::space >> -("#" >> *ascii::char_) ), ascii::space ); assert(result); assert(word == target); }); } #endif std::cout << std::endl; } { std::cout << "=== Cursor Benchmarks ===\n"; { QString target("var foo"); QString str("var foo"); runBenchmark("Sprout", [&]() { auto cursor = makeCursor<QChar>(&str); for (int j = 0; j < target.size(); ++j) { if (target.at(j) != *cursor++) { assert(false); } } }); } { QString target("var foo"); QString str("var foo"); runBenchmark("Inline", [&]() { QString result; auto cursor = makeCursor<QChar>(&str); result = "foo"; for (int j = 0; j < target.size(); ++j) { if (target.at(j) != str.at(j)) { result = ""; } } }); } } return 0; } // vim: set ts=4 sw=4 : <|endoftext|>
<commit_before>#include <stdint.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <vector> #if defined(__MACH__) #include <mach/mach_time.h> #elif defined(__linux__) #include <time.h> #endif uint64_t nanotime() { #if defined(__MACH__) static mach_timebase_info_data_t info; if (info.denom == 0) mach_timebase_info(&info); return mach_absolute_time() * info.numer / info.denom; #elif defined(__linux__) struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec * UINT64_C(1000000000) + ts.tv_nsec; #endif } #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "gason.h" struct Stat { const char *parserName; size_t sourceSize; size_t objectCount; size_t arrayCount; size_t numberCount; size_t stringCount; size_t trueCount; size_t falseCount; size_t nullCount; size_t memberCount; size_t elementCount; size_t stringLength; uint64_t parseTime; uint64_t updateTime; }; struct Rapid { rapidjson::Document doc; bool parse(const std::vector<char> &buffer) { doc.Parse(buffer.data()); return doc.HasParseError(); } const char *strError() { return rapidjson::GetParseError_En(doc.GetParseError()); } void update(Stat &stat) { genStat(stat, doc); } static void genStat(Stat &stat, const rapidjson::Value &v) { using namespace rapidjson; switch (v.GetType()) { case kNullType: stat.nullCount++; break; case kFalseType: stat.falseCount++; break; case kTrueType: stat.trueCount++; break; case kObjectType: for (Value::ConstMemberIterator m = v.MemberBegin(); m != v.MemberEnd(); ++m) { stat.stringLength += m->name.GetStringLength(); genStat(stat, m->value); } stat.objectCount++; stat.memberCount += (v.MemberEnd() - v.MemberBegin()); stat.stringCount += (v.MemberEnd() - v.MemberBegin()); break; case kArrayType: for (Value::ConstValueIterator i = v.Begin(); i != v.End(); ++i) genStat(stat, *i); stat.arrayCount++; stat.elementCount += v.Size(); break; case kStringType: stat.stringCount++; stat.stringLength += v.GetStringLength(); break; case kNumberType: stat.numberCount++; break; } } static const char *name() { return "rapid normal"; } }; struct RapidInsitu : Rapid { std::vector<char> source; bool parse(const std::vector<char> &buffer) { source = buffer; doc.ParseInsitu(source.data()); return doc.HasParseError(); } static const char *name() { return "rapid insitu"; } }; struct Gason { std::vector<char> source; JsonAllocator allocator; JsonValue value; char *endptr; int result; bool parse(const std::vector<char> &buffer) { source = buffer; return (result = jsonParse(source.data(), &endptr, &value, allocator)) == JSON_OK; } const char *strError() { return jsonStrError(result); } void update(Stat &stat) { genStat(stat, value); } static void genStat(Stat &stat, JsonValue v) { switch (v.getTag()) { case JSON_ARRAY: for (auto i : v) { genStat(stat, i->value); stat.elementCount++; } stat.arrayCount++; break; case JSON_OBJECT: for (auto i : v) { genStat(stat, i->value); stat.memberCount++; stat.stringLength += strlen(i->key); stat.stringCount++; } stat.objectCount++; break; case JSON_STRING: stat.stringCount++; stat.stringLength += strlen(v.toString()); break; case JSON_NUMBER: stat.numberCount++; break; case JSON_TRUE: stat.trueCount++; break; case JSON_FALSE: stat.falseCount++; break; case JSON_NULL: stat.nullCount++; break; } } static const char *name() { return "gason"; } }; template <typename T> static Stat run(size_t iterations, const std::vector<char> &buffer) { Stat stat; memset(&stat, 0, sizeof(stat)); stat.parserName = T::name(); stat.sourceSize = buffer.size() * iterations; std::vector<T> docs(iterations); auto t = nanotime(); for (auto &i : docs) { i.parse(buffer); } stat.parseTime += nanotime() - t; t = nanotime(); for (auto &i : docs) i.update(stat); stat.updateTime += nanotime() - t; return stat; } static void print(const Stat &stat) { printf("%8zd %8zd %8zd %8zd %8zd %8zd %8zd %8zd %8zd %8zd %8zd %11.2f %11.2f %11.2f %s\n", stat.objectCount, stat.arrayCount, stat.numberCount, stat.stringCount, stat.trueCount, stat.falseCount, stat.nullCount, stat.memberCount, stat.elementCount, stat.stringLength, stat.sourceSize, stat.updateTime / 1e6, stat.parseTime / 1e6, stat.sourceSize / (stat.parseTime / 1e9) / (1 << 20), stat.parserName); } #if defined(__clang__) #define COMPILER "Clang " __clang_version__ #elif defined(__GNUC__) #define COMPILER "GCC " __VERSION__ #endif #ifndef __x86_64__ #define __x86_64__ 0 #endif #ifndef NDEBUG #define NDEBUG 0 #endif int main(int argc, const char **argv) { printf("gason benchmark, %s, x86_64 %d, SIZEOF_POINTER %d, NDEBUG %d\n", COMPILER, __x86_64__, __SIZEOF_POINTER__, NDEBUG); size_t iterations = 10; for (int i = 1; i < argc; ++i) { if (!strcmp("-n", argv[i])) { iterations = strtol(argv[++i], NULL, 0); continue; } FILE *fp = fopen(argv[i], "r"); if (!fp) { perror(argv[i]); exit(EXIT_FAILURE); } fseek(fp, 0, SEEK_END); size_t size = ftell(fp); fseek(fp, 0, SEEK_SET); std::vector<char> buffer; buffer.resize(size + 1); fread(buffer.data(), 1, size, fp); fclose(fp); putchar('\n'); printf("%s, %zdB x %zd:\n", argv[i], size, iterations); printf("%8s %8s %8s %8s %8s %8s %8s %8s %8s %8s %8s %11s %11s %11s\n", "Object", "Array", "Number", "String", "True", "False", "Null", "Member", "Element", "StrLen", "Size", "Update(ms)", "Parse(ms)", "Speed(Mb/s)"); print(run<Rapid>(iterations, buffer)); print(run<RapidInsitu>(iterations, buffer)); print(run<Gason>(iterations, buffer)); } return 0; } <commit_msg>windows nanosleep() implementation<commit_after>#include <stdint.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <vector> #if defined(__linux__) #include <time.h> #elif defined(__MACH__) #include <mach/mach_time.h> #elif defined(_WIN32) #include <windows.h> #endif uint64_t nanotime() { #if defined(__linux__) struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec * UINT64_C(1000000000) + ts.tv_nsec; #elif defined(__MACH__) static mach_timebase_info_data_t info; if (info.denom == 0) mach_timebase_info(&info); return mach_absolute_time() * info.numer / info.denom; #elif defined(_WIN32) static LARGE_INTEGER frequency; if (frequency.QuadPart == 0) QueryPerformanceFrequency(&frequency); LARGE_INTEGER counter; QueryPerformanceCounter(&counter); return counter.QuadPart * UINT64_C(1000000000) / frequency.QuadPart; #endif } #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "gason.h" struct Stat { const char *parserName; size_t sourceSize; size_t objectCount; size_t arrayCount; size_t numberCount; size_t stringCount; size_t trueCount; size_t falseCount; size_t nullCount; size_t memberCount; size_t elementCount; size_t stringLength; uint64_t parseTime; uint64_t updateTime; }; struct Rapid { rapidjson::Document doc; bool parse(const std::vector<char> &buffer) { doc.Parse(buffer.data()); return doc.HasParseError(); } const char *strError() { return rapidjson::GetParseError_En(doc.GetParseError()); } void update(Stat &stat) { genStat(stat, doc); } static void genStat(Stat &stat, const rapidjson::Value &v) { using namespace rapidjson; switch (v.GetType()) { case kNullType: stat.nullCount++; break; case kFalseType: stat.falseCount++; break; case kTrueType: stat.trueCount++; break; case kObjectType: for (Value::ConstMemberIterator m = v.MemberBegin(); m != v.MemberEnd(); ++m) { stat.stringLength += m->name.GetStringLength(); genStat(stat, m->value); } stat.objectCount++; stat.memberCount += (v.MemberEnd() - v.MemberBegin()); stat.stringCount += (v.MemberEnd() - v.MemberBegin()); break; case kArrayType: for (Value::ConstValueIterator i = v.Begin(); i != v.End(); ++i) genStat(stat, *i); stat.arrayCount++; stat.elementCount += v.Size(); break; case kStringType: stat.stringCount++; stat.stringLength += v.GetStringLength(); break; case kNumberType: stat.numberCount++; break; } } static const char *name() { return "rapid normal"; } }; struct RapidInsitu : Rapid { std::vector<char> source; bool parse(const std::vector<char> &buffer) { source = buffer; doc.ParseInsitu(source.data()); return doc.HasParseError(); } static const char *name() { return "rapid insitu"; } }; struct Gason { std::vector<char> source; JsonAllocator allocator; JsonValue value; char *endptr; int result; bool parse(const std::vector<char> &buffer) { source = buffer; return (result = jsonParse(source.data(), &endptr, &value, allocator)) == JSON_OK; } const char *strError() { return jsonStrError(result); } void update(Stat &stat) { genStat(stat, value); } static void genStat(Stat &stat, JsonValue v) { switch (v.getTag()) { case JSON_ARRAY: for (auto i : v) { genStat(stat, i->value); stat.elementCount++; } stat.arrayCount++; break; case JSON_OBJECT: for (auto i : v) { genStat(stat, i->value); stat.memberCount++; stat.stringLength += strlen(i->key); stat.stringCount++; } stat.objectCount++; break; case JSON_STRING: stat.stringCount++; stat.stringLength += strlen(v.toString()); break; case JSON_NUMBER: stat.numberCount++; break; case JSON_TRUE: stat.trueCount++; break; case JSON_FALSE: stat.falseCount++; break; case JSON_NULL: stat.nullCount++; break; } } static const char *name() { return "gason"; } }; template <typename T> static Stat run(size_t iterations, const std::vector<char> &buffer) { Stat stat; memset(&stat, 0, sizeof(stat)); stat.parserName = T::name(); stat.sourceSize = buffer.size() * iterations; std::vector<T> docs(iterations); auto t = nanotime(); for (auto &i : docs) { i.parse(buffer); } stat.parseTime += nanotime() - t; t = nanotime(); for (auto &i : docs) i.update(stat); stat.updateTime += nanotime() - t; return stat; } static void print(const Stat &stat) { printf("%8zd %8zd %8zd %8zd %8zd %8zd %8zd %8zd %8zd %8zd %8zd %11.2f %11.2f %11.2f %s\n", stat.objectCount, stat.arrayCount, stat.numberCount, stat.stringCount, stat.trueCount, stat.falseCount, stat.nullCount, stat.memberCount, stat.elementCount, stat.stringLength, stat.sourceSize, stat.updateTime / 1e6, stat.parseTime / 1e6, stat.sourceSize / (stat.parseTime / 1e9) / (1 << 20), stat.parserName); } #if defined(__clang__) #define COMPILER "Clang " __clang_version__ #elif defined(__GNUC__) #define COMPILER "GCC " __VERSION__ #endif #ifndef __x86_64__ #define __x86_64__ 0 #endif #ifndef NDEBUG #define NDEBUG 0 #endif int main(int argc, const char **argv) { printf("gason benchmark, %s, x86_64 %d, SIZEOF_POINTER %d, NDEBUG %d\n", COMPILER, __x86_64__, __SIZEOF_POINTER__, NDEBUG); size_t iterations = 10; for (int i = 1; i < argc; ++i) { if (!strcmp("-n", argv[i])) { iterations = strtol(argv[++i], NULL, 0); continue; } FILE *fp = fopen(argv[i], "r"); if (!fp) { perror(argv[i]); exit(EXIT_FAILURE); } fseek(fp, 0, SEEK_END); size_t size = ftell(fp); fseek(fp, 0, SEEK_SET); std::vector<char> buffer; buffer.resize(size + 1); fread(buffer.data(), 1, size, fp); fclose(fp); putchar('\n'); printf("%s, %zdB x %zd:\n", argv[i], size, iterations); printf("%8s %8s %8s %8s %8s %8s %8s %8s %8s %8s %8s %11s %11s %11s\n", "Object", "Array", "Number", "String", "True", "False", "Null", "Member", "Element", "StrLen", "Size", "Update(ms)", "Parse(ms)", "Speed(Mb/s)"); print(run<Rapid>(iterations, buffer)); print(run<RapidInsitu>(iterations, buffer)); print(run<Gason>(iterations, buffer)); } return 0; } <|endoftext|>
<commit_before>#include <nan.h> #include <openssl/bio.h> #include <openssl/buffer.h> #include <openssl/crypto.h> #include <openssl/pem.h> #include <openssl/rsa.h> #include <openssl/x509.h> NAN_METHOD(extractPublic) { const auto sourceString = info[0]->ToString(); if (!sourceString->IsOneByte()) { Nan::ThrowError("Malformed character found"); return; } size_t sourceLength = sourceString->Length(); const auto sourceBuf = new char[sourceLength]; Nan::DecodeWrite(sourceBuf, sourceLength, sourceString); const auto source = BIO_new_mem_buf(sourceBuf, sourceLength); if (source == nullptr) { Nan::ThrowError("Memory allocation failed"); delete[] sourceBuf; return; } const auto rsa = PEM_read_bio_RSAPrivateKey(source, nullptr, nullptr, nullptr); BIO_free(source); delete[] sourceBuf; if (rsa == nullptr) { Nan::ThrowError("Decode failed"); return; } const auto destination = BIO_new(BIO_s_mem()); if (destination == nullptr) { Nan::ThrowError("Memory allocation failed"); return; } const auto result = PEM_write_bio_RSAPublicKey(destination, rsa); RSA_free(rsa); if (result != 1) { Nan::ThrowError("Public key extraction failed"); BIO_free(destination); return; } char *pem; const auto pemLength = BIO_get_mem_data(destination, &pem); info.GetReturnValue().Set(Nan::Encode(pem, pemLength)); BIO_free(destination); } NAN_METHOD(generate) { const auto exponent = BN_new(); const auto mem = BIO_new(BIO_s_mem()); const auto rsa = RSA_new(); char *data; long result; if (exponent == nullptr || mem == nullptr || rsa == nullptr) { Nan::ThrowError("Memory allocation failed"); goto done; } result = BN_set_word(exponent, 65537); if (result != 1) { Nan::ThrowError("Exponent setting failed"); goto done; } result = RSA_generate_key_ex(rsa, 2048, exponent, nullptr); if (result != 1) { Nan::ThrowError("Key generation failed"); goto done; } result = PEM_write_bio_RSAPrivateKey(mem, rsa, NULL, NULL, 0, NULL, NULL); if (result != 1) { Nan::ThrowError("Key export failed"); goto done; } result = BIO_get_mem_data(mem, &data); info.GetReturnValue().Set(Nan::Encode(data, result)); done: RSA_free(rsa); BIO_free(mem); BN_free(exponent); } NAN_MODULE_INIT(InitAll) { Nan::Set(target, Nan::New<v8::String>("extractPublic").ToLocalChecked(), Nan::GetFunction(Nan::New<v8::FunctionTemplate>(extractPublic)).ToLocalChecked()); Nan::Set(target, Nan::New<v8::String>("generate").ToLocalChecked(), Nan::GetFunction(Nan::New<v8::FunctionTemplate>(generate)).ToLocalChecked()); } NODE_MODULE(crypto_key, InitAll); <commit_msg>node-gypの警告を直す (#3906)<commit_after>#include <nan.h> #include <openssl/bio.h> #include <openssl/buffer.h> #include <openssl/crypto.h> #include <openssl/pem.h> #include <openssl/rsa.h> #include <openssl/x509.h> NAN_METHOD(extractPublic) { const auto sourceString = info[0]->ToString(Nan::GetCurrentContext()).ToLocalChecked(); if (!sourceString->IsOneByte()) { Nan::ThrowError("Malformed character found"); return; } size_t sourceLength = sourceString->Length(); const auto sourceBuf = new char[sourceLength]; Nan::DecodeWrite(sourceBuf, sourceLength, sourceString); const auto source = BIO_new_mem_buf(sourceBuf, sourceLength); if (source == nullptr) { Nan::ThrowError("Memory allocation failed"); delete[] sourceBuf; return; } const auto rsa = PEM_read_bio_RSAPrivateKey(source, nullptr, nullptr, nullptr); BIO_free(source); delete[] sourceBuf; if (rsa == nullptr) { Nan::ThrowError("Decode failed"); return; } const auto destination = BIO_new(BIO_s_mem()); if (destination == nullptr) { Nan::ThrowError("Memory allocation failed"); return; } const auto result = PEM_write_bio_RSAPublicKey(destination, rsa); RSA_free(rsa); if (result != 1) { Nan::ThrowError("Public key extraction failed"); BIO_free(destination); return; } char *pem; const auto pemLength = BIO_get_mem_data(destination, &pem); info.GetReturnValue().Set(Nan::Encode(pem, pemLength)); BIO_free(destination); } NAN_METHOD(generate) { const auto exponent = BN_new(); const auto mem = BIO_new(BIO_s_mem()); const auto rsa = RSA_new(); char *data; long result; if (exponent == nullptr || mem == nullptr || rsa == nullptr) { Nan::ThrowError("Memory allocation failed"); goto done; } result = BN_set_word(exponent, 65537); if (result != 1) { Nan::ThrowError("Exponent setting failed"); goto done; } result = RSA_generate_key_ex(rsa, 2048, exponent, nullptr); if (result != 1) { Nan::ThrowError("Key generation failed"); goto done; } result = PEM_write_bio_RSAPrivateKey(mem, rsa, NULL, NULL, 0, NULL, NULL); if (result != 1) { Nan::ThrowError("Key export failed"); goto done; } result = BIO_get_mem_data(mem, &data); info.GetReturnValue().Set(Nan::Encode(data, result)); done: RSA_free(rsa); BIO_free(mem); BN_free(exponent); } NAN_MODULE_INIT(InitAll) { Nan::Set(target, Nan::New<v8::String>("extractPublic").ToLocalChecked(), Nan::GetFunction(Nan::New<v8::FunctionTemplate>(extractPublic)).ToLocalChecked()); Nan::Set(target, Nan::New<v8::String>("generate").ToLocalChecked(), Nan::GetFunction(Nan::New<v8::FunctionTemplate>(generate)).ToLocalChecked()); } NODE_MODULE(crypto_key, InitAll); <|endoftext|>
<commit_before>void AliITSMerge(Int_t Nfiles=1,const char* file0="galice.root", const char* file1="galice_bg.root"){ // TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject(file0); if (file) {file->Close(); delete file;} cout << "AliITSMerge" << endl; file = new TFile(file0,"UPDATE"); if (!file->IsOpen()) { cerr<<"Can't open "<<file0<<" !" << endl; return; } // end if !file file->ls(); // Get AliRun object from file or return if not on file if (gAlice) delete gAlice; gAlice = (AliRun*)file->Get("gAlice"); if (!gAlice) { cerr << "AliITSMerge.C : AliRun object not found on file" << endl; return; } // end if !gAlice if(Nfiles>2) Nfiles = 2; if(Nfiles<1) Nfiles = 1; AliRunDigitizer *manager = new AliRunDigitizer(Nfiles,1); manager->SetInputStream(0,file0); if(Nfiles>1) manager->SetInputStream(1,file1); manager->SetOutputFile(file0); AliITSDigitizer *dITS = new AliITSDigitizer(manager); manager->Exec(""); } <commit_msg>Reworked to work for the ITS only. Based on Jiri's MergeV1.C<commit_after>//////////////////////////////////////////////////////////////////////// // // name: AliITSMerge // date: 11.4.2002 // last update: 11.4.2002 // Updated 5/6/02 // author: Jiri Chudoba // update by Bjorn Nilsen // version: 1.1 // // description: // creates digits from sdigits for several detectors // stores sdigits in separate file (or in the source file // with sdigits). Stores gAlice object and copies TE to the // file with digits // ITS region of Interest is set // test // // input: // TString fileNameSDigits ... input file with sdigits // TString fileNameDigits ... output file with digits // Int_t nEvents ... how many events to process // Int_t ITS, many flags for diff. detectors // // History: // // 04.04.02 - first version // //////////////////////////////////////////////////////////////////////// #if !defined(__CINT__) || defined(__MAKECINT__) #include "iostream.h" #include "TDatetime.h" #include "STEER/AliRun.h" #include "STEER/AliRunDigitizer.h" #include "ITS/AliITSDigitizer.h" #include "ITS/AliITS.h" #include "ITS/AliITSDetType.h" #include "ITS/AliITSresponseSDD.h" #include "TStopwatch.h" #endif // #include "AliHits2SDigits.C" Int_t AliITSMerge(TString fileNameDigits="digits.root", TString fileNameSDigitsSig="sig.sdigits.root", TString fileNameSDigitsBgr="bgr.sdigits.root", Int_t nEvents = 1, Int_t iITS = 2){ // delete the current gAlice object, the one from input file // will be used if(gAlice){ delete gAlice; gAlice = 0; } // end if gAlice // Connect the Root Galice file containing Geometry, Kine and Hits TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject(fileNameSDigitsSig.Data()); if(!file) file = new TFile(fileNameSDigitsSig.Data()); TDatime *ct0 = new TDatime(2002,04,26,00,00,00), ct = file->GetCreationDate(); // Get AliRun object from file or create it if not on file if(!gAlice) { gAlice = (AliRun*)file->Get("gAlice"); if(gAlice) printf("AliRun object found on file\n"); if(!gAlice) gAlice = new AliRun("gAlice","Alice test program"); } // end if !gAlice AliRunDigitizer * manager = new AliRunDigitizer(2,1); manager->SetInputStream(0,fileNameSDigitsSig.Data()); manager->SetInputStream(1,fileNameSDigitsBgr.Data()); if (fileNameDigits != "") { manager->SetOutputFile(fileNameDigits); } manager->SetNrOfEventsToWrite(nEvents); if (iITS) { AliITSDigitizer *dITS = new AliITSDigitizer(manager); if (iITS == 2) dITS->SetByRegionOfInterestFlag(1); // For old files, must change SDD noise. // and for new file we will do it anyway for simplicity. AliITS *ITS = (AliITS*) gAlice->GetDetector("ITS"); AliITSresponseSDD *resp1 = ITS->DetType(1)->GetResponseModel(); resp1->SetNoiseParam(); resp1->SetNoiseAfterElectronics(); Float_t n,b; Int_t cPar[8]; resp1->GetNoiseParam(n,b); n = resp1->GetNoiseAfterElectronics(); cPar[0]=0; cPar[1]=0; cPar[2]=(Int_t)(b + 2.*n + 0.5); cPar[3]=(Int_t)(b + 2.*n + 0.5); cPar[4]=0; cPar[5]=0; cPar[6]=0; cPar[7]=0; resp1->SetCompressParam(cPar); } TStopwatch timer; timer.Start(); manager->Exec("deb all"); timer.Stop(); timer.Print(); // gAlice may need to be deleted but not if as part of larger production. delete manager; } <|endoftext|>
<commit_before>#include "test.h" #include "lcg.h" #include <cassert> #include <limits> #include <algorithm> #include <cmath> template <class T> void boxmuller(T* data, size_t count) { assert(count % 2 == 0); static const T twopi = T(2.0 * 3.14159265358979323846); LCG<T> r; for (size_t i = 0; i < count; i += 2) { T u1, u2; u1 = r(); u2 = r(); u1 = std::max(u1, std::numeric_limits<T>::min()); T radius = std::sqrt(-2 * std::log(u1)); T theta = twopi * u2; data[i ] = radius * std::cos(theta); data[i + 1] = radius * std::sin(theta); } } static void normaldistf_boxmuller(float* data, size_t count) { boxmuller(data, count); } static void normaldist_boxmuller(double* data, size_t count) { boxmuller(data, count); } REGISTER_TEST(boxmuller); <commit_msg>Prevent conditional in Box-Muller<commit_after>#include "test.h" #include "lcg.h" #include <cassert> #include <cmath> template <class T> void boxmuller(T* data, size_t count) { assert(count % 2 == 0); static const T twopi = T(2.0 * 3.14159265358979323846); LCG<T> r; for (size_t i = 0; i < count; i += 2) { T u1, u2; u1 = 1.0f - r(); // [0, 1) -> (0, 1] u2 = r(); T radius = std::sqrt(-2 * std::log(u1)); T theta = twopi * u2; data[i ] = radius * std::cos(theta); data[i + 1] = radius * std::sin(theta); } } static void normaldistf_boxmuller(float* data, size_t count) { boxmuller(data, count); } static void normaldist_boxmuller(double* data, size_t count) { boxmuller(data, count); } REGISTER_TEST(boxmuller); <|endoftext|>
<commit_before>/** * @file sqlite.cpp * @brief SQLite DB access layer * * (c) 2013-2014 by Mega Limited, Auckland, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include "mega.h" #ifdef USE_SQLITE namespace mega { SqliteDbAccess::SqliteDbAccess(const LocalPath& rootPath) : mRootPath(rootPath) { } SqliteDbAccess::~SqliteDbAccess() { } LocalPath SqliteDbAccess::databasePath(const FileSystemAccess& fsAccess, const string& name, const int version) const { ostringstream osstream; osstream << "megaclient_statecache" << version << "_" << name << ".db"; LocalPath path = mRootPath; path.appendWithSeparator( LocalPath::fromPath(osstream.str(), fsAccess), false); return path; } SqliteDbTable* SqliteDbAccess::open(PrnGen &rng, FileSystemAccess& fsAccess, const string& name, const int flags) { auto dbPath = databasePath(fsAccess, name, DB_VERSION); auto upgraded = true; { auto legacyPath = databasePath(fsAccess, name, LEGACY_DB_VERSION); auto fileAccess = fsAccess.newfileaccess(); if (fileAccess->fopen(legacyPath)) { LOG_debug << "Found legacy database at: " << legacyPath.toPath(fsAccess); if (currentDbVersion == LEGACY_DB_VERSION) { LOG_debug << "Using a legacy database."; dbPath = std::move(legacyPath); upgraded = false; } else if ((flags & DB_OPEN_FLAG_RECYCLE)) { LOG_debug << "Trying to recycle a legacy database."; if (fsAccess.renamelocal(legacyPath, dbPath, false)) { auto suffix = LocalPath::fromPath("-shm", fsAccess); auto from = legacyPath + suffix; auto to = dbPath + suffix; fsAccess.renamelocal(from, to); suffix = LocalPath::fromPath("-wal", fsAccess); from = legacyPath + suffix; to = dbPath + suffix; fsAccess.renamelocal(from, to); LOG_debug << "Legacy database recycled."; } else { LOG_debug << "Unable to recycle database, deleting..."; fsAccess.unlinklocal(legacyPath); } } else { LOG_debug << "Deleting outdated legacy database."; fsAccess.unlinklocal(legacyPath); } } } if (upgraded) { LOG_debug << "Using an upgraded DB: " << dbPath.toPath(fsAccess); currentDbVersion = DB_VERSION; } const string dbPathStr = dbPath.toPath(fsAccess); sqlite3* db; int result = sqlite3_open(dbPathStr.c_str(), &db); if (result) { if (db) { sqlite3_close(db); } return nullptr; } #if !(TARGET_OS_IPHONE) result = sqlite3_exec(db, "PRAGMA journal_mode=WAL;", nullptr, nullptr, nullptr); if (result) { sqlite3_close(db); return nullptr; } #endif /* ! TARGET_OS_IPHONE */ const char* sql = "CREATE TABLE IF NOT EXISTS statecache ( " " id INTEGER PRIMARY KEY ASC NOT NULL, " " content BLOB NOT NULL " ");"; result = sqlite3_exec(db, sql, nullptr, nullptr, nullptr); if (result) { sqlite3_close(db); return nullptr; } const char* tableVar = "CREATE TABLE IF NOT EXISTS vars(name text PRIMARY KEY NOT NULL, value BLOB)"; result = sqlite3_exec(db, tableVar, nullptr, nullptr, nullptr); if (result) { sqlite3_close(db); return nullptr; } return new SqliteDbTable(rng, db, fsAccess, dbPathStr, (flags & DB_OPEN_FLAG_TRANSACTED) > 0); } bool SqliteDbAccess::probe(FileSystemAccess& fsAccess, const string& name) const { auto fileAccess = fsAccess.newfileaccess(); LocalPath dbPath = databasePath(fsAccess, name, DB_VERSION); if (fileAccess->isfile(dbPath)) { return true; } dbPath = databasePath(fsAccess, name, LEGACY_DB_VERSION); return fileAccess->isfile(dbPath); } const LocalPath& SqliteDbAccess::rootPath() const { return mRootPath; } SqliteDbTable::SqliteDbTable(PrnGen &rng, sqlite3* db, FileSystemAccess &fsAccess, const string &path, const bool checkAlwaysTransacted) : DbTable(rng, checkAlwaysTransacted) , db(db) , pStmt(nullptr) , dbfile(path) , fsaccess(&fsAccess) { } SqliteDbTable::~SqliteDbTable() { resetCommitter(); if (!db) { return; } sqlite3_finalize(pStmt); if (inTransaction()) { abort(); } sqlite3_close(db); LOG_debug << "Database closed " << dbfile; } bool SqliteDbTable::inTransaction() const { return sqlite3_get_autocommit(db) == 0; } LocalPath SqliteDbTable::dbFile() const { return LocalPath::fromPath(dbfile, *fsaccess); } // set cursor to first record void SqliteDbTable::rewind() { if (!db) { return; } int result; if (pStmt) { result = sqlite3_reset(pStmt); } else { result = sqlite3_prepare(db, "SELECT id, content FROM statecache", -1, &pStmt, NULL); } if (result != SQLITE_OK) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(result)); LOG_err << "Unable to rewind database: " << dbfile << err; assert(!"Unable to rewind database."); } } // retrieve next record through cursor bool SqliteDbTable::next(uint32_t* index, string* data) { if (!db) { return false; } if (!pStmt) { return false; } int rc = sqlite3_step(pStmt); if (rc != SQLITE_ROW) { sqlite3_finalize(pStmt); pStmt = NULL; if (rc != SQLITE_DONE) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc)); LOG_err << "Unable to get next record from database: " << dbfile << err; assert(!"Unable to get next record from database."); } return false; } *index = sqlite3_column_int(pStmt, 0); data->assign((char*)sqlite3_column_blob(pStmt, 1), sqlite3_column_bytes(pStmt, 1)); return true; } // retrieve record by index bool SqliteDbTable::get(uint32_t index, string* data) { if (!db) { return false; } checkTransaction(); sqlite3_stmt *stmt; int rc; rc = sqlite3_prepare(db, "SELECT content FROM statecache WHERE id = ?", -1, &stmt, NULL); if (rc == SQLITE_OK) { rc = sqlite3_bind_int(stmt, 1, index); if (rc == SQLITE_OK) { rc = sqlite3_step(stmt); if (rc == SQLITE_ROW) { data->assign((char*)sqlite3_column_blob(stmt, 0), sqlite3_column_bytes(stmt, 0)); } } } sqlite3_finalize(stmt); if (rc != SQLITE_DONE && rc != SQLITE_ROW) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc)); LOG_err << "Unable to get record from database: " << dbfile << err; assert(!"Unable to get record from database."); } return rc == SQLITE_ROW; } // add/update record by index bool SqliteDbTable::put(uint32_t index, char* data, unsigned len) { if (!db) { return false; } checkTransaction(); sqlite3_stmt *stmt; bool result = false; int rc = sqlite3_prepare(db, "INSERT OR REPLACE INTO statecache (id, content) VALUES (?, ?)", -1, &stmt, NULL); if (rc == SQLITE_OK) { rc = sqlite3_bind_int(stmt, 1, index); if (rc == SQLITE_OK) { rc = sqlite3_bind_blob(stmt, 2, data, len, SQLITE_STATIC); if (rc == SQLITE_OK) { rc = sqlite3_step(stmt); if (rc == SQLITE_DONE) { result = true; } } } } sqlite3_finalize(stmt); if (!result) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc)); LOG_err << "Unable to put record into database: " << dbfile << err; assert(!"Unable to put record into database."); } return result; } // delete record by index bool SqliteDbTable::del(uint32_t index) { if (!db) { return false; } checkTransaction(); char buf[64]; sprintf(buf, "DELETE FROM statecache WHERE id = %" PRIu32, index); int rc = sqlite3_exec(db, buf, 0, 0, nullptr); if (rc != SQLITE_OK) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc)); LOG_err << "Unable to delete record from database: " << dbfile << err; assert(!"Unable to delete record from database."); return false; } return true; } // truncate table void SqliteDbTable::truncate() { if (!db) { return; } checkTransaction(); int rc = sqlite3_exec(db, "DELETE FROM statecache", 0, 0, NULL); if (rc != API_OK) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc)); LOG_err << "Unable to truncate database: " << dbfile << err; assert(!"Unable to truncate database."); } } // begin transaction void SqliteDbTable::begin() { if (!db) { return; } LOG_debug << "DB transaction BEGIN " << dbfile; int rc = sqlite3_exec(db, "BEGIN", 0, 0, NULL); if (rc != SQLITE_OK) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc)); LOG_err << "Unable to begin transaction on database: " << dbfile << err; assert(!"Unable to begin transaction on database."); } } // commit transaction void SqliteDbTable::commit() { if (!db) { return; } LOG_debug << "DB transaction COMMIT " << dbfile; int rc = sqlite3_exec(db, "COMMIT", 0, 0, NULL); if (rc != SQLITE_OK) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc)); LOG_err << "Unable to commit transaction on database: " << dbfile << err; assert(!"Unable to commit transaction on database."); } } // abort transaction void SqliteDbTable::abort() { if (!db) { return; } LOG_debug << "DB transaction ROLLBACK " << dbfile; int rc = sqlite3_exec(db, "ROLLBACK", 0, 0, NULL); if (rc != SQLITE_OK) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc)); LOG_err << "Unable to rollback transaction on database: " << dbfile << err; assert(!"Unable to rollback transaction on database."); } } void SqliteDbTable::remove() { if (!db) { return; } sqlite3_finalize(pStmt); if (inTransaction()) { abort(); } sqlite3_close(db); db = NULL; auto localpath = LocalPath::fromPath(dbfile, *fsaccess); fsaccess->unlinklocal(localpath); } int SqliteDbTable::readSessionType() { std::string sessionType = getVar(MegaClient::SESSIONTYPE); return (sessionType != "") ? atoi(sessionType.c_str()) : -1; } std::string SqliteDbTable::getVar(const std::string& name) { if (!db) { return ""; } std::string value; checkTransaction(); sqlite3_stmt *stmt; if (sqlite3_prepare(db, "SELECT value FROM vars WHERE name = ?", -1, &stmt, NULL) == SQLITE_OK) { if (sqlite3_bind_text(stmt, 1, name.c_str(), name.length(), SQLITE_STATIC) == SQLITE_OK) { if((sqlite3_step(stmt) == SQLITE_ROW)) { const void* data = sqlite3_column_blob(stmt, 0); int size = sqlite3_column_bytes(stmt, 0); if (data && size) { value.assign(static_cast<const char*>(data), size); } } } } sqlite3_finalize(stmt); return value; } bool SqliteDbTable::setVar(const std::string& name, const std::string& value) { if (!db) { return false; } checkTransaction(); sqlite3_stmt *stmt; bool result = false; if (sqlite3_prepare(db, "INSERT OR REPLACE INTO vars (name, value) VALUES (?, ?)", -1, &stmt, NULL) == SQLITE_OK) { if (sqlite3_bind_text(stmt, 1, name.c_str(), name.length(), SQLITE_STATIC) == SQLITE_OK) { if (sqlite3_bind_blob(stmt, 2, value.data(), value.size(), SQLITE_STATIC) == SQLITE_OK) { if (sqlite3_step(stmt) == SQLITE_DONE) { result = true; } } } } sqlite3_finalize(stmt); return result; } } // namespace #endif <commit_msg>Fix warnings at compilation<commit_after>/** * @file sqlite.cpp * @brief SQLite DB access layer * * (c) 2013-2014 by Mega Limited, Auckland, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include "mega.h" #ifdef USE_SQLITE namespace mega { SqliteDbAccess::SqliteDbAccess(const LocalPath& rootPath) : mRootPath(rootPath) { } SqliteDbAccess::~SqliteDbAccess() { } LocalPath SqliteDbAccess::databasePath(const FileSystemAccess& fsAccess, const string& name, const int version) const { ostringstream osstream; osstream << "megaclient_statecache" << version << "_" << name << ".db"; LocalPath path = mRootPath; path.appendWithSeparator( LocalPath::fromPath(osstream.str(), fsAccess), false); return path; } SqliteDbTable* SqliteDbAccess::open(PrnGen &rng, FileSystemAccess& fsAccess, const string& name, const int flags) { auto dbPath = databasePath(fsAccess, name, DB_VERSION); auto upgraded = true; { auto legacyPath = databasePath(fsAccess, name, LEGACY_DB_VERSION); auto fileAccess = fsAccess.newfileaccess(); if (fileAccess->fopen(legacyPath)) { LOG_debug << "Found legacy database at: " << legacyPath.toPath(fsAccess); if (currentDbVersion == LEGACY_DB_VERSION) { LOG_debug << "Using a legacy database."; dbPath = std::move(legacyPath); upgraded = false; } else if ((flags & DB_OPEN_FLAG_RECYCLE)) { LOG_debug << "Trying to recycle a legacy database."; if (fsAccess.renamelocal(legacyPath, dbPath, false)) { auto suffix = LocalPath::fromPath("-shm", fsAccess); auto from = legacyPath + suffix; auto to = dbPath + suffix; fsAccess.renamelocal(from, to); suffix = LocalPath::fromPath("-wal", fsAccess); from = legacyPath + suffix; to = dbPath + suffix; fsAccess.renamelocal(from, to); LOG_debug << "Legacy database recycled."; } else { LOG_debug << "Unable to recycle database, deleting..."; fsAccess.unlinklocal(legacyPath); } } else { LOG_debug << "Deleting outdated legacy database."; fsAccess.unlinklocal(legacyPath); } } } if (upgraded) { LOG_debug << "Using an upgraded DB: " << dbPath.toPath(fsAccess); currentDbVersion = DB_VERSION; } const string dbPathStr = dbPath.toPath(fsAccess); sqlite3* db; int result = sqlite3_open(dbPathStr.c_str(), &db); if (result) { if (db) { sqlite3_close(db); } return nullptr; } #if !(TARGET_OS_IPHONE) result = sqlite3_exec(db, "PRAGMA journal_mode=WAL;", nullptr, nullptr, nullptr); if (result) { sqlite3_close(db); return nullptr; } #endif /* ! TARGET_OS_IPHONE */ const char* sql = "CREATE TABLE IF NOT EXISTS statecache ( " " id INTEGER PRIMARY KEY ASC NOT NULL, " " content BLOB NOT NULL " ");"; result = sqlite3_exec(db, sql, nullptr, nullptr, nullptr); if (result) { sqlite3_close(db); return nullptr; } const char* tableVar = "CREATE TABLE IF NOT EXISTS vars(name text PRIMARY KEY NOT NULL, value BLOB)"; result = sqlite3_exec(db, tableVar, nullptr, nullptr, nullptr); if (result) { sqlite3_close(db); return nullptr; } return new SqliteDbTable(rng, db, fsAccess, dbPathStr, (flags & DB_OPEN_FLAG_TRANSACTED) > 0); } bool SqliteDbAccess::probe(FileSystemAccess& fsAccess, const string& name) const { auto fileAccess = fsAccess.newfileaccess(); LocalPath dbPath = databasePath(fsAccess, name, DB_VERSION); if (fileAccess->isfile(dbPath)) { return true; } dbPath = databasePath(fsAccess, name, LEGACY_DB_VERSION); return fileAccess->isfile(dbPath); } const LocalPath& SqliteDbAccess::rootPath() const { return mRootPath; } SqliteDbTable::SqliteDbTable(PrnGen &rng, sqlite3* db, FileSystemAccess &fsAccess, const string &path, const bool checkAlwaysTransacted) : DbTable(rng, checkAlwaysTransacted) , db(db) , pStmt(nullptr) , dbfile(path) , fsaccess(&fsAccess) { } SqliteDbTable::~SqliteDbTable() { resetCommitter(); if (!db) { return; } sqlite3_finalize(pStmt); if (inTransaction()) { abort(); } sqlite3_close(db); LOG_debug << "Database closed " << dbfile; } bool SqliteDbTable::inTransaction() const { return sqlite3_get_autocommit(db) == 0; } LocalPath SqliteDbTable::dbFile() const { return LocalPath::fromPath(dbfile, *fsaccess); } // set cursor to first record void SqliteDbTable::rewind() { if (!db) { return; } int result; if (pStmt) { result = sqlite3_reset(pStmt); } else { result = sqlite3_prepare(db, "SELECT id, content FROM statecache", -1, &pStmt, NULL); } if (result != SQLITE_OK) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(result)); LOG_err << "Unable to rewind database: " << dbfile << err; assert(!"Unable to rewind database."); } } // retrieve next record through cursor bool SqliteDbTable::next(uint32_t* index, string* data) { if (!db) { return false; } if (!pStmt) { return false; } int rc = sqlite3_step(pStmt); if (rc != SQLITE_ROW) { sqlite3_finalize(pStmt); pStmt = NULL; if (rc != SQLITE_DONE) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc)); LOG_err << "Unable to get next record from database: " << dbfile << err; assert(!"Unable to get next record from database."); } return false; } *index = sqlite3_column_int(pStmt, 0); data->assign((char*)sqlite3_column_blob(pStmt, 1), sqlite3_column_bytes(pStmt, 1)); return true; } // retrieve record by index bool SqliteDbTable::get(uint32_t index, string* data) { if (!db) { return false; } checkTransaction(); sqlite3_stmt *stmt; int rc; rc = sqlite3_prepare(db, "SELECT content FROM statecache WHERE id = ?", -1, &stmt, NULL); if (rc == SQLITE_OK) { rc = sqlite3_bind_int(stmt, 1, index); if (rc == SQLITE_OK) { rc = sqlite3_step(stmt); if (rc == SQLITE_ROW) { data->assign((char*)sqlite3_column_blob(stmt, 0), sqlite3_column_bytes(stmt, 0)); } } } sqlite3_finalize(stmt); if (rc != SQLITE_DONE && rc != SQLITE_ROW) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc)); LOG_err << "Unable to get record from database: " << dbfile << err; assert(!"Unable to get record from database."); } return rc == SQLITE_ROW; } // add/update record by index bool SqliteDbTable::put(uint32_t index, char* data, unsigned len) { if (!db) { return false; } checkTransaction(); sqlite3_stmt *stmt; bool result = false; int rc = sqlite3_prepare(db, "INSERT OR REPLACE INTO statecache (id, content) VALUES (?, ?)", -1, &stmt, NULL); if (rc == SQLITE_OK) { rc = sqlite3_bind_int(stmt, 1, index); if (rc == SQLITE_OK) { rc = sqlite3_bind_blob(stmt, 2, data, len, SQLITE_STATIC); if (rc == SQLITE_OK) { rc = sqlite3_step(stmt); if (rc == SQLITE_DONE) { result = true; } } } } sqlite3_finalize(stmt); if (!result) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc)); LOG_err << "Unable to put record into database: " << dbfile << err; assert(!"Unable to put record into database."); } return result; } // delete record by index bool SqliteDbTable::del(uint32_t index) { if (!db) { return false; } checkTransaction(); char buf[64]; sprintf(buf, "DELETE FROM statecache WHERE id = %" PRIu32, index); int rc = sqlite3_exec(db, buf, 0, 0, nullptr); if (rc != SQLITE_OK) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc)); LOG_err << "Unable to delete record from database: " << dbfile << err; assert(!"Unable to delete record from database."); return false; } return true; } // truncate table void SqliteDbTable::truncate() { if (!db) { return; } checkTransaction(); int rc = sqlite3_exec(db, "DELETE FROM statecache", 0, 0, NULL); if (rc != API_OK) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc)); LOG_err << "Unable to truncate database: " << dbfile << err; assert(!"Unable to truncate database."); } } // begin transaction void SqliteDbTable::begin() { if (!db) { return; } LOG_debug << "DB transaction BEGIN " << dbfile; int rc = sqlite3_exec(db, "BEGIN", 0, 0, NULL); if (rc != SQLITE_OK) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc)); LOG_err << "Unable to begin transaction on database: " << dbfile << err; assert(!"Unable to begin transaction on database."); } } // commit transaction void SqliteDbTable::commit() { if (!db) { return; } LOG_debug << "DB transaction COMMIT " << dbfile; int rc = sqlite3_exec(db, "COMMIT", 0, 0, NULL); if (rc != SQLITE_OK) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc)); LOG_err << "Unable to commit transaction on database: " << dbfile << err; assert(!"Unable to commit transaction on database."); } } // abort transaction void SqliteDbTable::abort() { if (!db) { return; } LOG_debug << "DB transaction ROLLBACK " << dbfile; int rc = sqlite3_exec(db, "ROLLBACK", 0, 0, NULL); if (rc != SQLITE_OK) { string err = string(" Error: ") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc)); LOG_err << "Unable to rollback transaction on database: " << dbfile << err; assert(!"Unable to rollback transaction on database."); } } void SqliteDbTable::remove() { if (!db) { return; } sqlite3_finalize(pStmt); if (inTransaction()) { abort(); } sqlite3_close(db); db = NULL; auto localpath = LocalPath::fromPath(dbfile, *fsaccess); fsaccess->unlinklocal(localpath); } int SqliteDbTable::readSessionType() { std::string sessionType = getVar(MegaClient::SESSIONTYPE); return (sessionType != "") ? atoi(sessionType.c_str()) : -1; } std::string SqliteDbTable::getVar(const std::string& name) { if (!db) { return ""; } std::string value; checkTransaction(); sqlite3_stmt *stmt; if (sqlite3_prepare(db, "SELECT value FROM vars WHERE name = ?", -1, &stmt, NULL) == SQLITE_OK) { if (sqlite3_bind_text(stmt, 1, name.c_str(), static_cast<int>(name.length()), SQLITE_STATIC) == SQLITE_OK) { if((sqlite3_step(stmt) == SQLITE_ROW)) { const void* data = sqlite3_column_blob(stmt, 0); int size = sqlite3_column_bytes(stmt, 0); if (data && size) { value.assign(static_cast<const char*>(data), size); } } } } sqlite3_finalize(stmt); return value; } bool SqliteDbTable::setVar(const std::string& name, const std::string& value) { if (!db) { return false; } checkTransaction(); sqlite3_stmt *stmt; bool result = false; if (sqlite3_prepare(db, "INSERT OR REPLACE INTO vars (name, value) VALUES (?, ?)", -1, &stmt, NULL) == SQLITE_OK) { if (sqlite3_bind_text(stmt, 1, name.c_str(), static_cast<int>(name.length()), SQLITE_STATIC) == SQLITE_OK) { if (sqlite3_bind_blob(stmt, 2, value.data(), static_cast<int>(value.size()), SQLITE_STATIC) == SQLITE_OK) { if (sqlite3_step(stmt) == SQLITE_DONE) { result = true; } } } } sqlite3_finalize(stmt); return result; } } // namespace #endif <|endoftext|>
<commit_before>#pragma once #include <Eigen/Core> #include <string> #include <igl/readSTL.h> #include <igl/slice.h> #include <igl/slice_into.h> #include "stiffness_matrix_assembly.hpp" #include "load_vector_assembly.hpp" #include "dirichlet_boundary.hpp" typedef Eigen::VectorXd Vector; //----------------solveBegin---------------- //! Solve the FEM system. //! //! @param[out] u will at the end contain the FEM solution. //! @param[in] vertices list of triangle vertices for the mesh //! @param[in] triangles list of triangles (described by indices) //! @param[in] f the RHS f (as in the exercise) //! @param[in] g the boundary value (as in the exercise) //! @param[in] sigma the function sigma as in the exercise //! @param[in] r the parameter r from the lecture notes //! return number of degrees of freedom (without the boundary dofs) int solveFiniteElement(Vector& u, const Eigen::MatrixXd& vertices, const Eigen::MatrixXi& triangles, const std::function<double(double, double)>& f, const std::function<double(double, double)>& sigma, const std::function<double(double, double)>& g, double r) { SparseMatrix A; // (write your solution here) Vector F; // (write your solution here) u.resize(vertices.rows()); u.setZero(); Eigen::VectorXi interiorVertexIndices; // set Dirichlet Boundary conditions // (write your solution here) SparseMatrix AInterior; igl::slice(A, interiorVertexIndices, interiorVertexIndices, AInterior); Eigen::SimplicialLDLT<SparseMatrix> solver; Vector FInterior; igl::slice(F, interiorVertexIndices, FInterior); //initialize solver for AInterior // (write your solution here) //solve interior system // (write your solution here) return interiorVertexIndices.size(); } //----------------solveEnd---------------- <commit_msg>Solved series 2 problem 2i<commit_after>#pragma once #include <Eigen/Core> #include <string> #include <igl/readSTL.h> #include <igl/slice.h> #include <igl/slice_into.h> #include "stiffness_matrix_assembly.hpp" #include "load_vector_assembly.hpp" #include "dirichlet_boundary.hpp" typedef Eigen::VectorXd Vector; //----------------solveBegin---------------- //! Solve the FEM system. //! //! @param[out] u will at the end contain the FEM solution. //! @param[in] vertices list of triangle vertices for the mesh //! @param[in] triangles list of triangles (described by indices) //! @param[in] f the RHS f (as in the exercise) //! @param[in] g the boundary value (as in the exercise) //! @param[in] sigma the function sigma as in the exercise //! @param[in] r the parameter r from the lecture notes //! return number of degrees of freedom (without the boundary dofs) int solveFiniteElement(Vector& u, const Eigen::MatrixXd& vertices, const Eigen::MatrixXi& triangles, const std::function<double(double, double)>& f, const std::function<double(double, double)>& sigma, const std::function<double(double, double)>& g, double r) { SparseMatrix A; // (write your solution here) assembleStiffnessMatrix(A, vertices, triangles, sigma, r); Vector F; // (write your solution here) assembleLoadVector(F, vertices, triangles, f); u.resize(vertices.rows()); u.setZero(); Eigen::VectorXi interiorVertexIndices; // set Dirichlet Boundary conditions // (write your solution here) setDirichletBoundary(u, interiorVertexIndices, vertices, triangles, g); F -= A * u; SparseMatrix AInterior; igl::slice(A, interiorVertexIndices, interiorVertexIndices, AInterior); Eigen::SimplicialLDLT<SparseMatrix> solver; Vector FInterior; igl::slice(F, interiorVertexIndices, FInterior); //initialize solver for AInterior // (write your solution here) //// NPDE_START_TEMPLATE solver.compute(AInterior); if (solver.info() != Eigen::Success) { throw std::runtime_error("Could not decompose the matrix"); } //// NPDE_END_TEMPLATE //solve interior system // (write your solution here) //// NPDE_START_TEMPLATE Vector uInterior = solver.solve(FInterior); igl::slice_into(uInterior, interiorVertexIndices, u); //// NPDE_END_TEMPLATE return interiorVertexIndices.size(); } //----------------solveEnd---------------- <|endoftext|>
<commit_before>#include "WrapperGenerator.h" using namespace std; void WrapperGenerator::initOpToGenMap() { shared_ptr<TracingInnerWrapperGenerator> traceGen; shared_ptr<CachingIPCInnerWrapperGenerator> cachingIPCGen; shared_ptr<NonCachingIPCInnerWrapperGenerator> nonCachingIPCGen; traceGen = make_shared<TracingInnerWrapperGenerator>(operationMap); cachingIPCGen = make_shared<CachingIPCInnerWrapperGenerator>(); nonCachingIPCGen = make_shared<NonCachingIPCInnerWrapperGenerator>(); operationToGenerator = WrapperGenMap({{"MUTEX_LOCK", traceGen}, {"MUTEX_UNLOCK", traceGen}, {"CV_WAIT", traceGen}, {"CV_BROADCAST", traceGen}, {"CV_SIGNAL", traceGen}, {"QUEUE_ENQUEUE", traceGen}, {"QUEUE_DEQUEUE", traceGen}, {"MESSAGE_SEND", traceGen}, {"MESSAGE_RECEIVE", traceGen}, {"MKNOD", cachingIPCGen}, {"OPEN", cachingIPCGen}, {"PIPE", cachingIPCGen}, {"MSGGET", cachingIPCGen}, {"READ", nonCachingIPCGen}, {"WRITE", nonCachingIPCGen}, {"MSGRCV", nonCachingIPCGen}, {"MSGSND", nonCachingIPCGen}}); } WrapperGenerator::WrapperGenerator(shared_ptr<unordered_map<string, FunctionPrototype>> _prototypeMap, std::shared_ptr<std::unordered_map<std::string, std::string>> _operationMap, string pathPrefix): prototypeMap(_prototypeMap), operationMap(_operationMap) { initOpToGenMap(); headerFile.open(pathPrefix + "VProfEventWrappers.h"); implementationFile.open(pathPrefix + "VProfEventWrappers.cpp"); const string generatedFileMessage = " ///////////////////////////////////////////////////// \n" " // Note that this file was generated by VProfiler. // \n" " // Please do not change the contents of this file! // \n" " ///////////////////////////////////////////////////// \n\n"; headerFile << generatedFileMessage; implementationFile << generatedFileMessage; } vector<string> WrapperGenerator::getFilenames() { vector<string> result; for (auto kv : *prototypeMap) { result.push_back(kv.second.filename); } sort(result.begin(), result.end()); result.erase(unique(result.begin(), result.end()), result.end()); return result; } void WrapperGenerator::GenerateHeader() { vector<string> includeNames = getFilenames(); headerFile << "#ifndef VPROFEVENTWRAPPERS_H\n#define VPROFEVENTWRAPPERS_H\n"; for (string &includeName : includeNames) { headerFile << "#include \"" + includeName + "\"\n"; } headerFile << "#include \"trace_tool.h\"\n\n" "#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n"; for (auto kv : *prototypeMap) { headerFile << kv.second.functionPrototype + ";\n\n"; } headerFile << "#ifdef __cplusplus\n}\n#endif\n\n#endif"; headerFile.close(); } void WrapperGenerator::GenerateImplementations() { string operation; implementationFile << "#include \"VProfEventWrappers.h\"\n\n"; for (auto kv : *prototypeMap) { operation = (*operationMap)[kv.first]; implementationFile << kv.second.functionPrototype + " {\n\t"; if (kv.second.returnType != "void") { implementationFile << kv.second.returnType + " result;\n\t"; } operationToGenerator[operation]->GenerateWrapperPrologue(kv.first, kv.second); if (kv.second.returnType != "void") { implementationFile << "result = "; } implementationFile << kv.second.innerCallPrefix + "("; for (int i = 0, j = kv.second.paramVars.size(); i < j; i++) { implementationFile << kv.second.paramVars[i]; if (i != (j - 1)) { implementationFile << ", "; } } implementationFile <<");\n\t"; operationToGenerator[operation]->GenerateWrapperEpilogue(kv.first, kv.second); if (kv.second.returnType != "void") { implementationFile << "\treturn result;\n"; } implementationFile << "}\n\n"; } implementationFile.close(); } void WrapperGenerator::GenerateWrappers() { GenerateHeader(); GenerateImplementations(); } <commit_msg>Changed WrapperGenerator to use the correct constructors.<commit_after>#include "WrapperGenerator.h" using namespace std; void WrapperGenerator::initOpToGenMap() { shared_ptr<TracingInnerWrapperGenerator> traceGen; shared_ptr<CachingIPCInnerWrapperGenerator> cachingIPCGen; shared_ptr<NonCachingIPCInnerWrapperGenerator> nonCachingIPCGen; traceGen = make_shared<TracingInnerWrapperGenerator>(implementationFile, operationMap); cachingIPCGen = make_shared<CachingIPCInnerWrapperGenerator>(implementationFile); nonCachingIPCGen = make_shared<NonCachingIPCInnerWrapperGenerator>(implementationFile); operationToGenerator = WrapperGenMap({{"MUTEX_LOCK", traceGen}, {"MUTEX_UNLOCK", traceGen}, {"CV_WAIT", traceGen}, {"CV_BROADCAST", traceGen}, {"CV_SIGNAL", traceGen}, {"QUEUE_ENQUEUE", traceGen}, {"QUEUE_DEQUEUE", traceGen}, {"MESSAGE_SEND", traceGen}, {"MESSAGE_RECEIVE", traceGen}, {"MKNOD", cachingIPCGen}, {"OPEN", cachingIPCGen}, {"PIPE", cachingIPCGen}, {"MSGGET", cachingIPCGen}, {"READ", nonCachingIPCGen}, {"WRITE", nonCachingIPCGen}, {"MSGRCV", nonCachingIPCGen}, {"MSGSND", nonCachingIPCGen}}); } WrapperGenerator::WrapperGenerator(shared_ptr<unordered_map<string, FunctionPrototype>> _prototypeMap, std::shared_ptr<std::unordered_map<std::string, std::string>> _operationMap, string pathPrefix): prototypeMap(_prototypeMap), operationMap(_operationMap) { headerFile.open(pathPrefix + "VProfEventWrappers.h"); implementationFile.open(pathPrefix + "VProfEventWrappers.cpp"); initOpToGenMap(); const string generatedFileMessage = " ///////////////////////////////////////////////////// \n" " // Note that this file was generated by VProfiler. // \n" " // Please do not change the contents of this file! // \n" " ///////////////////////////////////////////////////// \n\n"; headerFile << generatedFileMessage; implementationFile << generatedFileMessage; } vector<string> WrapperGenerator::getFilenames() { vector<string> result; for (auto kv : *prototypeMap) { result.push_back(kv.second.filename); } sort(result.begin(), result.end()); result.erase(unique(result.begin(), result.end()), result.end()); return result; } void WrapperGenerator::GenerateHeader() { vector<string> includeNames = getFilenames(); headerFile << "#ifndef VPROFEVENTWRAPPERS_H\n#define VPROFEVENTWRAPPERS_H\n"; for (string &includeName : includeNames) { headerFile << "#include \"" + includeName + "\"\n"; } headerFile << "#include \"trace_tool.h\"\n\n" "#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n"; for (auto kv : *prototypeMap) { headerFile << kv.second.functionPrototype + ";\n\n"; } headerFile << "#ifdef __cplusplus\n}\n#endif\n\n#endif"; headerFile.close(); } void WrapperGenerator::GenerateImplementations() { string operation; implementationFile << "#include \"VProfEventWrappers.h\"\n\n"; for (auto kv : *prototypeMap) { operation = (*operationMap)[kv.first]; implementationFile << kv.second.functionPrototype + " {\n\t"; if (kv.second.returnType != "void") { implementationFile << kv.second.returnType + " result;\n\t"; } operationToGenerator[operation]->GenerateWrapperPrologue(kv.first, kv.second); if (kv.second.returnType != "void") { implementationFile << "result = "; } implementationFile << kv.second.innerCallPrefix + "("; for (int i = 0, j = kv.second.paramVars.size(); i < j; i++) { implementationFile << kv.second.paramVars[i]; if (i != (j - 1)) { implementationFile << ", "; } } implementationFile <<");\n\t"; operationToGenerator[operation]->GenerateWrapperEpilogue(kv.first, kv.second); if (kv.second.returnType != "void") { implementationFile << "\treturn result;\n"; } implementationFile << "}\n\n"; } implementationFile.close(); } void WrapperGenerator::GenerateWrappers() { GenerateHeader(); GenerateImplementations(); } <|endoftext|>
<commit_before><commit_msg>CGAL 4.14 compatibility<commit_after><|endoftext|>
<commit_before>#include<cstdio> #include<algorithm> #define ll long long #define maxn 50005 int n,m; ll ans; int color[maxn],pos[maxn]; ll sum[maxn]; struct query{ int id,l,r; ll up,down; }Q[maxn]; inline bool cmp1(const query &q1,const query &q2){ return pos[q1.l]<pos[q2.l]||(pos[q1.l]==pos[q2.l]&&q1.r<q2.r); } inline bool cmp2(const query &q1,const query &q2){ return q1.id<q2.id; } ll gcd(ll a,ll b){ return b==0?a:gcd(b,a%b); } inline void update(const int &p,const bool &delta){ ans=ans+((sum[color[p]]<<1)+(delta?1:-1))*(delta?1:-1); sum[color[p]]+=delta?1:-1; } inline void prelude(){ scanf("%d%d",&n,&m); for(int i=1;i<=n;++i) scanf("%d",&color[i]); pos[0]=sqrt(n); for(int i=1;i<=m;++i){ Q[i].id=i; scanf("%d%d",&Q[i].l,&Q[i].r); Q[i].down=(ll)(Q[i].r-Q[i].l+1)*(Q[i].r-Q[i].l); } std::sort(Q+1,Q+1+m,cmp1); } inline void solve(){ ll g; for(int i=1,l=1,r=0;i<=m;++i){ for(;r<Q[i].r;++r) update(r+1,true); for(;r>Q[i].r;--r) update(r,false); for(;l<Q[i].l;++l) update(l,false); for(;l>Q[i].l;--l) update(l-1,true); if(Q[i].l==Q[i].r){ Q[i].up=0; Q[i].down=1; continue; } Q[i].up=ans-(Q[i].r-Q[i].l+1); g=gcd(Q[i].up,Q[i].down); Q[i].up/=g; Q[i].down/=g; } std::sort(Q+1,Q+1+m,cmp2); } int main(){ prelude(); solve(); for(register int i=1;i<=m;++i) printf("%lld/%lld\n",Q[i].up,Q[i].down); return 0; } <commit_msg>Update Mo.cpp<commit_after>#include<cstdio> #include<algorithm> #include<cmath> #define ll long long #define maxn 50005 int n,m; ll ans; int color[maxn],pos[maxn]; ll sum[maxn]; struct query{ int id,l,r; ll up,down; }Q[maxn]; inline bool cmp1(const query &q1,const query &q2){ return pos[q1.l]<pos[q2.l]||(pos[q1.l]==pos[q2.l]&&q1.r<q2.r); } inline bool cmp2(const query &q1,const query &q2){ return q1.id<q2.id; } ll gcd(ll a,ll b){ return b==0?a:gcd(b,a%b); } inline void update(const int &p,const bool &delta){ ans=ans+((sum[color[p]]<<1)+(delta?1:-1))*(delta?1:-1); sum[color[p]]+=delta?1:-1; } inline void prelude(){ scanf("%d%d",&n,&m); for(int i=1;i<=n;++i) scanf("%d",&color[i]); pos[0]=std::sqrt(n); for(int i=1;i<=n;++i) pos[i]=(i-1)/pos[0]+1; for(int i=1;i<=m;++i){ Q[i].id=i; scanf("%d%d",&Q[i].l,&Q[i].r); Q[i].down=(ll)(Q[i].r-Q[i].l+1)*(Q[i].r-Q[i].l); } std::sort(Q+1,Q+1+m,cmp1); } inline void solve(){ ll g; for(int i=1,l=1,r=0;i<=m;++i){ for(;r<Q[i].r;++r) update(r+1,true); for(;r>Q[i].r;--r) update(r,false); for(;l<Q[i].l;++l) update(l,false); for(;l>Q[i].l;--l) update(l-1,true); if(Q[i].l==Q[i].r){ Q[i].up=0; Q[i].down=1; continue; } Q[i].up=ans-(Q[i].r-Q[i].l+1); g=gcd(Q[i].up,Q[i].down); Q[i].up/=g; Q[i].down/=g; } std::sort(Q+1,Q+1+m,cmp2); } int main(){ prelude(); solve(); for(register int i=1;i<=m;++i) printf("%lld/%lld\n",Q[i].up,Q[i].down); return 0; } <|endoftext|>
<commit_before>#include <pd_view.h> #include <pd_backend.h> #include <stdlib.h> #include <stdio.h> #include <string.h> /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct File { char** lines; int lineCount; char* startData; char* filename; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct SourceCodeData { uint32_t line; File file; // todo: support more files }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void* readFileFromDisk(const char* file, size_t* size) { size_t fileSize; char* data; FILE* f = fopen(file, "rb"); if (!f) { printf("SICO: Unable to open file %s\n", file); return 0; } fseek(f, 0, SEEK_END); fileSize = (size_t)ftell(f); fseek(f, 0, SEEK_SET); // pad the size a bit so we make sure to have the data null terminated data = (char*)malloc(fileSize + 16); data[fileSize] = 0; if ((fread((void*)data, 1, fileSize, f)) != fileSize) { free(data); fclose(f); printf("SICO: Unable to read the whole file %s to memory\n", file); } *size = fileSize; return data; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TODO: Do not read whole file to memory? // TODO: Have a cache of files void parseFile(File* file, const char* filename) { char* target; char* targetEnd; char** lines; size_t size; int lineCount = 0; if (file->filename) { if (!strcmp(filename, file->filename)) return; } if (!(target = (char*)readFileFromDisk(filename, &size))) return; if (file->startData) { free(file->lines); free(file->startData); free(file->filename); } file->startData = target; targetEnd = target + size; // so this is really waste of memory but will do for now file->lines = lines = (char**)malloc(sizeof(char*) * size); lines[0] = target; lineCount++; while (target < targetEnd) { if (*target == '\r') *target++ = 0; if (*target == '\n') { *target++ = 0; lines[lineCount++] = target; } target++; } file->filename = strdup(filename); file->lineCount = lineCount; printf("found %d lines in %s\n", lineCount, filename); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // #if 0 static void drawCallback(void* userData, PDRect* viewRect, PDUIPainter* painter) { int fontX; int fontY; int exceptionLine = (int)data->line - 2; PDUIPaint_fontMetrics(painter, &fontX, &fontY); PDUIPaint_fillRect(painter, viewRect, 0xffffff); PDUIPaint_setPen(painter, 0); // calc how many lines we can render int maxLineCount = (viewRect->height - viewRect->y) / fontY; // in case file has less lines than we can display we render the whole file if (data->file.lineCount < maxLineCount) { int y = 20; for (int i = 0, end = data->file.lineCount; i < end; ++i) { PDUIPaint_drawText(painter, viewRect->x, y, data->file.lines[i]); if (i == exceptionLine) { printf("crash at %d - %s\n", i, data->file.lines[i]); PDRect rect = { viewRect->x, y, viewRect->width, y + fontY }; PDUIPaint_fillRect(painter, &rect, 0xf9afafaf); } y += fontX + 2; } } // figure out which line to start at so we can keep the exception line in the center //PDUIPaint_setPen(painter, 0x1fffffff); //PDUIPaint_drawText(painter, viewRect->x, y, pch); //y += fontX + 2; */ } #endif /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void* createInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc) { (void)serviceFunc; SourceCodeData* userData = (SourceCodeData*)malloc(sizeof(SourceCodeData)); memset(userData, 0, sizeof(SourceCodeData)); //userData->view = PDUICustomView_create(uiFuncs, userData, drawCallback); return userData; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void destroyInstance(void* userData) { free(userData); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void setExceptionLocation(SourceCodeData* data, PDReader* inEvents) { const char* filename; uint32_t line; // TODO: How to show this? Tell user to switch to disassembly view? if (PDRead_findString(inEvents, &filename, "filename", 0) == PDReadStatus_notFound) return; if (PDRead_findU32(inEvents, &line, "line", 0) == PDReadStatus_notFound) return; parseFile(&data->file, filename); data->line = line; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static int update(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* writer) { uint32_t event; (void)uiFuncs; SourceCodeData* data = (SourceCodeData*)userData; while ((event = PDRead_getEvent(inEvents)) != 0) { switch (event) { case PDEventType_setExceptionLocation : setExceptionLocation(data, inEvents); break; } } PDWrite_eventBegin(writer, PDEventType_getExceptionLocation); PDWrite_eventEnd(writer); return 0; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static PDViewPlugin plugin = { 0, // version "SourceCode", createInstance, destroyInstance, update, }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" { PD_EXPORT void InitPlugin(int version, ServiceFunc* serviceFunc, RegisterPlugin* registerPlugin) { (void)version; (void)serviceFunc; registerPlugin(PD_VIEW_API_VERSION, &plugin); } } <commit_msg>Warning fix<commit_after>#include <pd_view.h> #include <pd_backend.h> #include <stdlib.h> #include <stdio.h> #include <string.h> /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct File { char** lines; int lineCount; char* startData; char* filename; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct SourceCodeData { uint32_t line; File file; // todo: support more files }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void* readFileFromDisk(const char* file, size_t* size) { size_t fileSize; char* data; FILE* f = fopen(file, "rb"); if (!f) { printf("SICO: Unable to open file %s\n", file); return 0; } fseek(f, 0, SEEK_END); fileSize = (size_t)ftell(f); fseek(f, 0, SEEK_SET); // pad the size a bit so we make sure to have the data null terminated data = (char*)malloc(fileSize + 16); data[fileSize] = 0; if ((fread((void*)data, 1, fileSize, f)) != fileSize) { free(data); fclose(f); printf("SICO: Unable to read the whole file %s to memory\n", file); } *size = fileSize; return data; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TODO: Do not read whole file to memory? // TODO: Have a cache of files void parseFile(File* file, const char* filename) { char* target; char* targetEnd; char** lines; size_t size; int lineCount = 0; if (file->filename) { if (!strcmp(filename, file->filename)) return; } if (!(target = (char*)readFileFromDisk(filename, &size))) return; if (file->startData) { free(file->lines); free(file->startData); free(file->filename); } file->startData = target; targetEnd = target + size; // so this is really waste of memory but will do for now file->lines = lines = (char**)malloc(sizeof(char*) * size); lines[0] = target; lineCount++; while (target < targetEnd) { if (*target == '\r') *target++ = 0; if (*target == '\n') { *target++ = 0; lines[lineCount++] = target; } target++; } file->filename = strdup(filename); file->lineCount = lineCount; printf("found %d lines in %s\n", lineCount, filename); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // #if 0 static void drawCallback(void* userData, PDRect* viewRect, PDUIPainter* painter) { int fontX; int fontY; int exceptionLine = (int)data->line - 2; PDUIPaint_fontMetrics(painter, &fontX, &fontY); PDUIPaint_fillRect(painter, viewRect, 0xffffff); PDUIPaint_setPen(painter, 0); // calc how many lines we can render int maxLineCount = (viewRect->height - viewRect->y) / fontY; // in case file has less lines than we can display we render the whole file if (data->file.lineCount < maxLineCount) { int y = 20; for (int i = 0, end = data->file.lineCount; i < end; ++i) { PDUIPaint_drawText(painter, viewRect->x, y, data->file.lines[i]); if (i == exceptionLine) { printf("crash at %d - %s\n", i, data->file.lines[i]); PDRect rect = { viewRect->x, y, viewRect->width, y + fontY }; PDUIPaint_fillRect(painter, &rect, 0xf9afafaf); } y += fontX + 2; } } // figure out which line to start at so we can keep the exception line in the center //PDUIPaint_setPen(painter, 0x1fffffff); //PDUIPaint_drawText(painter, viewRect->x, y, pch); //y += fontX + 2; */ } #endif /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void* createInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc) { (void)serviceFunc; (void)uiFuncs; SourceCodeData* userData = (SourceCodeData*)malloc(sizeof(SourceCodeData)); memset(userData, 0, sizeof(SourceCodeData)); //userData->view = PDUICustomView_create(uiFuncs, userData, drawCallback); return userData; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void destroyInstance(void* userData) { free(userData); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void setExceptionLocation(SourceCodeData* data, PDReader* inEvents) { const char* filename; uint32_t line; // TODO: How to show this? Tell user to switch to disassembly view? if (PDRead_findString(inEvents, &filename, "filename", 0) == PDReadStatus_notFound) return; if (PDRead_findU32(inEvents, &line, "line", 0) == PDReadStatus_notFound) return; parseFile(&data->file, filename); data->line = line; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static int update(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* writer) { uint32_t event; (void)uiFuncs; SourceCodeData* data = (SourceCodeData*)userData; while ((event = PDRead_getEvent(inEvents)) != 0) { switch (event) { case PDEventType_setExceptionLocation : setExceptionLocation(data, inEvents); break; } } PDWrite_eventBegin(writer, PDEventType_getExceptionLocation); PDWrite_eventEnd(writer); return 0; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static PDViewPlugin plugin = { 0, // version "SourceCode", createInstance, destroyInstance, update, }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" { PD_EXPORT void InitPlugin(int version, ServiceFunc* serviceFunc, RegisterPlugin* registerPlugin) { (void)version; (void)serviceFunc; registerPlugin(PD_VIEW_API_VERSION, &plugin); } } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <unistd.h> #include <cstring> #include <stdio.h> #include <cstdlib> #include <sys/wait.h> #include<boost/tokenizer.hpp> using namespace std; using namespace boost; int main() { char hostname[999]; if(gethostname(hostname, 999)==-1) perror("hostname"); char login[999]; if(getlogin_r(login,999)==-1) perror("login"); string stringinput; char* input[999]; char_separator<char> ands("&&"); char_separator<char> ors("||"); char_separator<char> semico(";"); while(true) { //if the user name and hostname both exists, then the program displays it before the dollar sign. cout << login << "@" << hostname << "$ "; getline(cin,stringinput); //this checks for comments. Basically, everything after the hash symbol is useless if(stringinput.find("#") != string::npos) { stringinput=stringinput.substr(0,stringinput.find("#")); } //this checks for || if(stringinput.find("||")!=string::npos ) { tokenizer<char_separator<char> > toke(stringinput,ors); tokenizer<char_separator<char> >::iterator it=toke.begin(); for(; it != toke.end(); it++) { char_separator<char> space(" "); tokenizer<char_separator<char> > tok(*it, space); int status=0; pid_t pid = fork(); if(pid==-1) { perror("this is an error with fork()"); exit(1); } else if(pid==0) { int counter=0; for(tokenizer<char_separator<char> >::iterator it1=tok.begin(); it1 != tok.end(); it1++,counter++) { input[counter]=new char[(*it1).size()]; strcpy(input[counter],(*it1).c_str()); } input[counter]=0; int good=execvp(input[0],input); if(good==-1) { perror("Command is bad and not good!"); exit(1); } } else if(pid>=1) { if(wait(&status)==-1) perror("wait"); if(status<=0) break; } } if(stringinput.find("exit")!=string::npos) continue; } //this checks for && else if(stringinput.find("&&")!=string::npos ) { if(stringinput.find("exit")!=string::npos) exit(1); tokenizer<char_separator<char> > toke(stringinput,ands); tokenizer<char_separator<char> >::iterator it=toke.begin(); for(; it != toke.end(); it++) { char_separator<char> space(" "); tokenizer<char_separator<char> > tok(*it, space); int status=0; pid_t pid = fork(); if(pid==-1) { perror("this is an error with fork()"); exit(1); } else if(pid==0) { int counter=0; for(tokenizer<char_separator<char> >::iterator it1=tok.begin(); it1 != tok.end(); it1++,counter++) { input[counter]=new char[(*it1).size()]; strcpy(input[counter],(*it1).c_str()); } input[counter]=0; int good=execvp(input[0],input); if(good==-1) { perror("Command is bad and not good!"); exit(1); } } else if(pid>=1) { if(wait(&status)==-1) perror("wait"); if(status>0) break; } } } //this checks for ; and other things else { tokenizer<char_separator<char> > toke(stringinput,semico); tokenizer<char_separator<char> >::iterator it=toke.begin(); for(; it != toke.end(); it++) { char_separator<char> space(" "); tokenizer<char_separator<char> > tok(*it, space); int status=0; pid_t pid = fork(); if(pid==-1) { perror("this is an error with fork()"); exit(1); } //checks on the child else if(pid==0) { //starts to parse and token int counter=0; tokenizer<char_separator<char> >::iterator it1=tok.begin(); for(; it1 != tok.end(); it1++,counter++) { input[counter]=new char[(*it1).size()]; strcpy(input[counter],(*it1).c_str()); } input[counter]=0; int good=execvp(input[0],input); //finds a invalid command if(good==-1) { perror("Command is bad and not good!"); exit(1); } } else if(pid>=1) { waitpid(-1,&status,0); //waits for the child to finish if(wait(&status)==-1) perror("wait"); //waits for the child to finish } } } if(stringinput.find("exit")!=string::npos) { exit(1); } } return 0; } <commit_msg>added <<< and >><commit_after>#include <iostream> #include <string> #include <vector> #include <unistd.h> #include <cstring> #include <stdio.h> #include <cstdlib> #include <sys/wait.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/types.h> #include<boost/tokenizer.hpp> using namespace std; using namespace boost; //this function checks for which file descriptor int openF(const string &in, int perms) { char_separator<char> space(" "); tokenizer<char_separator<char> > tok(in, space); tokenizer<char_separator<char> >::iterator it1=tok.begin(); int good=open((*it1).c_str(),perms,S_IRWXU|S_IRWXG|S_IRWXO); if(good==-1) perror("open"); return good; } void execR(const string &in, int sin, int sout, int serr) { char *input[999]; int counter=0; char_separator<char> space(" "); tokenizer<char_separator<char> > tok(in, space); tokenizer<char_separator<char> >::iterator it1=tok.begin(); for(;it1!=tok.end();it1++,counter++) { input[counter]=new char[(*it1).size()]; strcpy(input[counter],(*it1).c_str()); } input[counter]=0; if(sin >= 0) { if(close(0)==-1) { perror("close"); exit(1); } if(dup(sin)==-1) { perror("dup"); exit(1); } } if(sout >= 0) { if(close(1)==-1) { perror("close"); exit(1); } if(dup(sout)==-1) { perror("dup"); exit(1); } } if(serr >= 0) { if(close(2)==-1) { perror("close"); exit(1); } if(dup(serr)==-1) { perror("dup"); exit(1); } } int good=(execvp(input[0],input)); if(good==-1) { perror("execvp"); for(counter=0,it1=tok.begin(); it1!=tok.end(); it1++, counter++) delete[] input[counter]; exit(1); } } int main() { char hostname[999]; if(gethostname(hostname, 999)==-1) perror("hostname"); char login[999]; if(getlogin_r(login,999)==-1) perror("login"); string stringinput; char* input[999]; char_separator<char> ands("&&"); char_separator<char> ors("||"); char_separator<char> semico(";"); while(true) { //if the user name and hostname both exists, then the program displays it before the dollar sign. cout << login << "@" << hostname << "$ "; getline(cin,stringinput); //this checks for comments. Basically, everything after the hash symbol is useless if(stringinput.find("#") != string::npos) { stringinput=stringinput.substr(0,stringinput.find("#")); } //this checks for || if(stringinput.find("||")!=string::npos ) { tokenizer<char_separator<char> > toke(stringinput,ors); tokenizer<char_separator<char> >::iterator it=toke.begin(); for(; it != toke.end(); it++) { char_separator<char> space(" "); tokenizer<char_separator<char> > tok(*it, space); int status=0; pid_t pid = fork(); if(pid==-1) { perror("this is an error with fork()"); exit(1); } else if(pid==0) { int counter=0; tokenizer<char_separator<char> >::iterator it1=tok.begin(); for(; it1 != tok.end(); it1++,counter++) { input[counter]=new char[(*it1).size()]; strcpy(input[counter],(*it1).c_str()); } input[counter]=0; int good=execvp(input[0],input); if(good==-1) { perror("Command is bad and not good!"); for(counter=0,it1=tok.begin(); it1!=tok.end(); it1++,counter++) delete[] input[counter]; exit(1); } } else if(pid>=1) { if(wait(&status)==-1) perror("wait"); if(status<=0) break; } } if(stringinput.find("exit")!=string::npos) continue; } //this checks for && else if(stringinput.find("&&")!=string::npos ) { if(stringinput.find("exit")!=string::npos) exit(1); tokenizer<char_separator<char> > toke(stringinput,ands); tokenizer<char_separator<char> >::iterator it=toke.begin(); for(; it != toke.end(); it++) { char_separator<char> space(" "); tokenizer<char_separator<char> > tok(*it, space); int status=0; pid_t pid = fork(); if(pid==-1) { perror("this is an error with fork()"); exit(1); } else if(pid==0) { int counter=0; tokenizer<char_separator<char> >::iterator it1=tok.begin(); for(; it1 != tok.end(); it1++,counter++) { input[counter]=new char[(*it1).size()]; strcpy(input[counter],(*it1).c_str()); } input[counter]=0; int good=execvp(input[0],input); if(good==-1) { perror("Command is bad and not good!"); for(counter=0,it1=tok.begin(); it1!=tok.end(); it1++,counter++) delete[] input[counter]; exit(1); } } else if(pid>=1) { if(wait(&status)==-1) perror("wait"); if(status>0) break; } } } else if(stringinput.find("<<<")!=string::npos) { string triple="<<<"; string single="<"; string result; int out=-1,in=-1; int fd[2]; if(stringinput.find("\"")!=string::npos) { //if we find only one double quote then we report an error result=stringinput.substr(stringinput.find("\"")+1); if(result.find("\"")==string::npos) { cout << "only found one double quote" << endl; exit(1); } result=result.substr(0,result.find("\"")); if(pipe(fd)==-1) { perror("pipe is broken"); exit(1); } char *buffer=new char[result.size()]; strcpy(buffer,result.c_str()); if(write(fd[1],buffer,strlen(buffer))==-1) { perror("write"); exit(1); } if(close(fd[1])==-1) { perror("close"); exit(1); } in=fd[0]; delete [] buffer; } else { cout << "please!" << endl; exit(1); } string left=stringinput.substr(0,stringinput.find(single)); string right=stringinput.substr(stringinput.find(single)+single.size()); string prev=right; if(right.find(">")!=string::npos) { prev=prev.substr(0,right.find(">")); int perm=O_RDWR|O_CREAT; int index; if(right.find(">>")!=string::npos) { perm |= O_APPEND; index=right.find(">>")+2; } else { perm |= O_TRUNC; index=right.find(">")+1; } right=right.substr(index); out=openF(right,perm); } pid_t pid=fork(); if(pid==-1) perror("fork"); else if(pid==0) execR(left,in,out,-1); else { if(wait(0)==-1) { perror("wait"); exit(1); } if(in!=-1) { if(close(in)==-1) { perror("close"); exit(1); } } if(out!=-1) { if(close(out)==-1) { perror("close"); exit(1); } } } } else if(stringinput.find(">>")!=string::npos) { int in=-1,out=-1; string doublein=">>"; int perm=O_RDWR|O_CREAT; perm |= O_APPEND; int index=stringinput.find(doublein); string left=stringinput.substr(0,index); string right=stringinput.substr(stringinput.find(doublein)+doublein.size()); int good=openF(right,perm); pid_t pid=fork(); if(pid==-1) perror("fork"); else if(pid==0) execR(left,in,good,-1); else { if(wait(0)==-1) { perror("wait"); exit(1); } if(close(good)==-1) { perror("close"); exit(1); } } } //this checks for ; and other things else { tokenizer<char_separator<char> > toke(stringinput,semico); tokenizer<char_separator<char> >::iterator it=toke.begin(); for(; it != toke.end(); it++) { char_separator<char> space(" "); tokenizer<char_separator<char> > tok(*it, space); int status=0; pid_t pid = fork(); if(pid==-1) { perror("this is an error with fork()"); exit(1); } //checks on the child else if(pid==0) { //starts to parse and token int counter=0; tokenizer<char_separator<char> >::iterator it1=tok.begin(); for(; it1 != tok.end(); it1++,counter++) { input[counter]=new char[(*it1).size()]; strcpy(input[counter],(*it1).c_str()); } input[counter]=0; int good=execvp(input[0],input); //finds a invalid command if(good==-1) { perror("Command is bad and not good!"); for(counter=0,it1=tok.begin(); it1!=tok.end(); it1++,counter++) delete[] input[counter]; exit(1); } } else if(pid>=1) { //waits for the child to finish if(wait(&status)==-1) perror("wait"); //waits for the child to finish } } } if(stringinput.find("exit")!=string::npos) { exit(1); } } return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include "libtorrent/config.hpp" #include <boost/scoped_ptr.hpp> #ifdef TORRENT_WINDOWS // windows part #include "libtorrent/utf8.hpp" #include <windows.h> #include <winioctl.h> #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #else // posix part #define _FILE_OFFSET_BITS 64 #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <boost/static_assert.hpp> // make sure the _FILE_OFFSET_BITS define worked // on this platform BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8); #endif #include <boost/filesystem/operations.hpp> #include "libtorrent/file.hpp" #include <sstream> #include <cstring> #include <vector> #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_RANDOM #define O_RANDOM 0 #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #include "libtorrent/assert.hpp" namespace { #ifdef TORRENT_WINDOWS std::string utf8_native(std::string const& s) { try { std::wstring ws; libtorrent::utf8_wchar(s, ws); std::size_t size = wcstombs(0, ws.c_str(), 0); if (size == std::size_t(-1)) return s; std::string ret; ret.resize(size); size = wcstombs(&ret[0], ws.c_str(), size + 1); if (size == wchar_t(-1)) return s; ret.resize(size); return ret; } catch(std::exception) { return s; } } #else enum { mode_in = 1, mode_out = 2 }; mode_t map_open_mode(int m) { if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM; TORRENT_ASSERT(false); return 0; } #endif } namespace libtorrent { namespace fs = boost::filesystem; #ifdef TORRENT_WINDOWS const file::open_mode file::in(GENERIC_READ); const file::open_mode file::out(GENERIC_WRITE); const file::seek_mode file::begin(FILE_BEGIN); const file::seek_mode file::end(FILE_END); #else const file::open_mode file::in(mode_in); const file::open_mode file::out(mode_out); const file::seek_mode file::begin(SEEK_SET); const file::seek_mode file::end(SEEK_END); #endif file::file() #ifdef TORRENT_WINDOWS : m_file_handle(INVALID_HANDLE_VALUE) #else : m_fd(-1) #endif #ifndef NDEBUG , m_open_mode(0) #endif {} file::file(fs::path const& path, open_mode mode, error_code& ec) #ifdef TORRENT_WINDOWS : m_file_handle(INVALID_HANDLE_VALUE) #else : m_fd(-1) #endif #ifndef NDEBUG , m_open_mode(0) #endif { open(path, mode, ec); } file::~file() { close(); } bool file::open(fs::path const& path, open_mode mode, error_code& ec) { close(); #ifdef TORRENT_WINDOWS #ifdef UNICODE std::wstring file_path(safe_convert(path.native_file_string())); #else std::string file_path = utf8_native(path.native_file_string()); #endif m_file_handle = CreateFile( file_path.c_str() , mode.m_mask , FILE_SHARE_READ , 0 , (mode & out)?OPEN_ALWAYS:OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL , 0); if (m_file_handle == INVALID_HANDLE_VALUE) { ec = error_code(GetLastError(), get_system_category()); return false; } // try to make the file sparse if supported if (mode & out) { DWORD temp; ::DeviceIoControl(m_file_handle, FSCTL_SET_SPARSE, 0, 0 , 0, 0, &temp, 0); } #else // rely on default umask to filter x and w permissions // for group and others m_fd = ::open(path.native_file_string().c_str() , map_open_mode(mode.m_mask), S_IRWXU | S_IRWXG | S_IRWXO); if (m_fd == -1) { ec = error_code(errno, get_posix_category()); return false; } #endif #ifndef NDEBUG m_open_mode = mode; #endif TORRENT_ASSERT(is_open()); return true; } bool file::is_open() const { #ifdef TORRENT_WINDOWS return m_file_handle != INVALID_HANDLE_VALUE; #else return m_fd != -1; #endif } void file::close() { #ifdef TORRENT_WINDOWS if (m_file_handle == INVALID_HANDLE_VALUE) return; CloseHandle(m_file_handle); m_file_handle = INVALID_HANDLE_VALUE; #else if (m_fd == -1) return; ::close(m_fd); m_fd = -1; #endif #ifndef NDEBUG m_open_mode = 0; #endif } size_type file::read(char* buf, size_type num_bytes, error_code& ec) { TORRENT_ASSERT((m_open_mode & in) == in); TORRENT_ASSERT(buf); TORRENT_ASSERT(num_bytes >= 0); TORRENT_ASSERT(is_open()); #ifdef TORRENT_WINDOWS TORRENT_ASSERT(DWORD(num_bytes) == num_bytes); DWORD ret = 0; if (num_bytes != 0) { if (ReadFile(m_file_handle, buf, (DWORD)num_bytes, &ret, 0) == FALSE) { ec = error_code(GetLastError(), get_system_category()); return -1; } } #else size_type ret = ::read(m_fd, buf, num_bytes); if (ret == -1) ec = error_code(errno, get_posix_category()); #endif return ret; } size_type file::write(const char* buf, size_type num_bytes, error_code& ec) { TORRENT_ASSERT((m_open_mode & out) == out); TORRENT_ASSERT(buf); TORRENT_ASSERT(num_bytes >= 0); TORRENT_ASSERT(is_open()); #ifdef TORRENT_WINDOWS DWORD ret = 0; if (num_bytes != 0) { if (WriteFile(m_file_handle, buf, (DWORD)num_bytes, &ret, 0) == FALSE) { ec = error_code(GetLastError(), get_system_category()); return -1; } } #else size_type ret = ::write(m_fd, buf, num_bytes); if (ret == -1) ec = error_code(errno, get_posix_category()); #endif return ret; } bool file::set_size(size_type s, error_code& ec) { TORRENT_ASSERT(is_open()); TORRENT_ASSERT(s >= 0); #ifdef TORRENT_WINDOWS size_type pos = tell(ec); if (ec) return false; seek(s, begin, ec); if (ec) return false; if (::SetEndOfFile(m_file_handle) == FALSE) { ec = error_code(GetLastError(), get_system_category()); return false; } #else if (ftruncate(m_fd, s) < 0) { ec = error_code(errno, get_posix_category()); return false; } #endif return true; } size_type file::seek(size_type offset, seek_mode m, error_code& ec) { TORRENT_ASSERT(is_open()); #ifdef TORRENT_WINDOWS LARGE_INTEGER offs; offs.QuadPart = offset; if (SetFilePointerEx(m_file_handle, offs, &offs, m.m_val) == FALSE) { ec = error_code(GetLastError(), get_system_category()); return -1; } return offs.QuadPart; #else size_type ret = lseek(m_fd, offset, m.m_val); if (ret < 0) ec = error_code(errno, get_posix_category()); return ret; #endif } size_type file::tell(error_code& ec) { TORRENT_ASSERT(is_open()); #ifdef TORRENT_WINDOWS LARGE_INTEGER offs; offs.QuadPart = 0; // is there any other way to get offset? if (SetFilePointerEx(m_file_handle, offs, &offs , FILE_CURRENT) == FALSE) { ec = error_code(GetLastError(), get_system_category()); return -1; } return offs.QuadPart; #else size_type ret; ret = lseek(m_fd, 0, SEEK_CUR); if (ret < 0) ec = error_code(errno, get_posix_category()); return ret; #endif } } <commit_msg>don't set executable permission of files<commit_after>/* Copyright (c) 2003, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include "libtorrent/config.hpp" #include <boost/scoped_ptr.hpp> #ifdef TORRENT_WINDOWS // windows part #include "libtorrent/utf8.hpp" #include <windows.h> #include <winioctl.h> #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #else // posix part #define _FILE_OFFSET_BITS 64 #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <boost/static_assert.hpp> // make sure the _FILE_OFFSET_BITS define worked // on this platform BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8); #endif #include <boost/filesystem/operations.hpp> #include "libtorrent/file.hpp" #include <sstream> #include <cstring> #include <vector> #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_RANDOM #define O_RANDOM 0 #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #include "libtorrent/assert.hpp" namespace { #ifdef TORRENT_WINDOWS std::string utf8_native(std::string const& s) { try { std::wstring ws; libtorrent::utf8_wchar(s, ws); std::size_t size = wcstombs(0, ws.c_str(), 0); if (size == std::size_t(-1)) return s; std::string ret; ret.resize(size); size = wcstombs(&ret[0], ws.c_str(), size + 1); if (size == wchar_t(-1)) return s; ret.resize(size); return ret; } catch(std::exception) { return s; } } #else enum { mode_in = 1, mode_out = 2 }; mode_t map_open_mode(int m) { if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM; TORRENT_ASSERT(false); return 0; } #endif } namespace libtorrent { namespace fs = boost::filesystem; #ifdef TORRENT_WINDOWS const file::open_mode file::in(GENERIC_READ); const file::open_mode file::out(GENERIC_WRITE); const file::seek_mode file::begin(FILE_BEGIN); const file::seek_mode file::end(FILE_END); #else const file::open_mode file::in(mode_in); const file::open_mode file::out(mode_out); const file::seek_mode file::begin(SEEK_SET); const file::seek_mode file::end(SEEK_END); #endif file::file() #ifdef TORRENT_WINDOWS : m_file_handle(INVALID_HANDLE_VALUE) #else : m_fd(-1) #endif #ifndef NDEBUG , m_open_mode(0) #endif {} file::file(fs::path const& path, open_mode mode, error_code& ec) #ifdef TORRENT_WINDOWS : m_file_handle(INVALID_HANDLE_VALUE) #else : m_fd(-1) #endif #ifndef NDEBUG , m_open_mode(0) #endif { open(path, mode, ec); } file::~file() { close(); } bool file::open(fs::path const& path, open_mode mode, error_code& ec) { close(); #ifdef TORRENT_WINDOWS #ifdef UNICODE std::wstring file_path(safe_convert(path.native_file_string())); #else std::string file_path = utf8_native(path.native_file_string()); #endif m_file_handle = CreateFile( file_path.c_str() , mode.m_mask , FILE_SHARE_READ , 0 , (mode & out)?OPEN_ALWAYS:OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL , 0); if (m_file_handle == INVALID_HANDLE_VALUE) { ec = error_code(GetLastError(), get_system_category()); return false; } // try to make the file sparse if supported if (mode & out) { DWORD temp; ::DeviceIoControl(m_file_handle, FSCTL_SET_SPARSE, 0, 0 , 0, 0, &temp, 0); } #else // rely on default umask to filter x and w permissions // for group and others int permissions = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; m_fd = ::open(path.native_file_string().c_str() , map_open_mode(mode.m_mask), permissions); if (m_fd == -1) { ec = error_code(errno, get_posix_category()); return false; } #endif #ifndef NDEBUG m_open_mode = mode; #endif TORRENT_ASSERT(is_open()); return true; } bool file::is_open() const { #ifdef TORRENT_WINDOWS return m_file_handle != INVALID_HANDLE_VALUE; #else return m_fd != -1; #endif } void file::close() { #ifdef TORRENT_WINDOWS if (m_file_handle == INVALID_HANDLE_VALUE) return; CloseHandle(m_file_handle); m_file_handle = INVALID_HANDLE_VALUE; #else if (m_fd == -1) return; ::close(m_fd); m_fd = -1; #endif #ifndef NDEBUG m_open_mode = 0; #endif } size_type file::read(char* buf, size_type num_bytes, error_code& ec) { TORRENT_ASSERT((m_open_mode & in) == in); TORRENT_ASSERT(buf); TORRENT_ASSERT(num_bytes >= 0); TORRENT_ASSERT(is_open()); #ifdef TORRENT_WINDOWS TORRENT_ASSERT(DWORD(num_bytes) == num_bytes); DWORD ret = 0; if (num_bytes != 0) { if (ReadFile(m_file_handle, buf, (DWORD)num_bytes, &ret, 0) == FALSE) { ec = error_code(GetLastError(), get_system_category()); return -1; } } #else size_type ret = ::read(m_fd, buf, num_bytes); if (ret == -1) ec = error_code(errno, get_posix_category()); #endif return ret; } size_type file::write(const char* buf, size_type num_bytes, error_code& ec) { TORRENT_ASSERT((m_open_mode & out) == out); TORRENT_ASSERT(buf); TORRENT_ASSERT(num_bytes >= 0); TORRENT_ASSERT(is_open()); #ifdef TORRENT_WINDOWS DWORD ret = 0; if (num_bytes != 0) { if (WriteFile(m_file_handle, buf, (DWORD)num_bytes, &ret, 0) == FALSE) { ec = error_code(GetLastError(), get_system_category()); return -1; } } #else size_type ret = ::write(m_fd, buf, num_bytes); if (ret == -1) ec = error_code(errno, get_posix_category()); #endif return ret; } bool file::set_size(size_type s, error_code& ec) { TORRENT_ASSERT(is_open()); TORRENT_ASSERT(s >= 0); #ifdef TORRENT_WINDOWS size_type pos = tell(ec); if (ec) return false; seek(s, begin, ec); if (ec) return false; if (::SetEndOfFile(m_file_handle) == FALSE) { ec = error_code(GetLastError(), get_system_category()); return false; } #else if (ftruncate(m_fd, s) < 0) { ec = error_code(errno, get_posix_category()); return false; } #endif return true; } size_type file::seek(size_type offset, seek_mode m, error_code& ec) { TORRENT_ASSERT(is_open()); #ifdef TORRENT_WINDOWS LARGE_INTEGER offs; offs.QuadPart = offset; if (SetFilePointerEx(m_file_handle, offs, &offs, m.m_val) == FALSE) { ec = error_code(GetLastError(), get_system_category()); return -1; } return offs.QuadPart; #else size_type ret = lseek(m_fd, offset, m.m_val); if (ret < 0) ec = error_code(errno, get_posix_category()); return ret; #endif } size_type file::tell(error_code& ec) { TORRENT_ASSERT(is_open()); #ifdef TORRENT_WINDOWS LARGE_INTEGER offs; offs.QuadPart = 0; // is there any other way to get offset? if (SetFilePointerEx(m_file_handle, offs, &offs , FILE_CURRENT) == FALSE) { ec = error_code(GetLastError(), get_system_category()); return -1; } return offs.QuadPart; #else size_type ret; ret = lseek(m_fd, 0, SEEK_CUR); if (ret < 0) ec = error_code(errno, get_posix_category()); return ret; #endif } } <|endoftext|>
<commit_before>/* * Copyright 2016 Nu-book Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ReadBarcode.h" #include "TextUtfEncoding.h" #include "ZXNumeric.h" #include <iostream> #include <cstring> #include <string> #include <algorithm> #include <cctype> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" using namespace ZXing; static void PrintUsage(const char* exePath) { std::cout << "Usage: " << exePath << " [-fast] [-rotate] [-format <FORMAT[,...]>] <png image path>\n" << " -fast Skip some lines/pixels during detection\n" << " -rotate Also try rotated image during detection\n" << " -format Only detect given format(s)\n" << " -ispure Assume the image contains only a 'pure'/perfect code\n" << "\n" << "Supported formats are:\n"; for (auto f : BarcodeFormats::all()) { std::cout << " " << ToString(f) << "\n"; } std::cout << "Formats can be lowercase, with or without underscore, separated by ',', '|' and/or ' '\n"; } static bool ParseOptions(int argc, char* argv[], DecodeHints* hints, std::string* filePath) { hints->setTryHarder(true); for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-fast") == 0) { hints->setTryHarder(false); } else if (strcmp(argv[i], "-rotate") == 0) { hints->setTryRotate(true); } else if (strcmp(argv[i], "-ispure") == 0) { hints->setIsPure(true); hints->setBinarizer(Binarizer::FixedThreshold); } else if (strcmp(argv[i], "-format") == 0) { if (++i == argc) return false; try { hints->setFormats(BarcodeFormatsFromString(argv[i])); } catch (const std::exception& e) { std::cerr << e.what() << "\n"; return false; } } else { *filePath = argv[i]; } } return !filePath->empty(); } std::ostream& operator<<(std::ostream& os, const Position& points) { for (const auto& p : points) os << p.x << "x" << p.y << " "; return os; } int main(int argc, char* argv[]) { DecodeHints hints; std::string filePath; if (!ParseOptions(argc, argv, &hints, &filePath)) { PrintUsage(argv[0]); return -1; } int width, height, channels; std::unique_ptr<stbi_uc, void(*)(void*)> buffer(stbi_load(filePath.c_str(), &width, &height, &channels, 4), stbi_image_free); if (buffer == nullptr) { std::cerr << "Failed to read image: " << filePath << "\n"; return -1; } auto result = ReadBarcode({buffer.get(), width, height, ImageFormat::RGBX}, hints); std::cout << "Text: \"" << TextUtfEncoding::ToUtf8(result.text()) << "\"\n" << "Format: " << ToString(result.format()) << "\n" << "Position: " << result.position() << "\n" << "Rotation: " << std::lround(result.position().rotation() * kDegPerRad) << "\n" << "Error: " << ToString(result.status()) << "\n"; std::map<ResultMetadata::Key, const char*> keys = {{ResultMetadata::ERROR_CORRECTION_LEVEL, "EC Level: "}, {ResultMetadata::SUGGESTED_PRICE, "Price: "}, {ResultMetadata::ISSUE_NUMBER, "Issue #: "}, {ResultMetadata::POSSIBLE_COUNTRY, "Country: "}, {ResultMetadata::UPC_EAN_EXTENSION, "Extension:"}}; for (auto key : keys) { auto value = TextUtfEncoding::ToUtf8(result.metadata().getString(key.first)); if (value.size()) std::cout << key.second << value << "\n"; } return static_cast<int>(result.status()); } <commit_msg>example: trivial output cosmetic (add 'deg' to the 'Rotation:' output)<commit_after>/* * Copyright 2016 Nu-book Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ReadBarcode.h" #include "TextUtfEncoding.h" #include "ZXNumeric.h" #include <iostream> #include <cstring> #include <string> #include <algorithm> #include <cctype> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" using namespace ZXing; static void PrintUsage(const char* exePath) { std::cout << "Usage: " << exePath << " [-fast] [-rotate] [-format <FORMAT[,...]>] <png image path>\n" << " -fast Skip some lines/pixels during detection\n" << " -rotate Also try rotated image during detection\n" << " -format Only detect given format(s)\n" << " -ispure Assume the image contains only a 'pure'/perfect code\n" << "\n" << "Supported formats are:\n"; for (auto f : BarcodeFormats::all()) { std::cout << " " << ToString(f) << "\n"; } std::cout << "Formats can be lowercase, with or without underscore, separated by ',', '|' and/or ' '\n"; } static bool ParseOptions(int argc, char* argv[], DecodeHints* hints, std::string* filePath) { hints->setTryHarder(true); for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-fast") == 0) { hints->setTryHarder(false); } else if (strcmp(argv[i], "-rotate") == 0) { hints->setTryRotate(true); } else if (strcmp(argv[i], "-ispure") == 0) { hints->setIsPure(true); hints->setBinarizer(Binarizer::FixedThreshold); } else if (strcmp(argv[i], "-format") == 0) { if (++i == argc) return false; try { hints->setFormats(BarcodeFormatsFromString(argv[i])); } catch (const std::exception& e) { std::cerr << e.what() << "\n"; return false; } } else { *filePath = argv[i]; } } return !filePath->empty(); } std::ostream& operator<<(std::ostream& os, const Position& points) { for (const auto& p : points) os << p.x << "x" << p.y << " "; return os; } int main(int argc, char* argv[]) { DecodeHints hints; std::string filePath; if (!ParseOptions(argc, argv, &hints, &filePath)) { PrintUsage(argv[0]); return -1; } int width, height, channels; std::unique_ptr<stbi_uc, void(*)(void*)> buffer(stbi_load(filePath.c_str(), &width, &height, &channels, 4), stbi_image_free); if (buffer == nullptr) { std::cerr << "Failed to read image: " << filePath << "\n"; return -1; } auto result = ReadBarcode({buffer.get(), width, height, ImageFormat::RGBX}, hints); std::cout << "Text: \"" << TextUtfEncoding::ToUtf8(result.text()) << "\"\n" << "Format: " << ToString(result.format()) << "\n" << "Position: " << result.position() << "\n" << "Rotation: " << std::lround(result.position().rotation() * kDegPerRad) << " deg\n" << "Error: " << ToString(result.status()) << "\n"; std::map<ResultMetadata::Key, const char*> keys = {{ResultMetadata::ERROR_CORRECTION_LEVEL, "EC Level: "}, {ResultMetadata::SUGGESTED_PRICE, "Price: "}, {ResultMetadata::ISSUE_NUMBER, "Issue #: "}, {ResultMetadata::POSSIBLE_COUNTRY, "Country: "}, {ResultMetadata::UPC_EAN_EXTENSION, "Extension:"}}; for (auto key : keys) { auto value = TextUtfEncoding::ToUtf8(result.metadata().getString(key.first)); if (value.size()) std::cout << key.second << value << "\n"; } return static_cast<int>(result.status()); } <|endoftext|>
<commit_before>// // Test Suite for geos::index::quadtree::DoubleBits class. #include <tut/tut.hpp> // geos #include <geos/index/quadtree/DoubleBits.h> using namespace geos::index::quadtree; namespace tut { // dummy data, not used struct test_doublebits_data {}; typedef test_group<test_doublebits_data> group; typedef group::object object; group test_doublebits_group("geos::index::quadtree::DoubleBits"); // // Test Cases // // 1 - Test exponent() template<> template<> void object::test<1> () { ensure_equals(DoubleBits::exponent(-1), 0); ensure_equals(DoubleBits::exponent(8.0), 3); ensure_equals(DoubleBits::exponent(128.0), 7); } } // namespace tut <commit_msg>Add toString test<commit_after>// // Test Suite for geos::index::quadtree::DoubleBits class. #include <tut/tut.hpp> // geos #include <geos/index/quadtree/DoubleBits.h> using namespace geos::index::quadtree; namespace tut { // dummy data, not used struct test_doublebits_data {}; typedef test_group<test_doublebits_data> group; typedef group::object object; group test_doublebits_group("geos::index::quadtree::DoubleBits"); // // Test Cases // // 1 - Test exponent() template<> template<> void object::test<1> () { ensure_equals(DoubleBits::exponent(-1), 0); ensure_equals(DoubleBits::exponent(8.0), 3); ensure_equals(DoubleBits::exponent(128.0), 7); } // 2 - Test toString() template<> template<> void object::test<2> () { ensure_equals(DoubleBits(-1).toString(), "1 01111111111(0) 0000000000000000000000000000000000000000000000000000 [ -1.000000 ]"); ensure_equals(DoubleBits(8.0).toString(), "0 10000000010(3) 0000000000000000000000000000000000000000000000000000 [ 8.000000 ]"); ensure_equals(DoubleBits(128.0).toString(), "0 10000000110(7) 0000000000000000000000000000000000000000000000000000 [ 128.000000 ]"); } } // namespace tut <|endoftext|>
<commit_before>/* * Copyright (C) 2006-2008 Marc Boris Duerner * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "directoryimpl.h" #include "cxxtools/directory.h" namespace cxxtools { DirectoryIterator::DirectoryIterator() : _impl(0) { } DirectoryIterator::DirectoryIterator(const std::string& path, bool skipHidden) { _impl = new DirectoryIteratorImpl( path.c_str(), skipHidden ); } DirectoryIterator::DirectoryIterator(const DirectoryIterator& it) : _impl(0) { _impl = it._impl; if (_impl) _impl->ref(); } DirectoryIterator::~DirectoryIterator() { if (_impl && 0 == _impl->deref()) { delete _impl; } } DirectoryIterator& DirectoryIterator::operator++() { if (_impl && !_impl->advance()) { if (0 == _impl->deref()) delete _impl; _impl = 0; } return *this; } DirectoryIterator& DirectoryIterator::operator=(const DirectoryIterator& it) { if (_impl == it._impl) return *this; if (_impl && 0 == _impl->deref()) { delete _impl; } _impl = it._impl; if (_impl) _impl->ref(); return *this; } const std::string& DirectoryIterator::path() const { return _impl->path(); } const std::string& DirectoryIterator::operator*() const { return _impl->name(); } const std::string* DirectoryIterator::operator->() const { return &_impl->name(); } Directory::Directory() { } Directory::Directory(const std::string& path) : _path(path) { if ( ! Directory::exists( path.c_str() ) ) throw DirectoryNotFound(path); } Directory::Directory(const FileInfo& fi) : _path( fi.path() ) { if (! fi.isDirectory()) throw DirectoryNotFound(fi.path()); } Directory::Directory(const Directory& dir) : _path(dir._path) { } Directory::~Directory() { } Directory& Directory::operator=(const Directory& dir) { _path = dir._path; return *this; } std::size_t Directory::size() const { return 0; } Directory::const_iterator Directory::begin(bool skipHidden) const { return DirectoryIterator( path().c_str(), skipHidden ); } Directory::const_iterator Directory::end() const { return DirectoryIterator(); } void Directory::remove() { DirectoryImpl::remove( path() ); } void Directory::move(const std::string& to) { DirectoryImpl::move(path(), to); _path = to; } std::string Directory::dirName() const { // Find last slash. This separates the last path segment from the rest of the path std::string::size_type separatorPos = path().find_last_of( this->sep() ); // If there is no separator, this directory is relative to the current current directory. // So an empty path is returned. if (separatorPos == std::string::npos) { return ""; } // Include trailing separator to be able to distinguish between no path ("") and a path // which is relative to the root ("/"), for example. return path().substr(0, separatorPos + 1); } std::string Directory::name() const { std::string::size_type separatorPos = path().rfind( this->sep() ); if (separatorPos != std::string::npos) { return path().substr(separatorPos + 1); } else { return path(); } } Directory Directory::create(const std::string& path) { DirectoryImpl::create( path.c_str() ); return Directory(path); } bool Directory::exists(const std::string& path) { return FileInfo::getType( path.c_str() ) == FileInfo::Directory; } void Directory::chdir(const std::string& path) { DirectoryImpl::chdir(path); } std::string Directory::cwd() { return DirectoryImpl::cwd(); } std::string Directory::curdir() { return DirectoryImpl::curdir(); } std::string Directory::updir() { return DirectoryImpl::updir(); } std::string rootdir() { return DirectoryImpl::rootdir(); } std::string tmpdir() { return DirectoryImpl::tmpdir(); } std::string Directory::sep() { return DirectoryImpl::sep(); } } // namespace cxxtools <commit_msg>directory class can now iterate over directories referenced by links<commit_after>/* * Copyright (C) 2006-2008 Marc Boris Duerner * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "directoryimpl.h" #include "cxxtools/directory.h" namespace cxxtools { DirectoryIterator::DirectoryIterator() : _impl(0) { } DirectoryIterator::DirectoryIterator(const std::string& path, bool skipHidden) { _impl = new DirectoryIteratorImpl( path.c_str(), skipHidden ); } DirectoryIterator::DirectoryIterator(const DirectoryIterator& it) : _impl(0) { _impl = it._impl; if (_impl) _impl->ref(); } DirectoryIterator::~DirectoryIterator() { if (_impl && 0 == _impl->deref()) { delete _impl; } } DirectoryIterator& DirectoryIterator::operator++() { if (_impl && !_impl->advance()) { if (0 == _impl->deref()) delete _impl; _impl = 0; } return *this; } DirectoryIterator& DirectoryIterator::operator=(const DirectoryIterator& it) { if (_impl == it._impl) return *this; if (_impl && 0 == _impl->deref()) { delete _impl; } _impl = it._impl; if (_impl) _impl->ref(); return *this; } const std::string& DirectoryIterator::path() const { return _impl->path(); } const std::string& DirectoryIterator::operator*() const { return _impl->name(); } const std::string* DirectoryIterator::operator->() const { return &_impl->name(); } Directory::Directory() { } Directory::Directory(const std::string& path) : _path(path) { if (! exists(_path) ) throw DirectoryNotFound(path); } Directory::Directory(const FileInfo& fi) : _path( fi.path() ) { if (!exists(_path)) throw DirectoryNotFound(fi.path()); } Directory::Directory(const Directory& dir) : _path(dir._path) { } Directory::~Directory() { } Directory& Directory::operator=(const Directory& dir) { _path = dir._path; return *this; } std::size_t Directory::size() const { return 0; } Directory::const_iterator Directory::begin(bool skipHidden) const { return DirectoryIterator( path(), skipHidden ); } Directory::const_iterator Directory::end() const { return DirectoryIterator(); } void Directory::remove() { DirectoryImpl::remove( path() ); } void Directory::move(const std::string& to) { DirectoryImpl::move(path(), to); _path = to; } std::string Directory::dirName() const { // Find last slash. This separates the last path segment from the rest of the path std::string::size_type separatorPos = path().find_last_of( this->sep() ); // If there is no separator, this directory is relative to the current current directory. // So an empty path is returned. if (separatorPos == std::string::npos) { return ""; } // Include trailing separator to be able to distinguish between no path ("") and a path // which is relative to the root ("/"), for example. return path().substr(0, separatorPos + 1); } std::string Directory::name() const { std::string::size_type separatorPos = path().rfind( this->sep() ); if (separatorPos != std::string::npos) { return path().substr(separatorPos + 1); } else { return path(); } } Directory Directory::create(const std::string& path) { DirectoryImpl::create( path ); return Directory(path); } bool Directory::exists(const std::string& path) { return DirectoryImpl::exists(path); } void Directory::chdir(const std::string& path) { DirectoryImpl::chdir(path); } std::string Directory::cwd() { return DirectoryImpl::cwd(); } std::string Directory::curdir() { return DirectoryImpl::curdir(); } std::string Directory::updir() { return DirectoryImpl::updir(); } std::string rootdir() { return DirectoryImpl::rootdir(); } std::string tmpdir() { return DirectoryImpl::tmpdir(); } std::string Directory::sep() { return DirectoryImpl::sep(); } } // namespace cxxtools <|endoftext|>
<commit_before>/* Copyright (C) 2002 by Norman Kramer Multi-axis support (C) 2005 Adam D. Bradley <artdodge@cs.bu.edu> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "iutil/csinput.h" /* for JS max/mins */ #include "iutil/verbositymanager.h" #include "ivaria/reporter.h" #include "csutil/array.h" #include "csutil/csstring.h" #include "csutil/event.h" #include "csutil/eventnames.h" #include "csutil/eventhandlers.h" #include "csjoylin.h" #include <errno.h> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <linux/joystick.h> #define CS_LINUX_JOYSTICK_CFG "/config/joystick.cfg" #define CS_LINUX_JOYSTICK_KEY "Device.Joystick." CS_PLATFORM_NAME "." CS_PLUGIN_NAMESPACE_BEGIN(JoyLin) { SCF_IMPLEMENT_FACTORY (csLinuxJoystick); csLinuxJoystick::csLinuxJoystick (iBase *parent) : scfImplementationType (this, parent), object_reg(0), joystick(0), nJoy(0), bHooked(false) { } csLinuxJoystick::~csLinuxJoystick () { Close (); } bool csLinuxJoystick::Initialize (iObjectRegistry *oreg) { object_reg = oreg; return Init (); } #define CS_MAX_LINUX_JOYSTICK_AXES CS_MAX_JOYSTICK_AXES bool csLinuxJoystick::HandleEvent (iEvent& ev) { if (ev.Name != Frame) return false; struct js_event js; for (int i = 0; i < nJoy; i++) { joydata& jd = joystick[i]; while (read (jd.fd, &js, sizeof(js)) == sizeof(js)) { int32 axisread[CS_MAX_LINUX_JOYSTICK_AXES]; if ((js.type & ~JS_EVENT_INIT) == JS_EVENT_AXIS) jd.axis[js.number] = js.value; for (int iter=0 ; iter<MIN(jd.nAxes,CS_MAX_LINUX_JOYSTICK_AXES) ; iter++) axisread[iter] = jd.axis[iter]; /* "int16" to "int" */ switch (js.type & ~JS_EVENT_INIT) { case JS_EVENT_BUTTON: jd.button[js.number] = js.value; EventOutlet->Joystick (jd.number, js.number, js.value, axisread, jd.nAxes); break; case JS_EVENT_AXIS: EventOutlet->Joystick (jd.number, (uint) -1, 0, axisread, jd.nAxes); break; } } } return false; } bool csLinuxJoystick::Init () { bool verbose = false; csRef<iVerbosityManager> verbosemgr ( csQueryRegistry<iVerbosityManager> (object_reg)); if (verbosemgr) verbose = verbosemgr->Enabled ("joystick"); config.AddConfig (object_reg, CS_LINUX_JOYSTICK_CFG); csRef<iConfigIterator> it (config->Enumerate (CS_LINUX_JOYSTICK_KEY)); csArray<int> fds; csArray<dev_t> devids; nJoy=0; bHooked = false; EventOutlet = 0; while (it->Next ()) { int fd = open (it->GetStr (), O_RDONLY); if (fd >= 0) { Report (CS_REPORTER_SEVERITY_DEBUG, "Opened joystick device %s as fd#%d\n", it->GetStr(), fd); struct stat st; fstat(fd, &st); /* check devids for a dup st.st_dev */ for (csArray<dev_t>::Iterator i = devids.GetIterator(); i.HasNext(); ) { if (i.Next() == st.st_rdev) { close(fd); fd = -1; if (verbose) Report (CS_REPORTER_SEVERITY_WARNING, "Found duplicate joystick device %s\n", it->GetStr()); break; } } if (fd != -1) { nJoy++; fds.Push((const int) fd); devids.Push(st.st_rdev); } } else if (verbose || errno != ENOENT) { Report (CS_REPORTER_SEVERITY_WARNING, "Failed to open joystick device %s - error: %s\n", it->GetStr (), strerror (errno)); } } if (nJoy) { delete [] joystick; joystick = new joydata[nJoy]; csArray<int>::Iterator i = fds.GetIterator(); int n = 0; while (i.HasNext()) { int const fd = i.Next(); unsigned char axes = 2; unsigned char buttons = 2; int version = 0x000800; char name[128] = "Unknown"; ioctl (fd, JSIOCGVERSION, &version); ioctl (fd, JSIOCGAXES, &axes); ioctl (fd, JSIOCGBUTTONS, &buttons); ioctl (fd, JSIOCGNAME(128), name); Report (CS_REPORTER_SEVERITY_NOTIFY, "Joystick number %d (%s) has %hhu axes and %hhu buttons.\n" "Driver version is %d.%d.%d.\n", n, name, axes, buttons, version >> 16, (version >> 8) & 0xff, version & 0xff); joydata& jd = joystick[n]; jd.number = n; // CS joystick numbers are 0-based. jd.fd = fd; jd.nButtons = buttons; jd.nAxes = axes; jd.axis = new int16[axes]; jd.button = new int16[buttons]; fcntl(fd, F_SETFL, O_NONBLOCK); n++; } // hook into eventqueue Frame = csevFrame (object_reg); csRef<iEventQueue> eq (csQueryRegistry<iEventQueue> (object_reg)); if (eq != 0) { eq->RegisterListener (static_cast<iEventHandler*> (this), Frame); EventOutlet = eq->CreateEventOutlet (static_cast<iEventPlug*> (this)); bHooked = true; } } else { Report (CS_REPORTER_SEVERITY_NOTIFY, "No operable joystick found\n"); } return EventOutlet.IsValid(); } bool csLinuxJoystick::Close () { if (bHooked) { csRef<iEventQueue> eq (csQueryRegistry<iEventQueue> (object_reg)); if (eq != 0) eq->RemoveListener (static_cast<iEventHandler*> (this)); bHooked = false; } EventOutlet = 0; for (int i=0; i<nJoy; i++) close (joystick[i].fd); delete [] joystick; joystick = 0; nJoy = 0; return true; } void csLinuxJoystick::Report (int severity, const char* msg, ...) { va_list arg; va_start (arg, msg); csReportV (object_reg, severity, "crystalspace.device.joystick.linux", msg, arg); va_end (arg); } } CS_PLUGIN_NAMESPACE_END(JoyLin) <commit_msg>Lowered severity of a message which will always show in the linux joystick support. That the joystick device x can't be opened will always happen even more when trying 15 devices in two places and even further when there is no joypad attached.<commit_after>/* Copyright (C) 2002 by Norman Kramer Multi-axis support (C) 2005 Adam D. Bradley <artdodge@cs.bu.edu> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "iutil/csinput.h" /* for JS max/mins */ #include "iutil/verbositymanager.h" #include "ivaria/reporter.h" #include "csutil/array.h" #include "csutil/csstring.h" #include "csutil/event.h" #include "csutil/eventnames.h" #include "csutil/eventhandlers.h" #include "csjoylin.h" #include <errno.h> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <linux/joystick.h> #define CS_LINUX_JOYSTICK_CFG "/config/joystick.cfg" #define CS_LINUX_JOYSTICK_KEY "Device.Joystick." CS_PLATFORM_NAME "." CS_PLUGIN_NAMESPACE_BEGIN(JoyLin) { SCF_IMPLEMENT_FACTORY (csLinuxJoystick); csLinuxJoystick::csLinuxJoystick (iBase *parent) : scfImplementationType (this, parent), object_reg(0), joystick(0), nJoy(0), bHooked(false) { } csLinuxJoystick::~csLinuxJoystick () { Close (); } bool csLinuxJoystick::Initialize (iObjectRegistry *oreg) { object_reg = oreg; return Init (); } #define CS_MAX_LINUX_JOYSTICK_AXES CS_MAX_JOYSTICK_AXES bool csLinuxJoystick::HandleEvent (iEvent& ev) { if (ev.Name != Frame) return false; struct js_event js; for (int i = 0; i < nJoy; i++) { joydata& jd = joystick[i]; while (read (jd.fd, &js, sizeof(js)) == sizeof(js)) { int32 axisread[CS_MAX_LINUX_JOYSTICK_AXES]; if ((js.type & ~JS_EVENT_INIT) == JS_EVENT_AXIS) jd.axis[js.number] = js.value; for (int iter=0 ; iter<MIN(jd.nAxes,CS_MAX_LINUX_JOYSTICK_AXES) ; iter++) axisread[iter] = jd.axis[iter]; /* "int16" to "int" */ switch (js.type & ~JS_EVENT_INIT) { case JS_EVENT_BUTTON: jd.button[js.number] = js.value; EventOutlet->Joystick (jd.number, js.number, js.value, axisread, jd.nAxes); break; case JS_EVENT_AXIS: EventOutlet->Joystick (jd.number, (uint) -1, 0, axisread, jd.nAxes); break; } } } return false; } bool csLinuxJoystick::Init () { bool verbose = false; csRef<iVerbosityManager> verbosemgr ( csQueryRegistry<iVerbosityManager> (object_reg)); if (verbosemgr) verbose = verbosemgr->Enabled ("joystick"); config.AddConfig (object_reg, CS_LINUX_JOYSTICK_CFG); csRef<iConfigIterator> it (config->Enumerate (CS_LINUX_JOYSTICK_KEY)); csArray<int> fds; csArray<dev_t> devids; nJoy=0; bHooked = false; EventOutlet = 0; while (it->Next ()) { int fd = open (it->GetStr (), O_RDONLY); if (fd >= 0) { Report (CS_REPORTER_SEVERITY_DEBUG, "Opened joystick device %s as fd#%d\n", it->GetStr(), fd); struct stat st; fstat(fd, &st); /* check devids for a dup st.st_dev */ for (csArray<dev_t>::Iterator i = devids.GetIterator(); i.HasNext(); ) { if (i.Next() == st.st_rdev) { close(fd); fd = -1; if (verbose) Report (CS_REPORTER_SEVERITY_WARNING, "Found duplicate joystick device %s\n", it->GetStr()); break; } } if (fd != -1) { nJoy++; fds.Push((const int) fd); devids.Push(st.st_rdev); } } else if (verbose || errno != ENOENT) { Report (CS_REPORTER_SEVERITY_DEBUG, "Failed to open joystick device %s - error: %s\n", it->GetStr (), strerror (errno)); } } if (nJoy) { delete [] joystick; joystick = new joydata[nJoy]; csArray<int>::Iterator i = fds.GetIterator(); int n = 0; while (i.HasNext()) { int const fd = i.Next(); unsigned char axes = 2; unsigned char buttons = 2; int version = 0x000800; char name[128] = "Unknown"; ioctl (fd, JSIOCGVERSION, &version); ioctl (fd, JSIOCGAXES, &axes); ioctl (fd, JSIOCGBUTTONS, &buttons); ioctl (fd, JSIOCGNAME(128), name); Report (CS_REPORTER_SEVERITY_NOTIFY, "Joystick number %d (%s) has %hhu axes and %hhu buttons.\n" "Driver version is %d.%d.%d.\n", n, name, axes, buttons, version >> 16, (version >> 8) & 0xff, version & 0xff); joydata& jd = joystick[n]; jd.number = n; // CS joystick numbers are 0-based. jd.fd = fd; jd.nButtons = buttons; jd.nAxes = axes; jd.axis = new int16[axes]; jd.button = new int16[buttons]; fcntl(fd, F_SETFL, O_NONBLOCK); n++; } // hook into eventqueue Frame = csevFrame (object_reg); csRef<iEventQueue> eq (csQueryRegistry<iEventQueue> (object_reg)); if (eq != 0) { eq->RegisterListener (static_cast<iEventHandler*> (this), Frame); EventOutlet = eq->CreateEventOutlet (static_cast<iEventPlug*> (this)); bHooked = true; } } else { Report (CS_REPORTER_SEVERITY_NOTIFY, "No operable joystick found\n"); } return EventOutlet.IsValid(); } bool csLinuxJoystick::Close () { if (bHooked) { csRef<iEventQueue> eq (csQueryRegistry<iEventQueue> (object_reg)); if (eq != 0) eq->RemoveListener (static_cast<iEventHandler*> (this)); bHooked = false; } EventOutlet = 0; for (int i=0; i<nJoy; i++) close (joystick[i].fd); delete [] joystick; joystick = 0; nJoy = 0; return true; } void csLinuxJoystick::Report (int severity, const char* msg, ...) { va_list arg; va_start (arg, msg); csReportV (object_reg, severity, "crystalspace.device.joystick.linux", msg, arg); va_end (arg); } } CS_PLUGIN_NAMESPACE_END(JoyLin) <|endoftext|>
<commit_before>// Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // All Rights Reserved. // // Author: Daniel Ford #include "sampler.h" #include <algorithm> // For min() #include <cmath> using std::min; // The approximate gap in bytes between sampling actions. // I.e., we take one sample approximately once every // tcmalloc_sample_parameter bytes of allocation // i.e. about once every 512KB. #ifdef NO_TCMALLOC_SAMPLES DEFINE_int64(tcmalloc_sample_parameter, 0, "Unused: code is compiled with NO_TCMALLOC_SAMPLES"); #else DEFINE_int64(tcmalloc_sample_parameter, EnvToInt64("TCMALLOC_SAMPLE_PARAMETER", 1<<19), "The approximate gap in bytes between sampling actions. " "This must be between 1 and 1<<58."); // Note: there are other places in this file where the number 19 occurs. #endif namespace tcmalloc { // Statics for Sampler double Sampler::log_table_[1<<kFastlogNumBits]; // Populate the lookup table for FastLog2. // This approximates the log2 curve with a step function. // Steps have height equal to log2 of the mid-point of the step. void Sampler::PopulateFastLog2Table() { for (int i = 0; i < (1<<kFastlogNumBits); i++) { log_table_[i] = (log(1.0 + static_cast<double>(i+0.5)/(1<<kFastlogNumBits)) / log(2.0)); } } int Sampler::GetSamplePeriod() { return FLAGS_tcmalloc_sample_parameter; } // Run this before using your sampler void Sampler::Init(uint32_t seed) { // Initialize PRNG if (seed != 0) { rnd_ = seed; } else { rnd_ = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(this)); if (rnd_ == 0) { rnd_ = 1; } } // Step it forward 20 times for good measure for (int i = 0; i < 20; i++) { rnd_ = NextRandom(rnd_); } // Initialize counter bytes_until_sample_ = PickNextSamplingPoint(); } // Initialize the Statics for the Sampler class void Sampler::InitStatics() { PopulateFastLog2Table(); } // Generates a geometric variable with the specified mean (512K by default). // This is done by generating a random number between 0 and 1 and applying // the inverse cumulative distribution function for an exponential. // Specifically: Let m be the inverse of the sample period, then // the probability distribution function is m*exp(-mx) so the CDF is // p = 1 - exp(-mx), so // q = 1 - p = exp(-mx) // log_e(q) = -mx // -log_e(q)/m = x // log_2(q) * (-log_e(2) * 1/m) = x // In the code, q is actually in the range 1 to 2**26, hence the -26 below size_t Sampler::PickNextSamplingPoint() { rnd_ = NextRandom(rnd_); // Take the top 26 bits as the random number // (This plus the 1<<58 sampling bound give a max possible step of // 5194297183973780480 bytes.) const uint64_t prng_mod_power = 48; // Number of bits in prng // The uint32_t cast is to prevent a (hard-to-reproduce) NAN // under piii debug for some binaries. double q = static_cast<uint32_t>(rnd_ >> (prng_mod_power - 26)) + 1.0; // Put the computed p-value through the CDF of a geometric. // For faster performance (save ~1/20th exec time), replace // min(0.0, FastLog2(q) - 26) by (Fastlog2(q) - 26.000705) // The value 26.000705 is used rather than 26 to compensate // for inaccuracies in FastLog2 which otherwise result in a // negative answer. return static_cast<size_t>(min(0.0, (FastLog2(q) - 26)) * (-log(2.0) * FLAGS_tcmalloc_sample_parameter) + 1); } } // namespace tcmalloc <commit_msg>Disable TCMalloc heap sampling. BUG=38960,40149<commit_after>// Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // All Rights Reserved. // // Author: Daniel Ford #include "sampler.h" #include <algorithm> // For min() #include <cmath> using std::min; // The approximate gap in bytes between sampling actions. // I.e., we take one sample approximately once every // tcmalloc_sample_parameter bytes of allocation // i.e. about once every 512KB. #ifdef NO_TCMALLOC_SAMPLES DEFINE_int64(tcmalloc_sample_parameter, 0, "Unused: code is compiled with NO_TCMALLOC_SAMPLES"); #else DEFINE_int64(tcmalloc_sample_parameter, EnvToInt64("TCMALLOC_SAMPLE_PARAMETER", 0), "The approximate gap in bytes between sampling actions. " "This must be between 1 and 1<<58."); // Note: there are other places in this file where the number 19 occurs. #endif namespace tcmalloc { // Statics for Sampler double Sampler::log_table_[1<<kFastlogNumBits]; // Populate the lookup table for FastLog2. // This approximates the log2 curve with a step function. // Steps have height equal to log2 of the mid-point of the step. void Sampler::PopulateFastLog2Table() { for (int i = 0; i < (1<<kFastlogNumBits); i++) { log_table_[i] = (log(1.0 + static_cast<double>(i+0.5)/(1<<kFastlogNumBits)) / log(2.0)); } } int Sampler::GetSamplePeriod() { return FLAGS_tcmalloc_sample_parameter; } // Run this before using your sampler void Sampler::Init(uint32_t seed) { // Initialize PRNG if (seed != 0) { rnd_ = seed; } else { rnd_ = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(this)); if (rnd_ == 0) { rnd_ = 1; } } // Step it forward 20 times for good measure for (int i = 0; i < 20; i++) { rnd_ = NextRandom(rnd_); } // Initialize counter bytes_until_sample_ = PickNextSamplingPoint(); } // Initialize the Statics for the Sampler class void Sampler::InitStatics() { PopulateFastLog2Table(); } // Generates a geometric variable with the specified mean (512K by default). // This is done by generating a random number between 0 and 1 and applying // the inverse cumulative distribution function for an exponential. // Specifically: Let m be the inverse of the sample period, then // the probability distribution function is m*exp(-mx) so the CDF is // p = 1 - exp(-mx), so // q = 1 - p = exp(-mx) // log_e(q) = -mx // -log_e(q)/m = x // log_2(q) * (-log_e(2) * 1/m) = x // In the code, q is actually in the range 1 to 2**26, hence the -26 below size_t Sampler::PickNextSamplingPoint() { rnd_ = NextRandom(rnd_); // Take the top 26 bits as the random number // (This plus the 1<<58 sampling bound give a max possible step of // 5194297183973780480 bytes.) const uint64_t prng_mod_power = 48; // Number of bits in prng // The uint32_t cast is to prevent a (hard-to-reproduce) NAN // under piii debug for some binaries. double q = static_cast<uint32_t>(rnd_ >> (prng_mod_power - 26)) + 1.0; // Put the computed p-value through the CDF of a geometric. // For faster performance (save ~1/20th exec time), replace // min(0.0, FastLog2(q) - 26) by (Fastlog2(q) - 26.000705) // The value 26.000705 is used rather than 26 to compensate // for inaccuracies in FastLog2 which otherwise result in a // negative answer. return static_cast<size_t>(min(0.0, (FastLog2(q) - 26)) * (-log(2.0) * FLAGS_tcmalloc_sample_parameter) + 1); } } // namespace tcmalloc <|endoftext|>
<commit_before> #include <davix.hpp> DAVIX_C_DECL_BEGIN using namespace Davix; /// @brief clear a davix error object and release its memory, and set the error pointer to NULL /// void davix_error_clear(davix_error_t* ptr_err){ DavixError::clearError((DavixError**) ptr_err); } /// @brief create a new davix error object /// void davix_error_setup(davix_error_t* ptr_err, const char* scope, int status_code, const char* msg){ DavixError::setupError((DavixError**) ptr_err, scope, (Davix::StatusCode::Code)status_code, msg); } const char* davix_error_msg(davix_error_t err){ return ((DavixError*) err)->getErrMsg().c_str(); } int davix_error_code(davix_error_t err){ return ((DavixError*) err)->getStatus(); } const char* davix_error_scope(davix_error_t err){ return NULL; // TODO } void davix_error_propagate(davix_error_t* newErr, davix_error_t oldErr ){ DavixError::propagateError((DavixError**)newErr, (DavixError*) oldErr); } DAVIX_DIR* davix_posix_opendir(davix_sess_t sess, davix_params_t _params, const char* url, davix_error_t* err){ davix_return_val_if_fail(sess != NULL, NULL); DAVIX_DIR* ret = NULL; Davix::DavPosix p((Davix::Context*)(sess)); Davix::RequestParams * params = (Davix::RequestParams*) (_params); ret= p.opendir(params,url, (Davix::DavixError**) err); return ret; } int davix_posix_closedir(davix_sess_t sess, DAVIX_DIR* d, davix_error_t* err){ davix_return_val_if_fail(sess != NULL,-1); Davix::DavPosix p((Davix::Context*)(sess)); return p.closedir(d,(Davix::DavixError**) err); } struct dirent* davix_posix_readdir(davix_sess_t sess, DAVIX_DIR* d, davix_error_t* err){ davix_return_val_if_fail(sess != NULL,NULL); struct dirent* ret = NULL; Davix::DavPosix p((Davix::Context*)(sess)); if(d){ ret= p.readdir(d, (Davix::DavixError**) err); } return ret; } int davix_posix_mkdir(davix_sess_t sess, davix_params_t _params, const char* url, mode_t right, davix_error_t* err){ davix_return_val_if_fail(sess != NULL && url != NULL,-1); Davix::DavPosix p((Davix::Context*)(sess)); Davix::RequestParams * params = (Davix::RequestParams*) (_params); return p.mkdir(params,url, right, (Davix::DavixError**) err); } int davix_posix_unlink(davix_sess_t sess, davix_params_t _params, const char* url, davix_error_t* err){ davix_return_val_if_fail(sess != NULL && url != NULL,-1); Davix::DavPosix p((Davix::Context*)(sess)); Davix::RequestParams * params = (Davix::RequestParams*) (_params); return p.unlink(params, url, (Davix::DavixError**) err); } int davix_posix_rmdir(davix_sess_t sess, davix_params_t _params, const char* url, davix_error_t* err){ davix_return_val_if_fail(sess != NULL && url != NULL,-1); Davix::DavPosix p((Davix::Context*)(sess)); Davix::RequestParams * params = (Davix::RequestParams*) (_params); return p.rmdir(params, url, (Davix::DavixError**) err); } int davix_posix_stat(davix_sess_t sess, davix_params_t _params, const char* url, struct stat * st, davix_error_t* err){ davix_return_val_if_fail(sess != NULL,-1); Davix::DavPosix p((Davix::Context*)(sess)); Davix::RequestParams * params = (Davix::RequestParams*) (_params); return p.stat(params,url, st, (Davix::DavixError**) err); } //////////////////////////////////////////////// //////////////////////////////////////////////// ///// C bindings //////////////////////////////////////////////// //////////////////////////////////////////////// int davix_params_set_ssl_check(davix_params_t params, bool ssl_check, davix_error_t* err){ davix_return_val_if_fail(params != NULL, -1); Davix::RequestParams* p = (Davix::RequestParams*)(params); p->setSSLCAcheck(ssl_check); return 0; } davix_params_t davix_params_new(){ return (struct davix_request_params*) new Davix::RequestParams(); } davix_params_t davix_params_copy(davix_params_t p){ return (struct davix_request_params*) new Davix::RequestParams(*(Davix::RequestParams*) p); } void davix_params_free(davix_params_t p){ if(p){ delete ((Davix::RequestParams*) p); } } bool davix_params_get_keep_alive(davix_params_t params){ assert(params); return ((Davix::RequestParams*) params)->getKeepAlive(); } /// enable or disable http keep alive void davix_params_set_keep_alive(davix_params_t params, bool keep_alive){ assert(params); ((Davix::RequestParams*) params)->setKeepAlive(keep_alive); } void davix_params_set_protocol(davix_params_t params, davix_request_protocol_t protocol){ assert(params); ((Davix::RequestParams*) params)->setProtocol(protocol); } davix_request_protocol_t davix_params_get_protocol(davix_params_t params){ assert(params); return ((Davix::RequestParams*) params)->getProtocol(); } void davix_params_set_trans_redirect(davix_params_t params, bool redirection){ assert(params); ((Davix::RequestParams*) params)->setTransparentRedirectionSupport(redirection); } bool davix_params_get_trans_redirect(davix_params_t params){ assert(params); return ((Davix::RequestParams*) params)->getTransparentRedirectionSupport(); } void davix_params_set_user_agent(davix_params_t params, const char* user_agent){ assert(params && user_agent); ((Davix::RequestParams*) params)->setUserAgent(user_agent); } const char* davix_params_get_user_agent(davix_params_t params){ assert(params); return ((Davix::RequestParams*) params)->getUserAgent().c_str(); } void davix_params_set_conn_timeout(davix_params_t params, unsigned int timeout){ assert(params); struct timespec t; t.tv_sec = timeout; t.tv_nsec =0; return ((Davix::RequestParams*) params)->setConnectionTimeout(&t); } unsigned int davix_params_get_conn_timeout(davix_params_t params){ assert(params); return ((Davix::RequestParams*) params)->getConnectionTimeout()->tv_sec; } void davix_params_set_ops_timeout(davix_params_t params, unsigned int timeout){ assert(params); struct timespec t; t.tv_sec = timeout; t.tv_nsec =0; return ((Davix::RequestParams*) params)->setOperationTimeout(&t); } unsigned int davix_params_get_ops_timeout(davix_params_t params){ assert(params); return ((Davix::RequestParams*) params)->getOperationTimeout()->tv_sec; } void davix_params_set_client_cert_X509(davix_params_t params, davix_x509_cert_t cred){ assert(params && cred); ((Davix::RequestParams*) params)->setClientCertX509(*(Davix::X509Credential*) cred); } davix_x509_cert_t davix_params_get_client_cert_X509(davix_params_t params){ assert(params); return (davix_x509_cert_t) &((Davix::RequestParams*) params)->getClientCertX509(); } /// set login/password for HTTP Authentication void davix_params_set_login_passwd(davix_params_t params, const char* login, const char* password){ assert(params && login && password); ((Davix::RequestParams*) params)->setClientLoginPassword(login, password); } davix_x509_cert_t davix_x509_cert_new(){ return (davix_x509_cert_t) new Davix::X509Credential(); } /// return true if certificate container contain a valid credential, else false bool davix_x509_cert_has_cert(davix_x509_cert_t cred){ assert(cred); return ((Davix::X509Credential*) cred)->hasCert(); } /// load a pkcs12 certificate int davix_x509_cert_load_from_p12(davix_x509_cert_t cred, const char * path, const char* passwd, davix_error_t* err){ assert(cred && path); return ((Davix::X509Credential*) cred)->loadFromFileP12(path, ((passwd)?(passwd):""), (Davix::DavixError**)err); } /// free a container for X509 certificate void davix_x509_cert_free(davix_x509_cert_t cred){ if(cred) delete (Davix::X509Credential*) cred; } /** * @endcond **/ using namespace Davix; struct davix_uri_s; davix_uri_t davix_uri_new(const char* url){ return (davix_uri_t) new Uri(url); } davix_uri_t davix_uri_copy(davix_uri_t orig_uri){ assert(orig_uri != NULL); Uri* myself = (Uri*) orig_uri; return (davix_uri_t) new Uri(*myself); } void davix_uri_free(davix_uri_t duri){ if(duri) delete ((Uri*) duri); } int davix_uri_get_port(davix_uri_t duri){ assert(duri != NULL); return ((Uri*) duri)->getPort(); } const char* davix_uri_get_string(davix_uri_t duri){ assert(duri != NULL); Uri* myself = (Uri*) duri; return ((myself->getString().empty() == false)?(myself->getString().c_str()):NULL); } const char* davix_uri_get_path(davix_uri_t duri){ assert(duri != NULL); Uri* myself = (Uri*) duri; return ((myself->getPath().empty() == false)?(myself->getPath().c_str()):NULL); } const char* davix_uri_get_host(davix_uri_t duri){ assert(duri != NULL); Uri* myself = (Uri*) duri; return ((myself->getHost().empty() == false)?(myself->getHost().c_str()):NULL); } const char* davix_uri_get_path_and_query(davix_uri_t duri){ assert(duri != NULL); Uri* myself = (Uri*) duri; return ((myself->getPathAndQuery().empty() == false)?(myself->getPathAndQuery().c_str()):NULL); } const char* davix_uri_get_protocol(davix_uri_t duri){ assert(duri != NULL); Uri* myself = (Uri*) duri; return ((myself->getProtocol().empty() == false)?(myself->getProtocol().c_str()):NULL); } davix_status_t davix_uri_get_status(davix_uri_t duri){ assert(duri != NULL); Uri* myself = (Uri*) duri; return ((davix_status_t) myself->getStatus()); } DAVIX_C_DECL_END <commit_msg>- remove wrapper c old file<commit_after><|endoftext|>
<commit_before>#define BOOST_TEST_MODULE FastFourierTransform #include <boost/test/unit_test.hpp> #ifdef HAVE_FFTW # include <fftw3.h> #endif #include "context_setup.hpp" BOOST_AUTO_TEST_CASE(transform_expression) { const size_t N = 1024; std::vector<cl::CommandQueue> queue(1, ctx.queue(0)); vex::vector<cl_float> data(queue, N); vex::FFT<cl_float> fft(queue, N); // should compile data += fft(data * data) * 5; } BOOST_AUTO_TEST_CASE(check_correctness) { const size_t N = 1024; std::vector<cl::CommandQueue> queue(1, ctx.queue(0)); vex::vector<cl_float> in (queue, N); vex::vector<cl_float2> out (queue, N); vex::vector<cl_float> back(queue, N); vex::Random<cl_float> rnd; in = rnd(vex::element_index(), std::rand()); vex::FFT<cl_float, cl_float2> fft (queue, N); vex::FFT<cl_float2, cl_float > ifft(queue, N, vex::inverse); out = fft (in ); back = ifft(out); vex::Reductor<cl_float, vex::SUM> sum(queue); BOOST_CHECK(std::sqrt(sum(pow(in - back, 2.0f)) / N) < 1e-3); } #ifdef HAVE_FFTW void test(const vex::Context &ctx, std::vector<size_t> ns) { std::cout << ns[0]; for(size_t i = 1; i < ns.size(); i++) { std::cout << 'x' << ns[i]; } std::cout << std::endl; std::vector<cl::CommandQueue> queue(1, ctx.queue(0)); size_t n = std::accumulate(ns.begin(), ns.end(), 1UL, std::multiplies<size_t>()); // random data. std::vector<double> inp_h = random_vector(2 * n); // reference. std::vector<double> ref_h(2 * n); { std::vector<int> nsi(ns.begin(), ns.end()); fftw_plan p1 = fftw_plan_dft(nsi.size(), nsi.data(), reinterpret_cast<fftw_complex*>(inp_h.data()), reinterpret_cast<fftw_complex*>(ref_h.data()), FFTW_FORWARD, FFTW_ESTIMATE); fftw_execute(p1); fftw_destroy_plan(p1); } // test vex::vector<cl_double2> inp (queue, n, reinterpret_cast<cl_double2*>(inp_h.data())); vex::vector<cl_double2> ref (queue, n, reinterpret_cast<cl_double2*>(ref_h.data())); vex::vector<cl_double2> out (queue, n); vex::vector<cl_double2> back(queue, n); vex::FFT<cl_double2> fft (queue, ns); vex::FFT<cl_double2> ifft(queue, ns, vex::inverse); out = fft (inp); back = ifft(out); auto rms = [&](const vex::vector<cl_double2> &a, const vex::vector<cl_double2> &b) { static vex::Reductor<double, vex::SUM> sum(queue); return std::sqrt(sum(dot(a - b, a - b))) / std::sqrt(sum(dot(b, b))); }; BOOST_CHECK_SMALL(rms(out, ref), 1e-8); BOOST_CHECK_SMALL(rms(back, inp), 1e-8); } // random dimension, mostly 1. size_t random_dim(double p, double s) { static std::default_random_engine rng( std::rand() ); static std::uniform_real_distribution<double> rnd(0.0, 1.0); return 1 + static_cast<size_t>( s * std::pow(rnd(rng), p) ); } BOOST_AUTO_TEST_CASE(test_dimensions) { const size_t max = 1 << 20; vex::fft::planner p; for(size_t i = 0; i < 100 ; ++i) { // random number of dimensions, mostly 1. size_t dims = random_dim(3, 5); // random size. std::vector<size_t> n; size_t d_max = std::pow(max, 1.0 / dims); size_t total = 1; for(size_t d = 0 ; d < dims ; d++) { size_t sz = random_dim(dims == 1 ? 3 : 1, d_max); if(rand() % 3 != 0) sz = p.best_size(sz); n.push_back(sz); total *= sz; } // run if(total <= max) test(ctx, n); } } #endif BOOST_AUTO_TEST_SUITE_END() <commit_msg>Reduce time spent in FFT test<commit_after>#define BOOST_TEST_MODULE FastFourierTransform #include <boost/test/unit_test.hpp> #ifdef HAVE_FFTW # include <fftw3.h> #endif #include "context_setup.hpp" BOOST_AUTO_TEST_CASE(transform_expression) { const size_t N = 1024; std::vector<cl::CommandQueue> queue(1, ctx.queue(0)); vex::vector<cl_float> data(queue, N); vex::FFT<cl_float> fft(queue, N); // should compile data += fft(data * data) * 5; } BOOST_AUTO_TEST_CASE(check_correctness) { const size_t N = 1024; std::vector<cl::CommandQueue> queue(1, ctx.queue(0)); vex::vector<cl_float> in (queue, N); vex::vector<cl_float2> out (queue, N); vex::vector<cl_float> back(queue, N); vex::Random<cl_float> rnd; in = rnd(vex::element_index(), std::rand()); vex::FFT<cl_float, cl_float2> fft (queue, N); vex::FFT<cl_float2, cl_float > ifft(queue, N, vex::inverse); out = fft (in ); back = ifft(out); vex::Reductor<cl_float, vex::SUM> sum(queue); BOOST_CHECK(std::sqrt(sum(pow(in - back, 2.0f)) / N) < 1e-3); } #ifdef HAVE_FFTW void test(const vex::Context &ctx, std::vector<size_t> ns) { std::cout << ns[0]; for(size_t i = 1; i < ns.size(); i++) { std::cout << 'x' << ns[i]; } std::cout << std::endl; std::vector<cl::CommandQueue> queue(1, ctx.queue(0)); size_t n = std::accumulate(ns.begin(), ns.end(), 1UL, std::multiplies<size_t>()); // random data. std::vector<double> inp_h = random_vector(2 * n); // reference. std::vector<double> ref_h(2 * n); { std::vector<int> nsi(ns.begin(), ns.end()); fftw_plan p1 = fftw_plan_dft(nsi.size(), nsi.data(), reinterpret_cast<fftw_complex*>(inp_h.data()), reinterpret_cast<fftw_complex*>(ref_h.data()), FFTW_FORWARD, FFTW_ESTIMATE); fftw_execute(p1); fftw_destroy_plan(p1); } // test vex::vector<cl_double2> inp (queue, n, reinterpret_cast<cl_double2*>(inp_h.data())); vex::vector<cl_double2> ref (queue, n, reinterpret_cast<cl_double2*>(ref_h.data())); vex::vector<cl_double2> out (queue, n); vex::vector<cl_double2> back(queue, n); vex::FFT<cl_double2> fft (queue, ns); vex::FFT<cl_double2> ifft(queue, ns, vex::inverse); out = fft (inp); back = ifft(out); auto rms = [&](const vex::vector<cl_double2> &a, const vex::vector<cl_double2> &b) { static vex::Reductor<double, vex::SUM> sum(queue); return std::sqrt(sum(dot(a - b, a - b))) / std::sqrt(sum(dot(b, b))); }; BOOST_CHECK_SMALL(rms(out, ref), 1e-8); BOOST_CHECK_SMALL(rms(back, inp), 1e-8); } // random dimension, mostly 1. size_t random_dim(double p, double s) { static std::default_random_engine rng( std::rand() ); static std::uniform_real_distribution<double> rnd(0.0, 1.0); return 1 + static_cast<size_t>( s * std::pow(rnd(rng), p) ); } BOOST_AUTO_TEST_CASE(test_dimensions) { const size_t max = vex::is_cpu(ctx.device(0)) ? 1 << 10 : 1 << 20; vex::fft::planner p; for(size_t i = 0; i < 32; ++i) { // random number of dimensions, mostly 1. size_t dims = random_dim(3, 5); // random size. std::vector<size_t> n; size_t d_max = std::pow(max, 1.0 / dims); size_t total = 1; for(size_t d = 0 ; d < dims ; d++) { size_t sz = random_dim(dims == 1 ? 3 : 1, d_max); if(rand() % 3 != 0) sz = p.best_size(sz); n.push_back(sz); total *= sz; } // run if(total <= max) test(ctx, n); } } #endif BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include "draw_tree.h" struct tree_leaf { string id; unordered_set<int> elements; }; vector<string> node_colors = {"#73B2F9", "#EC7877", "#8ACB69", "#F5DB5D", "#BD80E5", "#F2A253", "#A37242", "#3D73A3", "#43A373", "#724AA4"}; void us_isect(unordered_set<int> &out, const unordered_set<int> &in1, const unordered_set<int> &in2) { out.clear(); if (in2.size() < in1.size()) { us_isect(out, in2, in1); return; } for (unordered_set<int>::const_iterator it = in1.begin(); it != in1.end(); ++it) { if (in2.find(*it) != in2.end()) out.insert(*it); } } void draw_tree_in_dot_file(const binary_matrix& m, string outputFileName) { // this function requires that there are no duplicate columns in the matrix binary_matrix a = m; // a.hide_duplicate_columns(); ofstream outputFile; outputFile.open(outputFileName); outputFile << "digraph {" << endl; vector< tree_leaf > leaves; int next_available_color = 0; map<string,string> color; for (int i = 0; i < a.n_rows; i++) { tree_leaf new_leaf; new_leaf.id = a.row_names[i]; for (int j = 0; j < a.n_columns; j++) { if (a.cell[i][j] == 1) { new_leaf.elements.insert(j); } } leaves.push_back(new_leaf); size_t pos = new_leaf.id.find("_", 0); //store the position of the delimiter string type; if (pos != string::npos) { type = new_leaf.id.substr(0, pos); } else { type = new_leaf.id; } if (color.count(type) == 0) { color[type] = node_colors[next_available_color]; next_available_color++; if (next_available_color == node_colors.size()) { next_available_color = 0; } } outputFile << new_leaf.id << "[shape=box,style=filled,fontsize=28,fillcolor=\"" << color[type] << "\"];" << endl; } int new_node_counter = 0; while (leaves.size() > 1) { unordered_set<int> max_intersection; int max_leaf1, max_leaf2; // find the two leaves with max cardinaliy of intersection for (int i = 0; i < leaves.size(); i++) { for (int j = i + 1; j < leaves.size(); j++) { unordered_set<int> intersection; us_isect(intersection, leaves[i].elements, leaves[j].elements); if (intersection.size() >= max_intersection.size()) { max_intersection = intersection; max_leaf1 = i; max_leaf2 = j; } } } // cout << "Largest intersection is between " << leaves[max_leaf1].id << " and " << leaves[max_leaf2].id << endl; // inserting the parent of these leaves into the tree tree_leaf parent_leaf; //parent_leaf.id = leaves[max_leaf1].id + "_" + leaves[max_leaf2].id; parent_leaf.id = "Int" + to_string(new_node_counter); new_node_counter++; parent_leaf.elements = max_intersection; outputFile << parent_leaf.id << "[shape=point,style=filled,fillcolor=black,label=\"\"];" << endl; string connector = " -> "; if (leaves[max_leaf1].id.find("Int") != string::npos) { connector = " -> "; } outputFile << parent_leaf.id << connector << leaves[max_leaf1].id << "[arrowhead=none];" << endl; if (leaves[max_leaf2].id.find("Int") != string::npos) { outputFile << parent_leaf.id << " -> " << leaves[max_leaf2].id << "[arrowhead=none];" << endl; } else { outputFile << parent_leaf.id << " -> " << leaves[max_leaf2].id << "[arrowhead=none];" << endl; } leaves.push_back(parent_leaf); // removing them from the leaves for (int i = max_leaf2; i < leaves.size() - 1; i++) { leaves[i] = leaves[i + 1]; } leaves.pop_back(); for (int i = max_leaf1; i < leaves.size() - 1; i++) { leaves[i] = leaves[i + 1]; } leaves.pop_back(); } outputFile << "}" << endl; outputFile.close(); }<commit_msg>Fixed a bug in tree construction<commit_after>#include "draw_tree.h" struct tree_leaf { string id; string label; unordered_set<int> elements; }; vector<string> node_colors = {"#73B2F9", "#EC7877", "#8ACB69", "#F5DB5D", "#BD80E5", "#F2A253", "#A37242", "#3D73A3", "#43A373", "#724AA4"}; void us_isect(unordered_set<int> &out, const unordered_set<int> &in1, const unordered_set<int> &in2) { out.clear(); if (in2.size() < in1.size()) { us_isect(out, in2, in1); return; } for (unordered_set<int>::const_iterator it = in1.begin(); it != in1.end(); ++it) { if (in2.find(*it) != in2.end()) out.insert(*it); } } void draw_tree_in_dot_file(const binary_matrix& m, string outputFileName) { // this function requires that there are no duplicate columns in the matrix binary_matrix a = m; // a.hide_duplicate_columns(); string legend = ""; ofstream outputFile; outputFile.open(outputFileName); outputFile << "digraph {" << endl; vector< tree_leaf > leaves; int next_available_color = 0; map<string,string> color; for (int i = 0; i < a.n_rows; i++) { tree_leaf new_leaf; new_leaf.id = a.row_names[i]; new_leaf.label = ""; for (int j = 0; j < a.n_columns; j++) { if (a.cell[i][j] == 1) { new_leaf.elements.insert(j); } } bool new_leaf_is_new = true; // check first if we have another leaf identical to this one for (int j = 0; j < leaves.size(); j++) { // checking if leaf i is identical to new_leaf if (new_leaf.elements == leaves[j].elements) { new_leaf_is_new = false; if (leaves[j].label == "") { leaves[j].label = leaves[j].id; } leaves[j].label += (" = " + new_leaf.id); break; } } if (new_leaf_is_new) { leaves.push_back(new_leaf); } } for (int i = 0; i < leaves.size(); i++) { size_t pos = leaves[i].id.find("_", 0); //store the position of the delimiter string type; if (pos != string::npos) { type = leaves[i].id.substr(0, pos); } else { type = leaves[i].id; } if (color.count(type) == 0) { color[type] = node_colors[next_available_color]; next_available_color++; if (next_available_color == node_colors.size()) { next_available_color = 0; } } outputFile << leaves[i].id << "[label=\"" << leaves[i].id << "\",shape=box,style=filled,fontsize=28,fillcolor=\"" << color[type] << "\"];" << endl; } // getting legend label string legend_label = ""; for (int i = 0; i < leaves.size(); i++) { if (leaves[i].label != "") { legend_label += (leaves[i].label + "\n"); } } if (legend_label != "") { legend_label = "Equalities among split rows:\n" + legend_label; outputFile << "legend[label=\"" << legend_label << "\",shape=box,fontsize=18];" << endl; } int new_node_counter = 0; cout << "INFO: Resulting phylogeny has " << leaves.size() << " leaves" << endl; while (leaves.size() > 1) { unordered_set<int> max_intersection; int max_leaf1, max_leaf2; // find the two leaves with max cardinaliy of intersection for (int i = 0; i < leaves.size(); i++) { for (int j = i + 1; j < leaves.size(); j++) { unordered_set<int> intersection; us_isect(intersection, leaves[i].elements, leaves[j].elements); if (intersection.size() >= max_intersection.size()) { max_intersection = intersection; max_leaf1 = i; max_leaf2 = j; } } } // cout << "Largest intersection is between " << leaves[max_leaf1].id << " and " << leaves[max_leaf2].id << endl; // inserting the parent of these leaves into the tree tree_leaf parent_leaf; //parent_leaf.id = leaves[max_leaf1].id + "_" + leaves[max_leaf2].id; parent_leaf.id = "Int" + to_string(new_node_counter); new_node_counter++; parent_leaf.elements = max_intersection; outputFile << parent_leaf.id << "[shape=point,style=filled,fillcolor=black,label=\"\"];" << endl; string connector = " -> "; if (leaves[max_leaf1].id.find("Int") != string::npos) { connector = " -> "; } outputFile << parent_leaf.id << connector << leaves[max_leaf1].id << "[arrowhead=none];" << endl; if (leaves[max_leaf2].id.find("Int") != string::npos) { outputFile << parent_leaf.id << " -> " << leaves[max_leaf2].id << "[arrowhead=none];" << endl; } else { outputFile << parent_leaf.id << " -> " << leaves[max_leaf2].id << "[arrowhead=none];" << endl; } leaves.push_back(parent_leaf); // removing them from the leaves for (int i = max_leaf2; i < leaves.size() - 1; i++) { leaves[i] = leaves[i + 1]; } leaves.pop_back(); for (int i = max_leaf1; i < leaves.size() - 1; i++) { leaves[i] = leaves[i + 1]; } leaves.pop_back(); } outputFile << "}" << endl; outputFile.close(); }<|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <math.h> #include "elevation.hxx" using namespace std; namespace osmwave { Elevation::Elevation(int south, int west, int north, int east, const string& tilesPath) : south(south), west(west), north(north), east(east), cols(east - west + 1), tileSize(0) { tiles = new int8_t*[(north - south + 1) * cols]; int i = 0; for (int lat = south; lat <= north; lat++) { for (int lon = west; lon <= east; lon++) { ostringstream ss; ss << tilesPath << "/" << (lat >= 0 ? 'N' : 'S') << setw(2) << setfill('0') << abs(lat) << (lon >= 0 ? 'E' : 'W') << setw(3) << abs(lon) << ".hgt"; string filePath = ss.str(); ifstream file(filePath.c_str(), ios::in | ios::binary | ios::ate); if (file.is_open()) { int size = file.tellg(); int currTileSize; switch (size) { case 2884802: currTileSize = 1201; break; case 25934402: currTileSize = 3601; break; default: cerr << "Unknown tile resolution in tile " << filePath << '\n'; } if (tileSize != 0 && tileSize != currTileSize) { cerr << "Warning! Tiles of different resolutions detected. This will not work.\n"; } else { tileSize = currTileSize; } tiles[i] = new int8_t[size]; file.seekg(0, ios::beg); file.read((char*)tiles[i], size); if (!file) { cerr << "Read " << file.gcount() << " of expected " << size << " bytes from " << filePath << "\n"; } //cerr << "Read " << file.gcount() << " bytes from " << filePath << '\n'; file.close(); i++; } else { cerr << "Unable to open file " << ss.str() << '\n'; } } } } Elevation::~Elevation() { int i = 0; for (int lat = south; lat <= north; lat++) { for (int lon = west; lon <= east; lon++) { delete tiles[i++]; } } delete tiles; } double Elevation::getTileValue(int8_t* tile, int index) { return tile[index] << 8 | tile[index + 1]; } double Elevation::elevation(double lat, double lon) { double fLat = floor(lat); double fLon = floor(lon); int tileRow = (int)fLat - south; int tileCol = (int)fLon - west; int8_t* tile = tiles[tileRow * cols + tileCol]; double row = (lat - fLat) * tileSize; double col = (lon - fLon) * tileSize; int rowI = floor(row); int colI = floor(col); int index = ((tileSize - rowI - 1) * tileSize + colI) * 2; double rowFrac = row - rowI; double colFrac = col - colI; double v00 = getTileValue(tile, index); double v10 = getTileValue(tile, index + 2); double v11 = getTileValue(tile, index - tileSize*2 + 2); double v01 = getTileValue(tile, index - tileSize*2); double v1 = v00 + (v10 - v00) * colFrac; double v2 = v01 + (v11 - v01) * colFrac; double result = v1 + (v2 - v1) * rowFrac; //cerr << "lat=" << lat << ", lon=" << lon << ", tileRow=" << tileRow << // ", tileCol=" << tileCol << ", row=" << row << ", col=" << col << // ", index=" << index << // ", v00=" << v00 << ", v10=" << v10 << ", v01=" << v01 << ", v11=" << v11 << ", output=" << result << '\n'; //cerr << (int)tile[index] << ":" << (int)tile[index + 1] << endl; return result; } } <commit_msg>Fix off by one error<commit_after>#include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <math.h> #include "elevation.hxx" using namespace std; namespace osmwave { Elevation::Elevation(int south, int west, int north, int east, const string& tilesPath) : south(south), west(west), north(north), east(east), cols(east - west + 1), tileSize(0) { tiles = new int8_t*[(north - south + 1) * cols]; int i = 0; for (int lat = south; lat <= north; lat++) { for (int lon = west; lon <= east; lon++) { ostringstream ss; ss << tilesPath << "/" << (lat >= 0 ? 'N' : 'S') << setw(2) << setfill('0') << abs(lat) << (lon >= 0 ? 'E' : 'W') << setw(3) << abs(lon) << ".hgt"; string filePath = ss.str(); ifstream file(filePath.c_str(), ios::in | ios::binary | ios::ate); if (file.is_open()) { int size = file.tellg(); int currTileSize; switch (size) { case 2884802: currTileSize = 1201; break; case 25934402: currTileSize = 3601; break; default: cerr << "Unknown tile resolution in tile " << filePath << '\n'; } if (tileSize != 0 && tileSize != currTileSize) { cerr << "Warning! Tiles of different resolutions detected. This will not work.\n"; } else { tileSize = currTileSize; } tiles[i] = new int8_t[size]; file.seekg(0, ios::beg); file.read((char*)tiles[i], size); if (!file) { cerr << "Read " << file.gcount() << " of expected " << size << " bytes from " << filePath << "\n"; } //cerr << "Read " << file.gcount() << " bytes from " << filePath << '\n'; file.close(); i++; } else { cerr << "Unable to open file " << ss.str() << '\n'; } } } } Elevation::~Elevation() { int i = 0; for (int lat = south; lat <= north; lat++) { for (int lon = west; lon <= east; lon++) { delete tiles[i++]; } } delete tiles; } double Elevation::getTileValue(int8_t* tile, int index) { return tile[index] << 8 | tile[index + 1]; } double Elevation::elevation(double lat, double lon) { double fLat = floor(lat); double fLon = floor(lon); int tileRow = (int)fLat - south; int tileCol = (int)fLon - west; int8_t* tile = tiles[tileRow * cols + tileCol]; double row = (lat - fLat) * (tileSize - 1); double col = (lon - fLon) * (tileSize - 1); int rowI = floor(row); int colI = floor(col); int index = ((tileSize - rowI - 1) * tileSize + colI) * 2; double rowFrac = row - rowI; double colFrac = col - colI; double v00 = getTileValue(tile, index); double v10 = getTileValue(tile, index + 2); double v11 = getTileValue(tile, index - tileSize*2 + 2); double v01 = getTileValue(tile, index - tileSize*2); double v1 = v00 + (v10 - v00) * colFrac; double v2 = v01 + (v11 - v01) * colFrac; double result = v1 + (v2 - v1) * rowFrac; //cerr << "lat=" << lat << ", lon=" << lon << ", tileRow=" << tileRow << // ", tileCol=" << tileCol << ", row=" << row << ", col=" << col << // ", index=" << index << // ", v00=" << v00 << ", v10=" << v10 << ", v01=" << v01 << ", v11=" << v11 << ", output=" << result << '\n'; //cerr << (int)tile[index] << ":" << (int)tile[index + 1] << endl; return result; } } <|endoftext|>
<commit_before>/* Copyright (C) 2015 INRA * * 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 INRA_EFYj_EXCEPTION_HPP #define INRA_EFYj_EXCEPTION_HPP #include <stdexcept> #include <string> namespace efyj { class efyj_error : public std::runtime_error { public: efyj_error(const std::string& msg); virtual ~efyj_error(); }; class solver_error : public efyj_error { public: solver_error(const std::string& msg); virtual ~solver_error(); }; struct solver_option_error : solver_error { solver_option_error(const std::string& msg); virtual ~solver_option_error(); }; class xml_parser_error : public efyj_error { public: xml_parser_error(const std::string& msg); xml_parser_error(const std::string& msg, const std::string& filepath); xml_parser_error(const std::string& msg, int line, int column, int error); virtual ~xml_parser_error(); int line() const { return m_line; } int column() const { return m_column; } int internal_error_code() const { return m_internal_error_code; } std::string filepath() const { return m_filepath; } std::string message() const { return m_message; } private: int m_line, m_column; int m_internal_error_code; std::string m_filepath; std::string m_message; }; class csv_parser_error : public efyj_error { public: csv_parser_error(const std::string& msg); csv_parser_error(const std::string& filepath, const std::string& msg); csv_parser_error(std::size_t line, const std::string& filepath, const std::string& msg); csv_parser_error(std::size_t line, std::size_t column, const std::string& filepath, const std::string& msg); virtual ~csv_parser_error(); std::size_t line() const { return m_line; } std::size_t column() const { return m_column; } std::string filepath() const { return m_filepath; } std::string msg() const { return m_msg; } private: std::size_t m_line; std::size_t m_column; std::string m_filepath; std::string m_msg; }; } #endif <commit_msg>exception: switching the solver_option_error from struct into class<commit_after>/* Copyright (C) 2015 INRA * * 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 INRA_EFYj_EXCEPTION_HPP #define INRA_EFYj_EXCEPTION_HPP #include <stdexcept> #include <string> namespace efyj { class efyj_error : public std::runtime_error { public: efyj_error(const std::string& msg); virtual ~efyj_error(); }; class solver_error : public efyj_error { public: solver_error(const std::string& msg); virtual ~solver_error(); }; class solver_option_error : solver_error { public: solver_option_error(const std::string& msg); virtual ~solver_option_error(); }; class xml_parser_error : public efyj_error { public: xml_parser_error(const std::string& msg); xml_parser_error(const std::string& msg, const std::string& filepath); xml_parser_error(const std::string& msg, int line, int column, int error); virtual ~xml_parser_error(); int line() const { return m_line; } int column() const { return m_column; } int internal_error_code() const { return m_internal_error_code; } std::string filepath() const { return m_filepath; } std::string message() const { return m_message; } private: int m_line, m_column; int m_internal_error_code; std::string m_filepath; std::string m_message; }; class csv_parser_error : public efyj_error { public: csv_parser_error(const std::string& msg); csv_parser_error(const std::string& filepath, const std::string& msg); csv_parser_error(std::size_t line, const std::string& filepath, const std::string& msg); csv_parser_error(std::size_t line, std::size_t column, const std::string& filepath, const std::string& msg); virtual ~csv_parser_error(); std::size_t line() const { return m_line; } std::size_t column() const { return m_column; } std::string filepath() const { return m_filepath; } std::string msg() const { return m_msg; } private: std::size_t m_line; std::size_t m_column; std::string m_filepath; std::string m_msg; }; } #endif <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * 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 Initial Developer of the Original Code is * Red Hat, Inc. * Portions created by the Initial Developer are Copyright (C) 2010 the * Initial Developer. All Rights Reserved. * * Contributor(s): David Tardon <dtardon@redhat.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ namespace detail { template<typename T> struct has_clone { template<typename U, U x> struct test; typedef char yes; typedef struct { char a[2]; } no; template<typename U> static yes check_sig(U*, test<U* (U::*)() const, &U::clone>* = 0); template<typename U> static no check_sig(...); static bool const value = sizeof(has_clone<T>::template check_sig<T>(0)) == sizeof(yes); }; template<typename T, bool HasClone> struct cloner { static T* clone(T* const other) { return new T(*other); } }; template<typename T> struct cloner<T, true> { static T* clone(T* const other) { return other->clone(); } }; } /** Creates a new copy of the passed object. If other is 0, just returns 0. Otherwise, if other has function named clone with signature T* (T::*)() const, the function is called. Otherwise, copy constructor is used. @returns 0 or newly allocated object */ template<typename T> T* clone(T* const other) { return other ? ::detail::cloner<T, ::detail::has_clone<T>::value>::clone(other) : 0; } // vim: set sts=4 sw=4 et: <commit_msg>use enum instead of static bool<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * 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 Initial Developer of the Original Code is * Red Hat, Inc. * Portions created by the Initial Developer are Copyright (C) 2010 the * Initial Developer. All Rights Reserved. * * Contributor(s): David Tardon <dtardon@redhat.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ namespace detail { template<typename T> struct has_clone { template<typename U, U x> struct test; typedef char yes; typedef struct { char a[2]; } no; template<typename U> static yes check_sig(U*, test<U* (U::*)() const, &U::clone>* = 0); template<typename U> static no check_sig(...); enum { value = sizeof(has_clone<T>::template check_sig<T>(0)) == sizeof(yes) }; }; template<typename T, bool HasClone> struct cloner { static T* clone(T* const other) { return new T(*other); } }; template<typename T> struct cloner<T, true> { static T* clone(T* const other) { return other->clone(); } }; } /** Creates a new copy of the passed object. If other is 0, just returns 0. Otherwise, if other has function named clone with signature T* (T::*)() const, the function is called. Otherwise, copy constructor is used. @returns 0 or newly allocated object */ template<typename T> T* clone(T* const other) { return other ? ::detail::cloner<T, ::detail::has_clone<T>::value>::clone(other) : 0; } // vim: set sts=4 sw=4 et: <|endoftext|>
<commit_before>// ***************************************************************************** // // Copyright (c) 2015, Southwest Research Institute® (SwRI®) // 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 Southwest Research Institute® (SwRI®) 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 Southwest Research Institute® 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 <mapviz/select_service_dialog.h> #include <QCloseEvent> #include <QHBoxLayout> #include <QLabel> #include <QLineEdit> #include <QListWidget> #include <QMessageBox> #include <QPushButton> #include <QTimerEvent> #include <QVBoxLayout> #include <rosapi/Services.h> #include <rosapi/ServicesForType.h> #include <QtGui/QMessageBox> namespace mapviz { void ServiceUpdaterThread::run() { ros::ServiceClient client; if (allowed_datatype_.empty()) { client = nh_.serviceClient<rosapi::Services>("/rosapi/services"); } else { client = nh_.serviceClient<rosapi::ServicesForType>("/rosapi/services_for_type"); } if (!client.waitForExistence(ros::Duration(1))) { // Check to see whether the rosapi services are actually running. Q_EMIT fetchingFailed(tr("Unable to list ROS services. Is rosapi_node running?")); return; } if (allowed_datatype_.empty()) { rosapi::Services srv; ROS_DEBUG("Listing all services."); if (client.call(srv)) { Q_EMIT servicesFetched(srv.response.services); } } else { rosapi::ServicesForType srv; srv.request.type = allowed_datatype_; ROS_DEBUG("Listing services for type %s", srv.request.type.c_str()); if (client.call(srv)) { Q_EMIT servicesFetched(srv.response.services); } else { // If there are any dead or unreachable nodes that provide services, even if // they're not of the service type we're looking for, the services_for_type // service will have an error and not return anything. Super annoying. Q_EMIT fetchingFailed(tr("Unable to list ROS services. You may have " \ "dead nodes; try running \"rosnode cleanup\".")); } } } std::string SelectServiceDialog::selectService(const std::string& datatype, QWidget* parent) { SelectServiceDialog dialog(datatype, parent); dialog.setDatatypeFilter(datatype); if (dialog.exec() == QDialog::Accepted) { return dialog.selectedService(); } else { return ""; } } SelectServiceDialog::SelectServiceDialog(const std::string& datatype, QWidget* parent) : allowed_datatype_(datatype), ok_button_(new QPushButton("&Ok")), cancel_button_(new QPushButton("&Cancel")), list_widget_(new QListWidget()), name_filter_(new QLineEdit()), QDialog(parent) { QHBoxLayout *filter_box = new QHBoxLayout(); filter_box->addWidget(new QLabel("Filter:")); filter_box->addWidget(name_filter_); QHBoxLayout *button_box = new QHBoxLayout(); button_box->addStretch(1); button_box->addWidget(cancel_button_); button_box->addWidget(ok_button_); QVBoxLayout *vbox = new QVBoxLayout(); vbox->addWidget(list_widget_); vbox->addLayout(filter_box); vbox->addLayout(button_box); setLayout(vbox); // This is ugly, but necessary in order to be able to send a std::vector<std::string> // via a queued signal/slot connection. qRegisterMetaType<ServiceStringVector>("ServiceStringVector"); connect(ok_button_, SIGNAL(clicked(bool)), this, SLOT(accept())); connect(cancel_button_, SIGNAL(clicked(bool)), this, SLOT(reject())); connect(name_filter_, SIGNAL(textChanged(const QString &)), this, SLOT(updateDisplayedServices())); ok_button_->setDefault(true); setWindowTitle("Select service..."); fetch_services_timer_id_ = startTimer(5000); fetchServices(); } SelectServiceDialog::~SelectServiceDialog() { if (worker_thread_) { // If the thread's parent is destroyed before the thread has finished, // it will cause a segmentation fault. We'll wait a few seconds for // it to finish cleanly, and if that doesn't work, try to force it to // die and wait a few more. worker_thread_->wait(5000); if (worker_thread_->isRunning()) { worker_thread_->terminate(); worker_thread_->wait(2000); } } } void SelectServiceDialog::fetchServices() { // If we don't currently have a worker thread or the previous one has // finished, start a new one. if (!worker_thread_ || worker_thread_->isFinished()) { worker_thread_.reset(new ServiceUpdaterThread(nh_, allowed_datatype_, this)); QObject::connect(worker_thread_.get(), SIGNAL(servicesFetched(ServiceStringVector)), this, SLOT(updateKnownServices(ServiceStringVector))); QObject::connect(worker_thread_.get(), SIGNAL(fetchingFailed(const QString)), this, SLOT(displayUpdateError(const QString))); worker_thread_->start(); } } void SelectServiceDialog::updateKnownServices(ServiceStringVector services) { known_services_ = services; updateDisplayedServices(); } void SelectServiceDialog::displayUpdateError(const QString error_msg) { killTimer(fetch_services_timer_id_); QMessageBox mbox(this->parentWidget()); mbox.setIcon(QMessageBox::Warning); mbox.setText(error_msg); mbox.exec(); } std::vector<std::string> SelectServiceDialog::filterServices() { std::vector<std::string> filtered_services; QString filter_text = name_filter_->text(); Q_FOREACH(const std::string& service, known_services_) { if (QString::fromStdString(service).contains(filter_text, Qt::CaseInsensitive)) { filtered_services.push_back(service); } } return filtered_services; } void SelectServiceDialog::updateDisplayedServices() { std::vector<std::string> next_displayed_services = filterServices(); // It's a lot more work to keep track of the additions/removals like // this compared to resetting the QListWidget's items each time, but // it allows Qt to properly track the selection and current items // across updates, which results in much less frustration for the user. std::set<std::string> prev_names; for (size_t i = 0; i < displayed_services_.size(); i++) { prev_names.insert(displayed_services_[i]); } std::set<std::string> next_names; for (size_t i = 0; i < next_displayed_services.size(); i++) { next_names.insert(next_displayed_services[i]); } std::set<std::string> added_names; std::set_difference(next_names.begin(), next_names.end(), prev_names.begin(), prev_names.end(), std::inserter(added_names, added_names.end())); std::set<std::string> removed_names; std::set_difference(prev_names.begin(), prev_names.end(), next_names.begin(), next_names.end(), std::inserter(removed_names, removed_names.end())); // Remove all the removed names size_t removed = 0; for (size_t i = 0; i < displayed_services_.size(); i++) { if (removed_names.count(displayed_services_[i]) == 0) { continue; } QListWidgetItem *item = list_widget_->takeItem(i - removed); delete item; removed++; } // Now we can add the new items. for (size_t i = 0; i < next_displayed_services.size(); i++) { if (added_names.count(next_displayed_services[i]) == 0) { continue; } list_widget_->insertItem(i, QString::fromStdString(next_displayed_services[i])); if (list_widget_->count() == 1) { list_widget_->setCurrentRow(0); } } displayed_services_.swap(next_displayed_services); } void SelectServiceDialog::setDatatypeFilter(const std::string& datatype) { allowed_datatype_ = datatype; updateDisplayedServices(); } std::string SelectServiceDialog::selectedService() const { QModelIndex qt_selection = list_widget_->selectionModel()->currentIndex(); if (qt_selection.isValid()) { int row = qt_selection.row(); if (row < displayed_services_.size()) { return displayed_services_[row]; } } return ""; } void SelectServiceDialog::timerEvent(QTimerEvent* event) { if (event->timerId() == fetch_services_timer_id_) { fetchServices(); } } void SelectServiceDialog::closeEvent(QCloseEvent* event) { // We don't need to keep making requests from the ROS master. killTimer(fetch_services_timer_id_); QDialog::closeEvent(event); } }<commit_msg>Remove unnecessary include<commit_after>// ***************************************************************************** // // Copyright (c) 2015, Southwest Research Institute® (SwRI®) // 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 Southwest Research Institute® (SwRI®) 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 Southwest Research Institute® 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 <mapviz/select_service_dialog.h> #include <QCloseEvent> #include <QHBoxLayout> #include <QLabel> #include <QLineEdit> #include <QListWidget> #include <QMessageBox> #include <QPushButton> #include <QTimerEvent> #include <QVBoxLayout> #include <rosapi/Services.h> #include <rosapi/ServicesForType.h> namespace mapviz { void ServiceUpdaterThread::run() { ros::ServiceClient client; if (allowed_datatype_.empty()) { client = nh_.serviceClient<rosapi::Services>("/rosapi/services"); } else { client = nh_.serviceClient<rosapi::ServicesForType>("/rosapi/services_for_type"); } if (!client.waitForExistence(ros::Duration(1))) { // Check to see whether the rosapi services are actually running. Q_EMIT fetchingFailed(tr("Unable to list ROS services. Is rosapi_node running?")); return; } if (allowed_datatype_.empty()) { rosapi::Services srv; ROS_DEBUG("Listing all services."); if (client.call(srv)) { Q_EMIT servicesFetched(srv.response.services); } } else { rosapi::ServicesForType srv; srv.request.type = allowed_datatype_; ROS_DEBUG("Listing services for type %s", srv.request.type.c_str()); if (client.call(srv)) { Q_EMIT servicesFetched(srv.response.services); } else { // If there are any dead or unreachable nodes that provide services, even if // they're not of the service type we're looking for, the services_for_type // service will have an error and not return anything. Super annoying. Q_EMIT fetchingFailed(tr("Unable to list ROS services. You may have " \ "dead nodes; try running \"rosnode cleanup\".")); } } } std::string SelectServiceDialog::selectService(const std::string& datatype, QWidget* parent) { SelectServiceDialog dialog(datatype, parent); dialog.setDatatypeFilter(datatype); if (dialog.exec() == QDialog::Accepted) { return dialog.selectedService(); } else { return ""; } } SelectServiceDialog::SelectServiceDialog(const std::string& datatype, QWidget* parent) : allowed_datatype_(datatype), ok_button_(new QPushButton("&Ok")), cancel_button_(new QPushButton("&Cancel")), list_widget_(new QListWidget()), name_filter_(new QLineEdit()), QDialog(parent) { QHBoxLayout *filter_box = new QHBoxLayout(); filter_box->addWidget(new QLabel("Filter:")); filter_box->addWidget(name_filter_); QHBoxLayout *button_box = new QHBoxLayout(); button_box->addStretch(1); button_box->addWidget(cancel_button_); button_box->addWidget(ok_button_); QVBoxLayout *vbox = new QVBoxLayout(); vbox->addWidget(list_widget_); vbox->addLayout(filter_box); vbox->addLayout(button_box); setLayout(vbox); // This is ugly, but necessary in order to be able to send a std::vector<std::string> // via a queued signal/slot connection. qRegisterMetaType<ServiceStringVector>("ServiceStringVector"); connect(ok_button_, SIGNAL(clicked(bool)), this, SLOT(accept())); connect(cancel_button_, SIGNAL(clicked(bool)), this, SLOT(reject())); connect(name_filter_, SIGNAL(textChanged(const QString &)), this, SLOT(updateDisplayedServices())); ok_button_->setDefault(true); setWindowTitle("Select service..."); fetch_services_timer_id_ = startTimer(5000); fetchServices(); } SelectServiceDialog::~SelectServiceDialog() { if (worker_thread_) { // If the thread's parent is destroyed before the thread has finished, // it will cause a segmentation fault. We'll wait a few seconds for // it to finish cleanly, and if that doesn't work, try to force it to // die and wait a few more. worker_thread_->wait(5000); if (worker_thread_->isRunning()) { worker_thread_->terminate(); worker_thread_->wait(2000); } } } void SelectServiceDialog::fetchServices() { // If we don't currently have a worker thread or the previous one has // finished, start a new one. if (!worker_thread_ || worker_thread_->isFinished()) { worker_thread_.reset(new ServiceUpdaterThread(nh_, allowed_datatype_, this)); QObject::connect(worker_thread_.get(), SIGNAL(servicesFetched(ServiceStringVector)), this, SLOT(updateKnownServices(ServiceStringVector))); QObject::connect(worker_thread_.get(), SIGNAL(fetchingFailed(const QString)), this, SLOT(displayUpdateError(const QString))); worker_thread_->start(); } } void SelectServiceDialog::updateKnownServices(ServiceStringVector services) { known_services_ = services; updateDisplayedServices(); } void SelectServiceDialog::displayUpdateError(const QString error_msg) { killTimer(fetch_services_timer_id_); QMessageBox mbox(this->parentWidget()); mbox.setIcon(QMessageBox::Warning); mbox.setText(error_msg); mbox.exec(); } std::vector<std::string> SelectServiceDialog::filterServices() { std::vector<std::string> filtered_services; QString filter_text = name_filter_->text(); Q_FOREACH(const std::string& service, known_services_) { if (QString::fromStdString(service).contains(filter_text, Qt::CaseInsensitive)) { filtered_services.push_back(service); } } return filtered_services; } void SelectServiceDialog::updateDisplayedServices() { std::vector<std::string> next_displayed_services = filterServices(); // It's a lot more work to keep track of the additions/removals like // this compared to resetting the QListWidget's items each time, but // it allows Qt to properly track the selection and current items // across updates, which results in much less frustration for the user. std::set<std::string> prev_names; for (size_t i = 0; i < displayed_services_.size(); i++) { prev_names.insert(displayed_services_[i]); } std::set<std::string> next_names; for (size_t i = 0; i < next_displayed_services.size(); i++) { next_names.insert(next_displayed_services[i]); } std::set<std::string> added_names; std::set_difference(next_names.begin(), next_names.end(), prev_names.begin(), prev_names.end(), std::inserter(added_names, added_names.end())); std::set<std::string> removed_names; std::set_difference(prev_names.begin(), prev_names.end(), next_names.begin(), next_names.end(), std::inserter(removed_names, removed_names.end())); // Remove all the removed names size_t removed = 0; for (size_t i = 0; i < displayed_services_.size(); i++) { if (removed_names.count(displayed_services_[i]) == 0) { continue; } QListWidgetItem *item = list_widget_->takeItem(i - removed); delete item; removed++; } // Now we can add the new items. for (size_t i = 0; i < next_displayed_services.size(); i++) { if (added_names.count(next_displayed_services[i]) == 0) { continue; } list_widget_->insertItem(i, QString::fromStdString(next_displayed_services[i])); if (list_widget_->count() == 1) { list_widget_->setCurrentRow(0); } } displayed_services_.swap(next_displayed_services); } void SelectServiceDialog::setDatatypeFilter(const std::string& datatype) { allowed_datatype_ = datatype; updateDisplayedServices(); } std::string SelectServiceDialog::selectedService() const { QModelIndex qt_selection = list_widget_->selectionModel()->currentIndex(); if (qt_selection.isValid()) { int row = qt_selection.row(); if (row < displayed_services_.size()) { return displayed_services_[row]; } } return ""; } void SelectServiceDialog::timerEvent(QTimerEvent* event) { if (event->timerId() == fetch_services_timer_id_) { fetchServices(); } } void SelectServiceDialog::closeEvent(QCloseEvent* event) { // We don't need to keep making requests from the ROS master. killTimer(fetch_services_timer_id_); QDialog::closeEvent(event); } } <|endoftext|>
<commit_before>#include "LiquidCrystalExt.h" #include <stdio.h> #include <string.h> #include <inttypes.h> #include "LineDriver.h" #include "WProgram.h" /* When the display powers up, it is configured as follows: * * 1. Display clear * 2. Function set: * DL = 1; 8-bit interface data * N = 0; 1-line display * F = 0; 5x8 dot character font * 3. Display on/off control: * D = 0; Display off * C = 0; Cursor off * B = 0; Blinking off * 4. Entry mode set: * I/D = 1; Increment by 1 * S = 0; No shift * * Note, however, that resetting the Arduino doesn't reset the LCD, so we * can't assume that its in that state when a sketch starts (and the * LiquidCrystal constructor is called). */ void LiquidCrystalBase::begin(uint8_t cols, uint8_t lines, uint8_t dotsize) { if (lines > 1) _displayfunction |= LCD_2LINE; _numlines = lines; _currline = 0; /* For some 1 line displays you can select a 10 pixel high font */ if ((dotsize != 0) && (lines == 1)) _displayfunction |= LCD_5x10DOTS; config(); /* Put the LCD into 4 bit or 8 bit mode */ if (! (_displayfunction & LCD_8BITMODE)) { /* This is according to the hitachi HD44780 datasheet figure 24, pg 46 */ /* We start in 8bit mode, try to set 4 bit mode */ write4bits(0x03); delayMicroseconds(4500); // wait min 4.1ms /* Second try */ write4bits(0x03); delayMicroseconds(4500); // wait min 4.1ms /* Third go! */ write4bits(0x03); delayMicroseconds(150); /* Finally, set to 4-bit interface */ write4bits(0x02); } else { /* This is according to the hitachi HD44780 datasheet page 45 figure 23 */ /* Send function set command sequence */ command(LCD_FUNCTIONSET | _displayfunction); delayMicroseconds(4500); // wait more than 4.1ms /* Second try */ command(LCD_FUNCTIONSET | _displayfunction); delayMicroseconds(150); /* Third go */ command(LCD_FUNCTIONSET | _displayfunction); } /* Finally, set # lines, font size, etc. */ command(LCD_FUNCTIONSET | _displayfunction); /* Turn the display on with no cursor or blinking default */ _displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF; display(); /* Clear it off */ clear(); /* Initialize to default text direction (for romance languages) */ _displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT; /* Set the entry mode */ command(LCD_ENTRYMODESET | _displaymode); } /*----- High level commands, user API -----*/ void LiquidCrystalBase::clear() { command(LCD_CLEARDISPLAY); // clear display, set cursor position to zero delayMicroseconds(2000); // this command takes a long time! } void LiquidCrystalBase::home() { command(LCD_RETURNHOME); // set cursor position to zero delayMicroseconds(2000); // this command takes a long time! } void LiquidCrystalBase::setCursor(uint8_t col, uint8_t row) { static const int row_offsets[] = { 0x00, 0x40, 0x14, 0x54 }; if (row > _numlines) row = _numlines - 1; // we count rows starting with zero command(LCD_SETDDRAMADDR | (col + row_offsets[row])); } /* Turn the display on/off (quickly) */ void LiquidCrystalBase::noDisplay() { _displaycontrol &= ~LCD_DISPLAYON; command(LCD_DISPLAYCONTROL | _displaycontrol); } void LiquidCrystalBase::display() { _displaycontrol |= LCD_DISPLAYON; command(LCD_DISPLAYCONTROL | _displaycontrol); } /* Turns the underline cursor on/off */ void LiquidCrystalBase::noCursor() { _displaycontrol &= ~LCD_CURSORON; command(LCD_DISPLAYCONTROL | _displaycontrol); } void LiquidCrystalBase::cursor() { _displaycontrol |= LCD_CURSORON; command(LCD_DISPLAYCONTROL | _displaycontrol); } /* Turn on and off the blinking cursor */ void LiquidCrystalBase::noBlink() { _displaycontrol &= ~LCD_BLINKON; command(LCD_DISPLAYCONTROL | _displaycontrol); } void LiquidCrystalBase::blink() { _displaycontrol |= LCD_BLINKON; command(LCD_DISPLAYCONTROL | _displaycontrol); } /* These commands scroll the display without changing the RAM */ void LiquidCrystalBase::scrollDisplayLeft(void) { command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT); } void LiquidCrystalBase::scrollDisplayRight(void) { command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT); } /* This is for text that flows Left to Right */ void LiquidCrystalBase::leftToRight(void) { _displaymode |= LCD_ENTRYLEFT; command(LCD_ENTRYMODESET | _displaymode); } /* This is for text that flows Right to Left */ void LiquidCrystalBase::rightToLeft(void) { _displaymode &= ~LCD_ENTRYLEFT; command(LCD_ENTRYMODESET | _displaymode); } /* This will 'right justify' text from the cursor */ void LiquidCrystalBase::autoscroll(void) { _displaymode |= LCD_ENTRYSHIFTINCREMENT; command(LCD_ENTRYMODESET | _displaymode); } /* This will 'left justify' text from the cursor */ void LiquidCrystalBase::noAutoscroll(void) { _displaymode &= ~LCD_ENTRYSHIFTINCREMENT; command(LCD_ENTRYMODESET | _displaymode); } /* Allows us to fill the first 8 CGRAM locations with custom characters */ void LiquidCrystalBase::createChar(uint8_t location, uint8_t charmap[]) { location &= 0x7; // we only have 8 locations 0-7 command(LCD_SETCGRAMADDR | (location << 3)); for (int i = 0; i < 8; ++i) write(charmap[i]); } /*----- Mid level commands, for sending data/commands -----*/ inline void LiquidCrystalBase::command(uint8_t value) { send(value, LOW); } inline void LiquidCrystalBase::write(uint8_t value) { send(value, HIGH); } /*----- LiquidCrystal implementation -----*/ LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7, LineDriver *line_driver) { init(0, rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7, line_driver); } LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t enable, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7, LineDriver *line_driver) { init(0, rs, 255, enable, d0, d1, d2, d3, d4, d5, d6, d7, line_driver); } LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, LineDriver *line_driver) { init(1, rs, rw, enable, d0, d1, d2, d3, 0, 0, 0, 0, line_driver); } LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t enable, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, LineDriver *line_driver) { init(1, rs, 255, enable, d0, d1, d2, d3, 0, 0, 0, 0, line_driver); } void LiquidCrystal::init(uint8_t fourbitmode, uint8_t rs, uint8_t rw, uint8_t enable, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7, LineDriver *line_driver) { pins = line_driver; if (!pins) pins = DefaultLineDriver::getInstance(); _rs_pin = rs; _rw_pin = rw; _enable_pin = enable; _data_pins[0] = d0; _data_pins[1] = d1; _data_pins[2] = d2; _data_pins[3] = d3; _data_pins[4] = d4; _data_pins[5] = d5; _data_pins[6] = d6; _data_pins[7] = d7; pins->pinConfig(_rs_pin, OUTPUT); // we can save 1 pin by not using RW. Indicate by passing 255 instead of pin# if (_rw_pin != 255) pins->pinConfig(_rw_pin, OUTPUT); pins->pinConfig(_enable_pin, OUTPUT); if (fourbitmode) _displayfunction = LCD_4BITMODE | LCD_1LINE | LCD_5x8DOTS; else _displayfunction = LCD_8BITMODE | LCD_1LINE | LCD_5x8DOTS; begin(16, 1); } /*----- Low level data pushing commands -----*/ void LiquidCrystal::config() { for (int i = 0; i < 8; ++i) { pins->pinConfig(_data_pins[i], OUTPUT); pins->pinWrite(_data_pins[i], LOW); } /* SEE PAGE 45/46 FOR INITIALIZATION SPECIFICATION! * according to datasheet, we need at least 40ms after power rises above 2.7V * before sending commands. Arduino can turn on way befer 4.5V so we'll wait 50 */ delayMicroseconds(50000); /* Now we pull both RS and R/W low to begin commands */ pins->pinWrite(_rs_pin, LOW); pins->pinWrite(_enable_pin, LOW); if (_rw_pin != -1) pins->pinWrite(_rw_pin, LOW); } /* Write either command or data, with automatic 4/8-bit selection */ void LiquidCrystal::send(uint8_t value, uint8_t mode) { pins->pinWrite(_rs_pin, mode); /* If there is a RW pin indicated, set it low to write */ if (_rw_pin != 255) pins->pinWrite(_rw_pin, LOW); if (_displayfunction & LCD_8BITMODE) write8bits(value); else { write4bits(value >> 4); write4bits(value); } } void LiquidCrystal::pulseEnable(void) { pins->pinWrite(_enable_pin, LOW); delayMicroseconds(1); pins->pinWrite(_enable_pin, HIGH); delayMicroseconds(1); // enable pulse must be >450ns pins->pinWrite(_enable_pin, LOW); delayMicroseconds(100); // commands need > 37us to settle } void LiquidCrystal::write4bits(uint8_t value) { for (int i = 0; i < 4; ++i) { pins->pinConfig(_data_pins[i], OUTPUT); pins->pinWrite(_data_pins[i], (value >> i) & 0x01); } pulseEnable(); } void LiquidCrystal::write8bits(uint8_t value) { for (int i = 0; i < 8; ++i) { pins->pinConfig(_data_pins[i], OUTPUT); pins->pinWrite(_data_pins[i], (value >> i) & 0x01); } pulseEnable(); } <commit_msg>Renamed LineDriver's functions, fixed references to them (forgot to do it in previous commit)<commit_after>#include "LiquidCrystalExt.h" #include <stdio.h> #include <string.h> #include <inttypes.h> #include "LineDriver.h" #include "WProgram.h" /* When the display powers up, it is configured as follows: * * 1. Display clear * 2. Function set: * DL = 1; 8-bit interface data * N = 0; 1-line display * F = 0; 5x8 dot character font * 3. Display on/off control: * D = 0; Display off * C = 0; Cursor off * B = 0; Blinking off * 4. Entry mode set: * I/D = 1; Increment by 1 * S = 0; No shift * * Note, however, that resetting the Arduino doesn't reset the LCD, so we * can't assume that its in that state when a sketch starts (and the * LiquidCrystal constructor is called). */ void LiquidCrystalBase::begin(uint8_t cols, uint8_t lines, uint8_t dotsize) { if (lines > 1) _displayfunction |= LCD_2LINE; _numlines = lines; _currline = 0; /* For some 1 line displays you can select a 10 pixel high font */ if ((dotsize != 0) && (lines == 1)) _displayfunction |= LCD_5x10DOTS; config(); /* Put the LCD into 4 bit or 8 bit mode */ if (! (_displayfunction & LCD_8BITMODE)) { /* This is according to the hitachi HD44780 datasheet figure 24, pg 46 */ /* We start in 8bit mode, try to set 4 bit mode */ write4bits(0x03); delayMicroseconds(4500); // wait min 4.1ms /* Second try */ write4bits(0x03); delayMicroseconds(4500); // wait min 4.1ms /* Third go! */ write4bits(0x03); delayMicroseconds(150); /* Finally, set to 4-bit interface */ write4bits(0x02); } else { /* This is according to the hitachi HD44780 datasheet page 45 figure 23 */ /* Send function set command sequence */ command(LCD_FUNCTIONSET | _displayfunction); delayMicroseconds(4500); // wait more than 4.1ms /* Second try */ command(LCD_FUNCTIONSET | _displayfunction); delayMicroseconds(150); /* Third go */ command(LCD_FUNCTIONSET | _displayfunction); } /* Finally, set # lines, font size, etc. */ command(LCD_FUNCTIONSET | _displayfunction); /* Turn the display on with no cursor or blinking default */ _displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF; display(); /* Clear it off */ clear(); /* Initialize to default text direction (for romance languages) */ _displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT; /* Set the entry mode */ command(LCD_ENTRYMODESET | _displaymode); } /*----- High level commands, user API -----*/ void LiquidCrystalBase::clear() { command(LCD_CLEARDISPLAY); // clear display, set cursor position to zero delayMicroseconds(2000); // this command takes a long time! } void LiquidCrystalBase::home() { command(LCD_RETURNHOME); // set cursor position to zero delayMicroseconds(2000); // this command takes a long time! } void LiquidCrystalBase::setCursor(uint8_t col, uint8_t row) { static const int row_offsets[] = { 0x00, 0x40, 0x14, 0x54 }; if (row > _numlines) row = _numlines - 1; // we count rows starting with zero command(LCD_SETDDRAMADDR | (col + row_offsets[row])); } /* Turn the display on/off (quickly) */ void LiquidCrystalBase::noDisplay() { _displaycontrol &= ~LCD_DISPLAYON; command(LCD_DISPLAYCONTROL | _displaycontrol); } void LiquidCrystalBase::display() { _displaycontrol |= LCD_DISPLAYON; command(LCD_DISPLAYCONTROL | _displaycontrol); } /* Turns the underline cursor on/off */ void LiquidCrystalBase::noCursor() { _displaycontrol &= ~LCD_CURSORON; command(LCD_DISPLAYCONTROL | _displaycontrol); } void LiquidCrystalBase::cursor() { _displaycontrol |= LCD_CURSORON; command(LCD_DISPLAYCONTROL | _displaycontrol); } /* Turn on and off the blinking cursor */ void LiquidCrystalBase::noBlink() { _displaycontrol &= ~LCD_BLINKON; command(LCD_DISPLAYCONTROL | _displaycontrol); } void LiquidCrystalBase::blink() { _displaycontrol |= LCD_BLINKON; command(LCD_DISPLAYCONTROL | _displaycontrol); } /* These commands scroll the display without changing the RAM */ void LiquidCrystalBase::scrollDisplayLeft(void) { command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT); } void LiquidCrystalBase::scrollDisplayRight(void) { command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT); } /* This is for text that flows Left to Right */ void LiquidCrystalBase::leftToRight(void) { _displaymode |= LCD_ENTRYLEFT; command(LCD_ENTRYMODESET | _displaymode); } /* This is for text that flows Right to Left */ void LiquidCrystalBase::rightToLeft(void) { _displaymode &= ~LCD_ENTRYLEFT; command(LCD_ENTRYMODESET | _displaymode); } /* This will 'right justify' text from the cursor */ void LiquidCrystalBase::autoscroll(void) { _displaymode |= LCD_ENTRYSHIFTINCREMENT; command(LCD_ENTRYMODESET | _displaymode); } /* This will 'left justify' text from the cursor */ void LiquidCrystalBase::noAutoscroll(void) { _displaymode &= ~LCD_ENTRYSHIFTINCREMENT; command(LCD_ENTRYMODESET | _displaymode); } /* Allows us to fill the first 8 CGRAM locations with custom characters */ void LiquidCrystalBase::createChar(uint8_t location, uint8_t charmap[]) { location &= 0x7; // we only have 8 locations 0-7 command(LCD_SETCGRAMADDR | (location << 3)); for (int i = 0; i < 8; ++i) write(charmap[i]); } /*----- Mid level commands, for sending data/commands -----*/ inline void LiquidCrystalBase::command(uint8_t value) { send(value, LOW); } inline void LiquidCrystalBase::write(uint8_t value) { send(value, HIGH); } /*----- LiquidCrystal implementation -----*/ LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7, LineDriver *line_driver) { init(0, rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7, line_driver); } LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t enable, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7, LineDriver *line_driver) { init(0, rs, 255, enable, d0, d1, d2, d3, d4, d5, d6, d7, line_driver); } LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, LineDriver *line_driver) { init(1, rs, rw, enable, d0, d1, d2, d3, 0, 0, 0, 0, line_driver); } LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t enable, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, LineDriver *line_driver) { init(1, rs, 255, enable, d0, d1, d2, d3, 0, 0, 0, 0, line_driver); } void LiquidCrystal::init(uint8_t fourbitmode, uint8_t rs, uint8_t rw, uint8_t enable, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7, LineDriver *line_driver) { pins = line_driver; if (!pins) pins = DefaultLineDriver::getInstance(); _rs_pin = rs; _rw_pin = rw; _enable_pin = enable; _data_pins[0] = d0; _data_pins[1] = d1; _data_pins[2] = d2; _data_pins[3] = d3; _data_pins[4] = d4; _data_pins[5] = d5; _data_pins[6] = d6; _data_pins[7] = d7; pins->lineConfig(_rs_pin, OUTPUT); // we can save 1 pin by not using RW. Indicate by passing 255 instead of pin# if (_rw_pin != 255) pins->lineConfig(_rw_pin, OUTPUT); pins->lineConfig(_enable_pin, OUTPUT); if (fourbitmode) _displayfunction = LCD_4BITMODE | LCD_1LINE | LCD_5x8DOTS; else _displayfunction = LCD_8BITMODE | LCD_1LINE | LCD_5x8DOTS; begin(16, 1); } /*----- Low level data pushing commands -----*/ void LiquidCrystal::config() { for (int i = 0; i < 8; ++i) { pins->lineConfig(_data_pins[i], OUTPUT); pins->lineWrite(_data_pins[i], LOW); } /* SEE PAGE 45/46 FOR INITIALIZATION SPECIFICATION! * according to datasheet, we need at least 40ms after power rises above 2.7V * before sending commands. Arduino can turn on way befer 4.5V so we'll wait 50 */ delayMicroseconds(50000); /* Now we pull both RS and R/W low to begin commands */ pins->lineWrite(_rs_pin, LOW); pins->lineWrite(_enable_pin, LOW); if (_rw_pin != -1) pins->lineWrite(_rw_pin, LOW); } /* Write either command or data, with automatic 4/8-bit selection */ void LiquidCrystal::send(uint8_t value, uint8_t mode) { pins->lineWrite(_rs_pin, mode); /* If there is a RW pin indicated, set it low to write */ if (_rw_pin != 255) pins->lineWrite(_rw_pin, LOW); if (_displayfunction & LCD_8BITMODE) write8bits(value); else { write4bits(value >> 4); write4bits(value); } } void LiquidCrystal::pulseEnable(void) { pins->lineWrite(_enable_pin, LOW); delayMicroseconds(1); pins->lineWrite(_enable_pin, HIGH); delayMicroseconds(1); // enable pulse must be >450ns pins->lineWrite(_enable_pin, LOW); delayMicroseconds(100); // commands need > 37us to settle } void LiquidCrystal::write4bits(uint8_t value) { for (int i = 0; i < 4; ++i) { pins->lineConfig(_data_pins[i], OUTPUT); pins->lineWrite(_data_pins[i], (value >> i) & 0x01); } pulseEnable(); } void LiquidCrystal::write8bits(uint8_t value) { for (int i = 0; i < 8; ++i) { pins->lineConfig(_data_pins[i], OUTPUT); pins->lineWrite(_data_pins[i], (value >> i) & 0x01); } pulseEnable(); } <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <limits> #include <memory> #include "compiler/expression/ft_expr.h" #include "compiler/expression/ftnode.h" #include "runtime/full_text/ftcontains_visitor.h" #include "system/properties.h" #include "zorbatypes/numconversions.h" #include "zorbautils/indent.h" #include "zorbautils/stl_util.h" using namespace std; namespace zorba { #ifdef WIN32 // Windows annoyingly defines these as macros. #undef max #undef min #endif ////////// Inlines //////////////////////////////////////////////////////////// inline ft_int to_ft_int( xqp_integer const &i ) { ft_int result; if ( !NumConversions::integerToUInt( i, result ) ) { // TODO } return result; } inline void ftcontains_visitor::push_matches( ft_all_matches *am ) { matches_stack_.push( am ); } inline ft_all_matches* ftcontains_visitor::top_matches() const { return matches_stack_.top(); } inline ft_all_matches* ftcontains_visitor::pop_matches() { ft_all_matches *const am = top_matches(); matches_stack_.pop(); return am; } inline void ftcontains_visitor::push_options( ftmatch_options const *mo ) { options_stack_.push( mo ); } inline ftmatch_options const* ftcontains_visitor::top_options() const { return options_stack_.top(); } inline ftmatch_options const* ftcontains_visitor::pop_options() { ftmatch_options const *const mo = top_options(); options_stack_.pop(); return mo; } ////////// PUSH/POP macros //////////////////////////////////////////////////// #ifndef NDEBUG #define DOUT Properties::instance()->debug_out() #define TRACE_FULL_TEXT Properties::instance()->traceFulltext() inline void pop_helper( char const *what, int line ) { if ( TRACE_FULL_TEXT ) DOUT << "POP " << what << " @ line " << line << endl; } #define PUSH_MATCHES(M) \ if ( !TRACE_FULL_TEXT ) ; else \ DOUT << "PUSH MATCHES @ line " << __LINE__ << endl; push_matches(M) #define POP_MATCHES(M) \ ( pop_helper( "MATCHES", __LINE__ ), pop_matches(M) ) #define PUSH_OPTIONS(O) \ if ( !TRACE_FULL_TEXT ) ; else \ DOUT << "PUSH OPTIONS @ line " << __LINE__ << endl; push_options(O) #define POP_OPTIONS(O) \ ( pop_helper( "OPTIONS", __LINE__ ), pop_options(O) ) #else /* NDEBUG */ #define PUSH_MATCHES(M) push_matches(M) #define POP_MATCHES(M) pop_matches(M) #define PUSH_OPTIONS(O) push_options(O) #define POP_OPTIONS(O) pop_options(O) #endif /* NDEBUG */ /////////////////////////////////////////////////////////////////////////////// ftcontains_visitor::ftcontains_visitor( FTTokenIterator_t &search_ctx, PlanState &state ) : search_ctx_( search_ctx ), plan_state_( state ) { // do nothing } ftcontains_visitor::~ftcontains_visitor() { while ( !matches_stack_.empty() ) delete pop_matches(); ZORBA_ASSERT( options_stack_.empty() ); } void ftcontains_visitor::eval_ftrange( ftrange const &range, ft_int *at_least, ft_int *at_most ) { store::Item_t item1; PlanIterator::consumeNext( item1, range.get_plan_iter1(), plan_state_ ); *at_least = 0; *at_most = numeric_limits<ft_int>::max(); switch ( range.get_mode() ) { case ft_range_mode::at_least: *at_least = to_ft_int( item1->getIntegerValue() ); break; case ft_range_mode::at_most: *at_most = to_ft_int( item1->getIntegerValue() ); break; case ft_range_mode::exactly: *at_least = *at_most = to_ft_int( item1->getIntegerValue() ); break; case ft_range_mode::from_to: *at_least = to_ft_int( item1->getIntegerValue() ); store::Item_t item2; PlanIterator::consumeNext( item2, range.get_plan_iter2(), plan_state_ ); *at_most = to_ft_int( item2->getIntegerValue() ); break; } } bool ftcontains_visitor::ftcontains() const { if ( matches_stack_.empty() ) return false; ft_all_matches const &am = *top_matches(); if ( am.empty() ) return false; // // See spec section 4.3. // FOR_EACH( ft_all_matches, m, am ) if ( m->excludes.empty() ) return true; return false; } expr_visitor* ftcontains_visitor::get_expr_visitor() { return NULL; } ////////// Visit macros /////////////////////////////////////////////////////// #if 0 #define BEGIN_VISIT(LABEL) \ cout << indent << #LABEL << endl << inc_indent #define END_VISIT() \ cout << dec_indent #else #define BEGIN_VISIT(LABEL) /* nothing */ #define END_VISIT() /* nothing */ #endif /* NDEBUG */ #undef DEF_FTNODE_VISITOR_BEGIN_VISIT #define DEF_FTNODE_VISITOR_BEGIN_VISIT(V,C) \ ft_visit_result::type V::begin_visit( C& ) { \ BEGIN_VISIT(C); \ return ft_visit_result::proceed; \ } #undef DEF_FTNODE_VISITOR_END_VISIT #define DEF_FTNODE_VISITOR_END_VISIT(V,C) \ void V::end_visit( C& ) { \ END_VISIT(); \ } /////////////////////////////////////////////////////////////////////////////// #define V ftcontains_visitor ft_visit_result::type V::begin_visit( ftand& ) { BEGIN_VISIT( ftand ); PUSH_MATCHES( NULL ); // sentinel return ft_visit_result::proceed; } void V::end_visit( ftand& ) { while ( true ) { // the popping order is significant auto_ptr<ft_all_matches> am_right( POP_MATCHES() ); auto_ptr<ft_all_matches> am_left( POP_MATCHES() ); if ( !am_left.get() ) { PUSH_MATCHES( am_right.release() ); break; } auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_ftand( *am_left, *am_right, *result ); PUSH_MATCHES( result.release() ); } END_VISIT(); } DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftextension_selection ) ft_visit_result::type V::begin_visit( ftmild_not& ) { BEGIN_VISIT( ftmild_not ); PUSH_MATCHES( NULL ); // sentinel return ft_visit_result::proceed; } void V::end_visit( ftmild_not& ) { while ( true ) { // the popping order is significant auto_ptr<ft_all_matches> am_right( POP_MATCHES() ); auto_ptr<ft_all_matches> am_left( POP_MATCHES() ); if ( !am_left.get() ) { PUSH_MATCHES( am_right.release() ); break; } auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_ftmild_not( *am_left, *am_right, *result ); PUSH_MATCHES( result.release() ); } END_VISIT(); } ft_visit_result::type V::begin_visit( ftor& ) { BEGIN_VISIT( ftor ); PUSH_MATCHES( NULL ); // sentinel return ft_visit_result::proceed; } void V::end_visit( ftor& ) { while ( true ) { // the popping order is significant auto_ptr<ft_all_matches> am_right( POP_MATCHES() ); auto_ptr<ft_all_matches> am_left( POP_MATCHES() ); if ( !am_left.get() ) { PUSH_MATCHES( am_right.release() ); break; } auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_ftor( *am_left, *am_right, *result ); PUSH_MATCHES( result.release() ); } END_VISIT(); } ft_visit_result::type V::begin_visit( ftprimary_with_options &pwo ) { BEGIN_VISIT( ftprimary_with_options ); PUSH_OPTIONS( pwo.get_match_options() ); return ft_visit_result::proceed; } void V::end_visit( ftprimary_with_options& ) { POP_OPTIONS(); END_VISIT(); } DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftrange ) ft_visit_result::type V::begin_visit( ftselection& ) { query_pos_ = 0; return ft_visit_result::proceed; } DEF_FTNODE_VISITOR_END_VISIT( V, ftselection ) DEF_FTNODE_VISITOR_BEGIN_VISIT( V, ftunary_not ) void V::end_visit( ftunary_not& ) { apply_ftunary_not( *top_matches() ); END_VISIT(); } DEF_FTNODE_VISITOR_BEGIN_VISIT( V, ftwords ) void V::end_visit( ftwords &w ) { ftmatch_options const &options = *top_options(); if ( ftwild_card_option const *const wc = options.get_wild_card_option() ) { if ( wc->get_mode() == ft_wild_card_mode::with ) { // TODO: affects query tokenization } } store::Item_t item; FTQueryItemSeq query_items; while ( PlanIterator::consumeNext( item, w.get_plan_iter(), plan_state_ ) ) { FTQueryItem const qi( item->getQueryTokens() ); if ( !qi->empty() ) query_items.push_back( qi ); } if ( !query_items.empty() ) { auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_ftwords( search_ctx_, query_items, ++query_pos_, w.get_mode(), options, *result ); PUSH_MATCHES( result.release() ); } END_VISIT(); } DEF_FTNODE_VISITOR_BEGIN_VISIT( V, ftwords_times ) void V::end_visit( ftwords_times &wt ) { if ( ftrange const *const range = wt.get_times() ) { ft_int at_least, at_most; eval_ftrange( *range, &at_least, &at_most ); auto_ptr<ft_all_matches> const am( POP_MATCHES() ); auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_fttimes( *am, range->get_mode(), at_least, at_most, *result ); PUSH_MATCHES( result.release() ); } END_VISIT(); } ////////// FTPosFilters /////////////////////////////////////////////////////// DEF_FTNODE_VISITOR_BEGIN_VISIT( V, ftcontent_filter ) void V::end_visit( ftcontent_filter &f ) { apply_ftcontent( *top_matches(), f.get_mode(), search_ctx_->begin(), search_ctx_->end() - 1 ); END_VISIT(); } DEF_FTNODE_VISITOR_BEGIN_VISIT( V, ftdistance_filter ) void V::end_visit( ftdistance_filter &f ) { ft_int at_least, at_most; eval_ftrange( *f.get_range(), &at_least, &at_most ); auto_ptr<ft_all_matches> const am( POP_MATCHES() ); auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_ftdistance( *am, at_least, at_most, f.get_unit(), *result ); PUSH_MATCHES( result.release() ); END_VISIT(); } DEF_FTNODE_VISITOR_BEGIN_VISIT( V, ftorder_filter ) void V::end_visit( ftorder_filter& ) { auto_ptr<ft_all_matches> const am( POP_MATCHES() ); auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_ftorder( *am, *result ); PUSH_MATCHES( result.release() ); END_VISIT(); } DEF_FTNODE_VISITOR_BEGIN_VISIT( V, ftscope_filter ) void V::end_visit( ftscope_filter &f ) { auto_ptr<ft_all_matches> const am( POP_MATCHES() ); auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_ftscope( *am, f.get_scope(), f.get_unit(), *result ); PUSH_MATCHES( result.release() ); END_VISIT(); } DEF_FTNODE_VISITOR_BEGIN_VISIT( V, ftwindow_filter ) void V::end_visit( ftwindow_filter &f ) { store::Item_t item; PlanIterator::consumeNext( item, f.get_plan_iter(), plan_state_ ); auto_ptr<ft_all_matches> const am( POP_MATCHES() ); auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_ftwindow( *am, to_ft_int( item->getIntegerValue() ), f.get_unit(), *result ); PUSH_MATCHES( result.release() ); END_VISIT(); } ////////// FTMatchOptions ///////////////////////////////////////////////////// DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftcase_option ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftdiacritics_option ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftextension_option ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftlanguage_option ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftmatch_options ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftstem_option ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftstop_word_option ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftstop_words ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftthesaurus_id ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftthesaurus_option ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftwild_card_option ) #undef V } // namespace zorba /* vim:set et sw=2 ts=2: */ <commit_msg>Reworked debugging macros.<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <limits> #include <memory> #include "compiler/expression/ft_expr.h" #include "compiler/expression/ftnode.h" #include "runtime/full_text/ftcontains_visitor.h" #include "system/properties.h" #include "zorbatypes/numconversions.h" #include "zorbautils/indent.h" #include "zorbautils/stl_util.h" using namespace std; namespace zorba { #ifdef WIN32 // Windows annoyingly defines these as macros. #undef max #undef min #endif ////////// Inlines //////////////////////////////////////////////////////////// inline ft_int to_ft_int( xqp_integer const &i ) { ft_int result; if ( !NumConversions::integerToUInt( i, result ) ) { // TODO } return result; } inline void ftcontains_visitor::push_matches( ft_all_matches *am ) { matches_stack_.push( am ); } inline ft_all_matches* ftcontains_visitor::top_matches() const { return matches_stack_.top(); } inline ft_all_matches* ftcontains_visitor::pop_matches() { ft_all_matches *const am = top_matches(); matches_stack_.pop(); return am; } inline void ftcontains_visitor::push_options( ftmatch_options const *mo ) { options_stack_.push( mo ); } inline ftmatch_options const* ftcontains_visitor::top_options() const { return options_stack_.top(); } inline ftmatch_options const* ftcontains_visitor::pop_options() { ftmatch_options const *const mo = top_options(); options_stack_.pop(); return mo; } ////////// PUSH/POP macros //////////////////////////////////////////////////// #ifndef NDEBUG #define DOUT Properties::instance()->debug_out() #define TRACE_FULL_TEXT Properties::instance()->traceFulltext() inline void pop_helper( char const *what, int line ) { if ( TRACE_FULL_TEXT ) DOUT << indent << "(pop " << what << " @ line " << line << ")\n"; } #define PUSH(WHAT,OBJ) \ if ( !TRACE_FULL_TEXT ) ; else \ DOUT << indent << "(push " #WHAT " @ line " << __LINE__ << ")\n"; \ push_##WHAT(OBJ) #define POP(WHAT) \ ( pop_helper( #WHAT, __LINE__ ), pop_##WHAT() ) #else /* NDEBUG */ #define PUSH(WHAT,OBJ) push_##WHAT(OBJ) #define POP(WHAT) pop_##WHAT() #endif /* NDEBUG */ #define PUSH_MATCHES(M) PUSH(matches,M) #define POP_MATCHES() POP(matches) #define PUSH_OPTIONS(O) PUSH(options,O) #define POP_OPTIONS() POP(options) /////////////////////////////////////////////////////////////////////////////// ftcontains_visitor::ftcontains_visitor( FTTokenIterator_t &search_ctx, PlanState &state ) : search_ctx_( search_ctx ), plan_state_( state ) { // do nothing } ftcontains_visitor::~ftcontains_visitor() { while ( !matches_stack_.empty() ) delete pop_matches(); ZORBA_ASSERT( options_stack_.empty() ); } void ftcontains_visitor::eval_ftrange( ftrange const &range, ft_int *at_least, ft_int *at_most ) { store::Item_t item1; PlanIterator::consumeNext( item1, range.get_plan_iter1(), plan_state_ ); *at_least = 0; *at_most = numeric_limits<ft_int>::max(); switch ( range.get_mode() ) { case ft_range_mode::at_least: *at_least = to_ft_int( item1->getIntegerValue() ); break; case ft_range_mode::at_most: *at_most = to_ft_int( item1->getIntegerValue() ); break; case ft_range_mode::exactly: *at_least = *at_most = to_ft_int( item1->getIntegerValue() ); break; case ft_range_mode::from_to: *at_least = to_ft_int( item1->getIntegerValue() ); store::Item_t item2; PlanIterator::consumeNext( item2, range.get_plan_iter2(), plan_state_ ); *at_most = to_ft_int( item2->getIntegerValue() ); break; } } bool ftcontains_visitor::ftcontains() const { if ( matches_stack_.empty() ) return false; ft_all_matches const &am = *top_matches(); if ( am.empty() ) return false; // // See spec section 4.3. // FOR_EACH( ft_all_matches, m, am ) if ( m->excludes.empty() ) return true; return false; } expr_visitor* ftcontains_visitor::get_expr_visitor() { return NULL; } ////////// Visit macros /////////////////////////////////////////////////////// #ifndef NDEBUG #define BEGIN_VISIT(LABEL) \ cout << indent << "BEGIN " #LABEL << endl << inc_indent #define END_VISIT(LABEL) \ cout << dec_indent << indent << "END " #LABEL << endl #undef DEF_FTNODE_VISITOR_BEGIN_VISIT #define DEF_FTNODE_VISITOR_BEGIN_VISIT(V,C) \ ft_visit_result::type V::begin_visit( C& ) { \ BEGIN_VISIT(C); \ return ft_visit_result::proceed; \ } #undef DEF_FTNODE_VISITOR_END_VISIT #define DEF_FTNODE_VISITOR_END_VISIT(V,C) \ void V::end_visit( C& ) { \ END_VISIT(C); \ } #else /* NDEBUG */ #define BEGIN_VISIT(LABEL) /* nothing */ #define END_VISIT(LABEL) /* nothing */ #endif /* NDEBUG */ /////////////////////////////////////////////////////////////////////////////// #define V ftcontains_visitor ft_visit_result::type V::begin_visit( ftand& ) { BEGIN_VISIT( ftand ); PUSH_MATCHES( NULL ); // sentinel return ft_visit_result::proceed; } void V::end_visit( ftand& ) { while ( true ) { // the popping order is significant auto_ptr<ft_all_matches> am_right( POP_MATCHES() ); auto_ptr<ft_all_matches> am_left( POP_MATCHES() ); if ( !am_left.get() ) { PUSH_MATCHES( am_right.release() ); break; } auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_ftand( *am_left, *am_right, *result ); PUSH_MATCHES( result.release() ); } END_VISIT( ftand ); } DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftextension_selection ) ft_visit_result::type V::begin_visit( ftmild_not& ) { BEGIN_VISIT( ftmild_not ); PUSH_MATCHES( NULL ); // sentinel return ft_visit_result::proceed; } void V::end_visit( ftmild_not& ) { while ( true ) { // the popping order is significant auto_ptr<ft_all_matches> am_right( POP_MATCHES() ); auto_ptr<ft_all_matches> am_left( POP_MATCHES() ); if ( !am_left.get() ) { PUSH_MATCHES( am_right.release() ); break; } auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_ftmild_not( *am_left, *am_right, *result ); PUSH_MATCHES( result.release() ); } END_VISIT( ftmild_not ); } ft_visit_result::type V::begin_visit( ftor& ) { BEGIN_VISIT( ftor ); PUSH_MATCHES( NULL ); // sentinel return ft_visit_result::proceed; } void V::end_visit( ftor& ) { while ( true ) { // the popping order is significant auto_ptr<ft_all_matches> am_right( POP_MATCHES() ); auto_ptr<ft_all_matches> am_left( POP_MATCHES() ); if ( !am_left.get() ) { PUSH_MATCHES( am_right.release() ); break; } auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_ftor( *am_left, *am_right, *result ); PUSH_MATCHES( result.release() ); } END_VISIT( ftor ); } ft_visit_result::type V::begin_visit( ftprimary_with_options &pwo ) { BEGIN_VISIT( ftprimary_with_options ); PUSH_OPTIONS( pwo.get_match_options() ); return ft_visit_result::proceed; } void V::end_visit( ftprimary_with_options& ) { POP_OPTIONS(); END_VISIT( ftprimary_with_options ); } DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftrange ) ft_visit_result::type V::begin_visit( ftselection& ) { query_pos_ = 0; return ft_visit_result::proceed; } DEF_FTNODE_VISITOR_END_VISIT( V, ftselection ) DEF_FTNODE_VISITOR_BEGIN_VISIT( V, ftunary_not ) void V::end_visit( ftunary_not& ) { apply_ftunary_not( *top_matches() ); END_VISIT( ftunary_not ); } DEF_FTNODE_VISITOR_BEGIN_VISIT( V, ftwords ) void V::end_visit( ftwords &w ) { ftmatch_options const &options = *top_options(); if ( ftwild_card_option const *const wc = options.get_wild_card_option() ) { if ( wc->get_mode() == ft_wild_card_mode::with ) { // TODO: affects query tokenization } } store::Item_t item; FTQueryItemSeq query_items; while ( PlanIterator::consumeNext( item, w.get_plan_iter(), plan_state_ ) ) { FTQueryItem const qi( item->getQueryTokens() ); if ( !qi->empty() ) query_items.push_back( qi ); } if ( !query_items.empty() ) { auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_ftwords( search_ctx_, query_items, ++query_pos_, w.get_mode(), options, *result ); PUSH_MATCHES( result.release() ); } END_VISIT( ftwords ); } DEF_FTNODE_VISITOR_BEGIN_VISIT( V, ftwords_times ) void V::end_visit( ftwords_times &wt ) { if ( ftrange const *const range = wt.get_times() ) { ft_int at_least, at_most; eval_ftrange( *range, &at_least, &at_most ); auto_ptr<ft_all_matches> const am( POP_MATCHES() ); auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_fttimes( *am, range->get_mode(), at_least, at_most, *result ); PUSH_MATCHES( result.release() ); } END_VISIT( ftwords_times ); } ////////// FTPosFilters /////////////////////////////////////////////////////// DEF_FTNODE_VISITOR_BEGIN_VISIT( V, ftcontent_filter ) void V::end_visit( ftcontent_filter &f ) { apply_ftcontent( *top_matches(), f.get_mode(), search_ctx_->begin(), search_ctx_->end() - 1 ); END_VISIT( ftcontent_filter ); } DEF_FTNODE_VISITOR_BEGIN_VISIT( V, ftdistance_filter ) void V::end_visit( ftdistance_filter &f ) { ft_int at_least, at_most; eval_ftrange( *f.get_range(), &at_least, &at_most ); auto_ptr<ft_all_matches> const am( POP_MATCHES() ); auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_ftdistance( *am, at_least, at_most, f.get_unit(), *result ); PUSH_MATCHES( result.release() ); END_VISIT( ftdistance_filter ); } DEF_FTNODE_VISITOR_BEGIN_VISIT( V, ftorder_filter ) void V::end_visit( ftorder_filter& ) { auto_ptr<ft_all_matches> const am( POP_MATCHES() ); auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_ftorder( *am, *result ); PUSH_MATCHES( result.release() ); END_VISIT( ftorder_filter ); } DEF_FTNODE_VISITOR_BEGIN_VISIT( V, ftscope_filter ) void V::end_visit( ftscope_filter &f ) { auto_ptr<ft_all_matches> const am( POP_MATCHES() ); auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_ftscope( *am, f.get_scope(), f.get_unit(), *result ); PUSH_MATCHES( result.release() ); END_VISIT( ftscope_filter ); } DEF_FTNODE_VISITOR_BEGIN_VISIT( V, ftwindow_filter ) void V::end_visit( ftwindow_filter &f ) { store::Item_t item; PlanIterator::consumeNext( item, f.get_plan_iter(), plan_state_ ); auto_ptr<ft_all_matches> const am( POP_MATCHES() ); auto_ptr<ft_all_matches> result( new ft_all_matches ); apply_ftwindow( *am, to_ft_int( item->getIntegerValue() ), f.get_unit(), *result ); PUSH_MATCHES( result.release() ); END_VISIT( ftwindow_filter ); } ////////// FTMatchOptions ///////////////////////////////////////////////////// DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftcase_option ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftdiacritics_option ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftextension_option ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftlanguage_option ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftmatch_options ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftstem_option ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftstop_word_option ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftstop_words ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftthesaurus_id ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftthesaurus_option ) DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftwild_card_option ) #undef V } // namespace zorba /* vim:set et sw=2 ts=2: */ <|endoftext|>
<commit_before>//===--- ResolveLocation.cpp - Source location resolver ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This defines the ResolveLocationInAST function, which resolves a // source location into a ASTLocation. // //===----------------------------------------------------------------------===// #include "clang/Index/Utils.h" #include "clang/Index/ASTLocation.h" #include "clang/AST/DeclVisitor.h" #include "clang/AST/StmtVisitor.h" #include "clang/Lex/Lexer.h" #include "clang/Basic/SourceManager.h" #include "llvm/Support/Compiler.h" using namespace clang; using namespace idx; namespace { /// \brief Base for the LocResolver classes. Mostly does source range checking. class VISIBILITY_HIDDEN LocResolverBase { protected: ASTContext &Ctx; SourceLocation Loc; enum RangePos { BeforeLoc, ContainsLoc, AfterLoc }; RangePos CheckRange(SourceRange Range); RangePos CheckRange(Decl *D) { return CheckRange(D->getSourceRange()); } RangePos CheckRange(Stmt *Node) { return CheckRange(Node->getSourceRange()); } template <typename T> bool isBeforeLocation(T *Node) { return CheckRange(Node) == BeforeLoc; } template <typename T> bool ContainsLocation(T *Node) { return CheckRange(Node) == ContainsLoc; } template <typename T> bool isAfterLocation(T *Node) { return CheckRange(Node) == AfterLoc; } public: LocResolverBase(ASTContext &ctx, SourceLocation loc) : Ctx(ctx), Loc(loc) {} #ifndef NDEBUG /// \brief Debugging output. void print(Decl *D); /// \brief Debugging output. void print(Stmt *Node); #endif }; /// \brief Searches a statement for the ASTLocation that corresponds to a source /// location. class VISIBILITY_HIDDEN StmtLocResolver : public LocResolverBase, public StmtVisitor<StmtLocResolver, ASTLocation > { Decl *Parent; public: StmtLocResolver(ASTContext &ctx, SourceLocation loc, Decl *parent) : LocResolverBase(ctx, loc), Parent(parent) {} ASTLocation VisitDeclStmt(DeclStmt *Node); ASTLocation VisitStmt(Stmt *Node); }; /// \brief Searches a declaration for the ASTLocation that corresponds to a /// source location. class VISIBILITY_HIDDEN DeclLocResolver : public LocResolverBase, public DeclVisitor<DeclLocResolver, ASTLocation > { public: DeclLocResolver(ASTContext &ctx, SourceLocation loc) : LocResolverBase(ctx, loc) {} ASTLocation VisitDeclContext(DeclContext *DC); ASTLocation VisitTranslationUnitDecl(TranslationUnitDecl *TU); ASTLocation VisitVarDecl(VarDecl *D); ASTLocation VisitFunctionDecl(FunctionDecl *D); ASTLocation VisitDecl(Decl *D); }; } // anonymous namespace ASTLocation StmtLocResolver::VisitDeclStmt(DeclStmt *Node) { assert(ContainsLocation(Node) && "Should visit only after verifying that loc is in range"); // Search all declarations of this DeclStmt. for (DeclStmt::decl_iterator I = Node->decl_begin(), E = Node->decl_end(); I != E; ++I) { RangePos RP = CheckRange(*I); if (RP == AfterLoc) break; if (RP == ContainsLoc) return DeclLocResolver(Ctx, Loc).Visit(*I); } return ASTLocation(Parent, Node); } ASTLocation StmtLocResolver::VisitStmt(Stmt *Node) { assert(ContainsLocation(Node) && "Should visit only after verifying that loc is in range"); // Search the child statements. for (Stmt::child_iterator I = Node->child_begin(), E = Node->child_end(); I != E; ++I) { RangePos RP = CheckRange(*I); if (RP == AfterLoc) break; if (RP == ContainsLoc) return Visit(*I); } return ASTLocation(Parent, Node); } ASTLocation DeclLocResolver::VisitDeclContext(DeclContext *DC) { for (DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) { RangePos RP = CheckRange(*I); if (RP == AfterLoc) break; if (RP == ContainsLoc) return Visit(*I); } return ASTLocation(cast<Decl>(DC)); } ASTLocation DeclLocResolver::VisitTranslationUnitDecl(TranslationUnitDecl *TU) { ASTLocation ASTLoc = VisitDeclContext(TU); if (ASTLoc.getDecl() == TU) return ASTLocation(); return ASTLoc; } ASTLocation DeclLocResolver::VisitFunctionDecl(FunctionDecl *D) { assert(ContainsLocation(D) && "Should visit only after verifying that loc is in range"); // First, search through the parameters of the function. for (FunctionDecl::param_iterator I = D->param_begin(), E = D->param_end(); I != E; ++I) { RangePos RP = CheckRange(*I); if (RP == AfterLoc) return ASTLocation(D); if (RP == ContainsLoc) return Visit(*I); } // We didn't find the location in the parameters and we didn't get passed it. if (!D->isThisDeclarationADefinition()) return ASTLocation(D); // Second, search through the declarations that are part of the function. // If we find he location there, we won't have to search through its body. for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end(); I != E; ++I) { if (isa<ParmVarDecl>(*I)) continue; // We already searched through the parameters. RangePos RP = CheckRange(*I); if (RP == AfterLoc) break; if (RP == ContainsLoc) return Visit(*I); } // We didn't find a declaration that corresponds to the source location. // Finally, search through the body of the function. Stmt *Body = D->getBody(); assert(Body && "Expected definition"); assert(!isBeforeLocation(Body) && "This function is supposed to contain the loc"); if (isAfterLocation(Body)) return ASTLocation(D); // The body contains the location. assert(ContainsLocation(Body)); return StmtLocResolver(Ctx, Loc, D).Visit(Body); } ASTLocation DeclLocResolver::VisitVarDecl(VarDecl *D) { assert(ContainsLocation(D) && "Should visit only after verifying that loc is in range"); // Check whether the location points to the init expression. Expr *Init = D->getInit(); if (Init && ContainsLocation(Init)) return StmtLocResolver(Ctx, Loc, D).Visit(Init); return ASTLocation(D); } ASTLocation DeclLocResolver::VisitDecl(Decl *D) { assert(ContainsLocation(D) && "Should visit only after verifying that loc is in range"); if (DeclContext *DC = dyn_cast<DeclContext>(D)) return VisitDeclContext(DC); return ASTLocation(D); } LocResolverBase::RangePos LocResolverBase::CheckRange(SourceRange Range) { if (!Range.isValid()) return BeforeLoc; // Keep looking. // Update the end source range to cover the full length of the token // positioned at the end of the source range. // // e.g., // int foo // ^ ^ // // will be updated to // int foo // ^ ^ unsigned TokSize = Lexer::MeasureTokenLength(Range.getEnd(), Ctx.getSourceManager(), Ctx.getLangOptions()); Range.setEnd(Range.getEnd().getFileLocWithOffset(TokSize-1)); SourceManager &SourceMgr = Ctx.getSourceManager(); if (SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), Loc)) return BeforeLoc; if (SourceMgr.isBeforeInTranslationUnit(Loc, Range.getBegin())) return AfterLoc; return ContainsLoc; } #ifndef NDEBUG void LocResolverBase::print(Decl *D) { llvm::raw_ostream &OS = llvm::outs(); OS << "#### DECL " << D->getDeclKindName() << " ####\n"; D->print(OS); OS << " <"; D->getLocStart().print(OS, Ctx.getSourceManager()); OS << " > - <"; D->getLocEnd().print(OS, Ctx.getSourceManager()); OS << ">\n\n"; OS.flush(); } void LocResolverBase::print(Stmt *Node) { llvm::raw_ostream &OS = llvm::outs(); OS << "#### STMT " << Node->getStmtClassName() << " ####\n"; Node->printPretty(OS, Ctx, 0, PrintingPolicy(Ctx.getLangOptions())); OS << " <"; Node->getLocStart().print(OS, Ctx.getSourceManager()); OS << " > - <"; Node->getLocEnd().print(OS, Ctx.getSourceManager()); OS << ">\n\n"; OS.flush(); } #endif /// \brief Returns the AST node that a source location points to. /// ASTLocation idx::ResolveLocationInAST(ASTContext &Ctx, SourceLocation Loc) { if (Loc.isInvalid()) return ASTLocation(); return DeclLocResolver(Ctx, Loc).Visit(Ctx.getTranslationUnitDecl()); } <commit_msg>Resolve a location that is inside an ObjCMethodDecl.<commit_after>//===--- ResolveLocation.cpp - Source location resolver ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This defines the ResolveLocationInAST function, which resolves a // source location into a ASTLocation. // //===----------------------------------------------------------------------===// #include "clang/Index/Utils.h" #include "clang/Index/ASTLocation.h" #include "clang/AST/DeclVisitor.h" #include "clang/AST/StmtVisitor.h" #include "clang/Lex/Lexer.h" #include "clang/Basic/SourceManager.h" #include "llvm/Support/Compiler.h" using namespace clang; using namespace idx; namespace { /// \brief Base for the LocResolver classes. Mostly does source range checking. class VISIBILITY_HIDDEN LocResolverBase { protected: ASTContext &Ctx; SourceLocation Loc; enum RangePos { BeforeLoc, ContainsLoc, AfterLoc }; RangePos CheckRange(SourceRange Range); RangePos CheckRange(Decl *D) { return CheckRange(D->getSourceRange()); } RangePos CheckRange(Stmt *Node) { return CheckRange(Node->getSourceRange()); } template <typename T> bool isBeforeLocation(T *Node) { return CheckRange(Node) == BeforeLoc; } template <typename T> bool ContainsLocation(T *Node) { return CheckRange(Node) == ContainsLoc; } template <typename T> bool isAfterLocation(T *Node) { return CheckRange(Node) == AfterLoc; } public: LocResolverBase(ASTContext &ctx, SourceLocation loc) : Ctx(ctx), Loc(loc) {} #ifndef NDEBUG /// \brief Debugging output. void print(Decl *D); /// \brief Debugging output. void print(Stmt *Node); #endif }; /// \brief Searches a statement for the ASTLocation that corresponds to a source /// location. class VISIBILITY_HIDDEN StmtLocResolver : public LocResolverBase, public StmtVisitor<StmtLocResolver, ASTLocation > { Decl * const Parent; public: StmtLocResolver(ASTContext &ctx, SourceLocation loc, Decl *parent) : LocResolverBase(ctx, loc), Parent(parent) {} ASTLocation VisitDeclStmt(DeclStmt *Node); ASTLocation VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node); ASTLocation VisitStmt(Stmt *Node); }; /// \brief Searches a declaration for the ASTLocation that corresponds to a /// source location. class VISIBILITY_HIDDEN DeclLocResolver : public LocResolverBase, public DeclVisitor<DeclLocResolver, ASTLocation > { public: DeclLocResolver(ASTContext &ctx, SourceLocation loc) : LocResolverBase(ctx, loc) {} ASTLocation VisitDeclContext(DeclContext *DC); ASTLocation VisitTranslationUnitDecl(TranslationUnitDecl *TU); ASTLocation VisitVarDecl(VarDecl *D); ASTLocation VisitFunctionDecl(FunctionDecl *D); ASTLocation VisitObjCMethodDecl(ObjCMethodDecl *D); ASTLocation VisitDecl(Decl *D); }; } // anonymous namespace ASTLocation StmtLocResolver::VisitDeclStmt(DeclStmt *Node) { assert(ContainsLocation(Node) && "Should visit only after verifying that loc is in range"); // Search all declarations of this DeclStmt. for (DeclStmt::decl_iterator I = Node->decl_begin(), E = Node->decl_end(); I != E; ++I) { RangePos RP = CheckRange(*I); if (RP == AfterLoc) break; if (RP == ContainsLoc) return DeclLocResolver(Ctx, Loc).Visit(*I); } return ASTLocation(Parent, Node); } ASTLocation StmtLocResolver::VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node) { assert(ContainsLocation(Node) && "Should visit only after verifying that loc is in range"); return ASTLocation(Parent, Node); } ASTLocation StmtLocResolver::VisitStmt(Stmt *Node) { assert(ContainsLocation(Node) && "Should visit only after verifying that loc is in range"); // Search the child statements. for (Stmt::child_iterator I = Node->child_begin(), E = Node->child_end(); I != E; ++I) { RangePos RP = CheckRange(*I); if (RP == AfterLoc) break; if (RP == ContainsLoc) return Visit(*I); } return ASTLocation(Parent, Node); } ASTLocation DeclLocResolver::VisitDeclContext(DeclContext *DC) { for (DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) { RangePos RP = CheckRange(*I); if (RP == AfterLoc) break; if (RP == ContainsLoc) return Visit(*I); } return ASTLocation(cast<Decl>(DC)); } ASTLocation DeclLocResolver::VisitTranslationUnitDecl(TranslationUnitDecl *TU) { ASTLocation ASTLoc = VisitDeclContext(TU); if (ASTLoc.getDecl() == TU) return ASTLocation(); return ASTLoc; } ASTLocation DeclLocResolver::VisitFunctionDecl(FunctionDecl *D) { assert(ContainsLocation(D) && "Should visit only after verifying that loc is in range"); // First, search through the parameters of the function. for (FunctionDecl::param_iterator I = D->param_begin(), E = D->param_end(); I != E; ++I) { RangePos RP = CheckRange(*I); if (RP == AfterLoc) return ASTLocation(D); if (RP == ContainsLoc) return Visit(*I); } // We didn't find the location in the parameters and we didn't get passed it. if (!D->isThisDeclarationADefinition()) return ASTLocation(D); // Second, search through the declarations that are part of the function. // If we find he location there, we won't have to search through its body. for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end(); I != E; ++I) { if (isa<ParmVarDecl>(*I)) continue; // We already searched through the parameters. RangePos RP = CheckRange(*I); if (RP == AfterLoc) break; if (RP == ContainsLoc) return Visit(*I); } // We didn't find a declaration that corresponds to the source location. // Finally, search through the body of the function. Stmt *Body = D->getBody(); assert(Body && "Expected definition"); assert(!isBeforeLocation(Body) && "This function is supposed to contain the loc"); if (isAfterLocation(Body)) return ASTLocation(D); // The body contains the location. assert(ContainsLocation(Body)); return StmtLocResolver(Ctx, Loc, D).Visit(Body); } ASTLocation DeclLocResolver::VisitVarDecl(VarDecl *D) { assert(ContainsLocation(D) && "Should visit only after verifying that loc is in range"); // Check whether the location points to the init expression. Expr *Init = D->getInit(); if (Init && ContainsLocation(Init)) return StmtLocResolver(Ctx, Loc, D).Visit(Init); return ASTLocation(D); } ASTLocation DeclLocResolver::VisitObjCMethodDecl(ObjCMethodDecl *D) { assert(ContainsLocation(D) && "Should visit only after verifying that loc is in range"); // First, search through the parameters of the method. for (ObjCMethodDecl::param_iterator I = D->param_begin(), E = D->param_end(); I != E; ++I) { RangePos RP = CheckRange(*I); if (RP == AfterLoc) return ASTLocation(D); if (RP == ContainsLoc) return Visit(*I); } // We didn't find the location in the parameters and we didn't get passed it. if (!D->getBody()) return ASTLocation(D); // Second, search through the declarations that are part of the method. // If we find he location there, we won't have to search through its body. for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end(); I != E; ++I) { if (isa<ParmVarDecl>(*I)) continue; // We already searched through the parameters. RangePos RP = CheckRange(*I); if (RP == AfterLoc) break; if (RP == ContainsLoc) return Visit(*I); } // We didn't find a declaration that corresponds to the source location. // Finally, search through the body of the method. Stmt *Body = D->getBody(); assert(Body && "Expected definition"); assert(!isBeforeLocation(Body) && "This method is supposed to contain the loc"); if (isAfterLocation(Body)) return ASTLocation(D); // The body contains the location. assert(ContainsLocation(Body)); return StmtLocResolver(Ctx, Loc, D).Visit(Body); } ASTLocation DeclLocResolver::VisitDecl(Decl *D) { assert(ContainsLocation(D) && "Should visit only after verifying that loc is in range"); if (DeclContext *DC = dyn_cast<DeclContext>(D)) return VisitDeclContext(DC); return ASTLocation(D); } LocResolverBase::RangePos LocResolverBase::CheckRange(SourceRange Range) { if (!Range.isValid()) return BeforeLoc; // Keep looking. // Update the end source range to cover the full length of the token // positioned at the end of the source range. // // e.g., // int foo // ^ ^ // // will be updated to // int foo // ^ ^ unsigned TokSize = Lexer::MeasureTokenLength(Range.getEnd(), Ctx.getSourceManager(), Ctx.getLangOptions()); Range.setEnd(Range.getEnd().getFileLocWithOffset(TokSize-1)); SourceManager &SourceMgr = Ctx.getSourceManager(); if (SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), Loc)) return BeforeLoc; if (SourceMgr.isBeforeInTranslationUnit(Loc, Range.getBegin())) return AfterLoc; return ContainsLoc; } #ifndef NDEBUG void LocResolverBase::print(Decl *D) { llvm::raw_ostream &OS = llvm::outs(); OS << "#### DECL " << D->getDeclKindName() << " ####\n"; D->print(OS); OS << " <"; D->getLocStart().print(OS, Ctx.getSourceManager()); OS << " > - <"; D->getLocEnd().print(OS, Ctx.getSourceManager()); OS << ">\n\n"; OS.flush(); } void LocResolverBase::print(Stmt *Node) { llvm::raw_ostream &OS = llvm::outs(); OS << "#### STMT " << Node->getStmtClassName() << " ####\n"; Node->printPretty(OS, Ctx, 0, PrintingPolicy(Ctx.getLangOptions())); OS << " <"; Node->getLocStart().print(OS, Ctx.getSourceManager()); OS << " > - <"; Node->getLocEnd().print(OS, Ctx.getSourceManager()); OS << ">\n\n"; OS.flush(); } #endif /// \brief Returns the AST node that a source location points to. /// ASTLocation idx::ResolveLocationInAST(ASTContext &Ctx, SourceLocation Loc) { if (Loc.isInvalid()) return ASTLocation(); return DeclLocResolver(Ctx, Loc).Visit(Ctx.getTranslationUnitDecl()); } <|endoftext|>
<commit_before>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/CIFactory.h" #include "DeclCollector.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/Version.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/Job.h" #include "clang/Driver/Tool.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/Sema.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Option/ArgList.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Host.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Process.h" #include <ctime> using namespace clang; namespace cling { // // Dummy function so we can use dladdr to find the executable path. // void locate_cling_executable() { } /// \brief Retrieves the clang CC1 specific flags out of the compilation's /// jobs. Returns NULL on error. static const llvm::opt::ArgStringList *GetCC1Arguments(clang::DiagnosticsEngine *Diagnostics, clang::driver::Compilation *Compilation) { // We expect to get back exactly one Command job, if we didn't something // failed. Extract that job from the Compilation. const clang::driver::JobList &Jobs = Compilation->getJobs(); if (!Jobs.size() || !isa<clang::driver::Command>(*Jobs.begin())) { // diagnose this... return NULL; } // The one job we find should be to invoke clang again. const clang::driver::Command *Cmd = cast<clang::driver::Command>(*Jobs.begin()); if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") { // diagnose this... return NULL; } return &Cmd->getArguments(); } CompilerInstance* CIFactory::createCI(llvm::StringRef code, int argc, const char* const *argv, const char* llvmdir) { return createCI(llvm::MemoryBuffer::getMemBuffer(code), argc, argv, llvmdir, new DeclCollector()); } CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer, int argc, const char* const *argv, const char* llvmdir, DeclCollector* stateCollector) { // Create an instance builder, passing the llvmdir and arguments. // // Initialize the llvm library. llvm::InitializeNativeTarget(); llvm::InitializeAllAsmPrinters(); llvm::SmallString<512> resource_path; if (llvmdir) { resource_path = llvmdir; llvm::sys::path::append(resource_path,"lib", "clang", CLANG_VERSION_STRING); } else { // FIXME: The first arg really does need to be argv[0] on FreeBSD. // // Note: The second arg is not used for Apple, FreeBSD, Linux, // or cygwin, and can only be used on systems which support // the use of dladdr(). // // Note: On linux and cygwin this uses /proc/self/exe to find the path. // // Note: On Apple it uses _NSGetExecutablePath(). // // Note: On FreeBSD it uses getprogpath(). // // Note: Otherwise it uses dladdr(). // resource_path = CompilerInvocation::GetResourcesPath("cling", (void*)(intptr_t) locate_cling_executable ); } if (!llvm::sys::fs::is_directory(resource_path.str())) { llvm::errs() << "ERROR in cling::CIFactory::createCI():\n resource directory " << resource_path.str() << " not found!\n"; resource_path = ""; } DiagnosticOptions* DefaultDiagnosticOptions = new DiagnosticOptions(); DefaultDiagnosticOptions->ShowColors = llvm::sys::Process::StandardErrHasColors() ? 1 : 0; TextDiagnosticPrinter* DiagnosticPrinter = new TextDiagnosticPrinter(llvm::errs(), DefaultDiagnosticOptions); llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagIDs(new DiagnosticIDs()); DiagnosticsEngine* Diagnostics = new DiagnosticsEngine(DiagIDs, DefaultDiagnosticOptions, DiagnosticPrinter, /*Owns it*/ true); // LEAKS! std::vector<const char*> argvCompile(argv, argv + argc); // We do C++ by default; append right after argv[0] name // Only insert it if there is no other "-x": bool haveMinusX = false; for (const char* const* iarg = argv; !haveMinusX && iarg < argv + argc; ++iarg) { haveMinusX = !strcmp(*iarg, "-x"); } if (!haveMinusX) { argvCompile.insert(argvCompile.begin() + 1,"-x"); argvCompile.insert(argvCompile.begin() + 2, "c++"); } argvCompile.push_back("-c"); argvCompile.push_back("-"); clang::driver::Driver Driver(argv[0], llvm::sys::getDefaultTargetTriple(), "cling.out", *Diagnostics); //Driver.setWarnMissingInput(false); Driver.setCheckInputsExist(false); // think foo.C(12) llvm::ArrayRef<const char*>RF(&(argvCompile[0]), argvCompile.size()); llvm::OwningPtr<clang::driver::Compilation> Compilation(Driver.BuildCompilation(RF)); const clang::driver::ArgStringList* CC1Args = GetCC1Arguments(Diagnostics, Compilation.get()); if (CC1Args == NULL) { return 0; } clang::CompilerInvocation* Invocation = new clang::CompilerInvocation; clang::CompilerInvocation::CreateFromArgs(*Invocation, CC1Args->data() + 1, CC1Args->data() + CC1Args->size(), *Diagnostics); Invocation->getFrontendOpts().DisableFree = true; if (Invocation->getHeaderSearchOpts().UseBuiltinIncludes && !resource_path.empty()) { // Update ResourceDir // header search opts' entry for resource_path/include isn't // updated by providing a new resource path; update it manually. clang::HeaderSearchOptions& Opts = Invocation->getHeaderSearchOpts(); llvm::SmallString<512> oldResInc(Opts.ResourceDir); llvm::sys::path::append(oldResInc, "include"); llvm::SmallString<512> newResInc(resource_path); llvm::sys::path::append(newResInc, "include"); bool foundOldResInc = false; for (unsigned i = 0, e = Opts.UserEntries.size(); !foundOldResInc && i != e; ++i) { HeaderSearchOptions::Entry &E = Opts.UserEntries[i]; if (!E.IsFramework && E.Group == clang::frontend::System && E.IgnoreSysRoot && oldResInc.str() == E.Path) { E.Path = newResInc.c_str(); foundOldResInc = true; } } Opts.ResourceDir = resource_path.str(); } // Create and setup a compiler instance. CompilerInstance* CI = new CompilerInstance(); CI->setInvocation(Invocation); CI->createDiagnostics(DiagnosticPrinter, /*ShouldOwnClient=*/ false); { // // Buffer the error messages while we process // the compiler options. // // Set the language options, which cling needs SetClingCustomLangOpts(CI->getLangOpts()); CI->getInvocation().getPreprocessorOpts().addMacroDef("__CLING__"); if (CI->getLangOpts().CPlusPlus11 == 1) { // http://llvm.org/bugs/show_bug.cgi?id=13530 CI->getInvocation().getPreprocessorOpts() .addMacroDef("__CLING__CXX11"); } if (CI->getDiagnostics().hasErrorOccurred()) { delete CI; CI = 0; return 0; } } CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(), &Invocation->getTargetOpts())); if (!CI->hasTarget()) { delete CI; CI = 0; return 0; } CI->getTarget().setForcedLangOptions(CI->getLangOpts()); SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget()); if (CI->getTarget().getTriple().getOS() == llvm::Triple::Cygwin) { // clang "forgets" the basic arch part needed by winnt.h: if (CI->getTarget().getTriple().getArch() == llvm::Triple::x86) { CI->getInvocation().getPreprocessorOpts().addMacroDef("_X86_=1"); } else if (CI->getTarget().getTriple().getArch() == llvm::Triple::x86_64) { CI->getInvocation().getPreprocessorOpts().addMacroDef("__x86_64=1"); } else { llvm::errs() << "Warning: unhandled target architecture " << CI->getTarget().getTriple().getArchName() << '\n'; } } // Set up source and file managers CI->createFileManager(); SourceManager* SM = new SourceManager(CI->getDiagnostics(), CI->getFileManager(), /*UserFilesAreVolatile*/ true); CI->setSourceManager(SM); // FIXME: SM leaks. // As main file we want // * a virtual file that is claiming to be huge // * with an empty memory buffer attached (to bring the content) FileManager& FM = SM->getFileManager(); // Build the virtual file const char* Filename = "InteractiveInputLineIncluder.h"; const std::string& CGOptsMainFileName = CI->getInvocation().getCodeGenOpts().MainFileName; if (!CGOptsMainFileName.empty()) Filename = CGOptsMainFileName.c_str(); const FileEntry* FE = FM.getVirtualFile(Filename, 1U << 15U, time(0)); FileID MainFileID = SM->createMainFileID(FE, SrcMgr::C_User); const SrcMgr::SLocEntry& MainFileSLocE = SM->getSLocEntry(MainFileID); const SrcMgr::ContentCache* MainFileCC = MainFileSLocE.getFile().getContentCache(); if (!buffer) buffer = llvm::MemoryBuffer::getMemBuffer("/*CLING DEFAULT MEMBUF*/\n"); const_cast<SrcMgr::ContentCache*>(MainFileCC)->setBuffer(buffer); // Set up the preprocessor CI->createPreprocessor(); Preprocessor& PP = CI->getPreprocessor(); PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(), PP.getLangOpts()); // Set up the ASTContext ASTContext *Ctx = new ASTContext(CI->getLangOpts(), PP.getSourceManager(), &CI->getTarget(), PP.getIdentifierTable(), PP.getSelectorTable(), PP.getBuiltinInfo(), /*size_reserve*/0, /*DelayInit*/false); CI->setASTContext(Ctx); if (stateCollector) { // Add the callback keeping track of the macro definitions PP.addPPCallbacks(stateCollector); } else stateCollector = new DeclCollector(); // Set up the ASTConsumers CI->setASTConsumer(stateCollector); // Set up Sema CodeCompleteConsumer* CCC = 0; CI->createSema(TU_Complete, CCC); CI->takeASTConsumer(); // Transfer to ownership to the PP only // Set CodeGen options // CI->getCodeGenOpts().DebugInfo = 1; // want debug info // CI->getCodeGenOpts().EmitDeclMetadata = 1; // For unloading, for later CI->getCodeGenOpts().OptimizationLevel = 0; // see pure SSA, that comes out CI->getCodeGenOpts().CXXCtorDtorAliases = 0; // aliasing the complete // ctor to the base ctor causes // the JIT to crash // When asserts are on, TURN ON not compare the VerifyModule assert(CI->getCodeGenOpts().VerifyModule = 1); return CI; } void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) { Opts.EmitAllDecls = 0; // Otherwise if PCH attached will codegen all decls. Opts.Exceptions = 1; Opts.CXXExceptions = 1; Opts.Deprecated = 1; //Opts.Modules = 1; // C++11 is turned on if cling is built with C++11: it's an interperter; // cross-language compilation doesn't make sense. // Extracted from Boost/config/compiler. // SunProCC has no C++11. // VisualC's support is not obvious to extract from Boost... #if /*GCC*/ (defined(__GNUC__) && defined(__GXX_EXPERIMENTAL_CXX0X__)) \ || /*clang*/ (defined(__has_feature) && __has_feature(cxx_decltype)) \ || /*ICC*/ ((!(defined(_WIN32) || defined(_WIN64)) && defined(__STDC_HOSTED__) && defined(__INTEL_COMPILER) && (__STDC_HOSTED__ && (__INTEL_COMPILER <= 1200))) || defined(__GXX_EXPERIMENTAL_CPP0X__)) Opts.CPlusPlus11 = 1; #endif } void CIFactory::SetClingTargetLangOpts(LangOptions& Opts, const TargetInfo& Target) { if (Target.getTriple().getOS() == llvm::Triple::Win32) { Opts.MicrosoftExt = 1; Opts.MSCVersion = 1300; // Should fix http://llvm.org/bugs/show_bug.cgi?id=10528 Opts.DelayedTemplateParsing = 1; } else { Opts.MicrosoftExt = 0; } } } // end namespace <commit_msg>Add clarification comment.<commit_after>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/CIFactory.h" #include "DeclCollector.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/Version.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/Job.h" #include "clang/Driver/Tool.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/Sema.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Option/ArgList.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Host.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Process.h" #include <ctime> using namespace clang; namespace cling { // // Dummy function so we can use dladdr to find the executable path. // void locate_cling_executable() { } /// \brief Retrieves the clang CC1 specific flags out of the compilation's /// jobs. Returns NULL on error. static const llvm::opt::ArgStringList *GetCC1Arguments(clang::DiagnosticsEngine *Diagnostics, clang::driver::Compilation *Compilation) { // We expect to get back exactly one Command job, if we didn't something // failed. Extract that job from the Compilation. const clang::driver::JobList &Jobs = Compilation->getJobs(); if (!Jobs.size() || !isa<clang::driver::Command>(*Jobs.begin())) { // diagnose this... return NULL; } // The one job we find should be to invoke clang again. const clang::driver::Command *Cmd = cast<clang::driver::Command>(*Jobs.begin()); if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") { // diagnose this... return NULL; } return &Cmd->getArguments(); } CompilerInstance* CIFactory::createCI(llvm::StringRef code, int argc, const char* const *argv, const char* llvmdir) { return createCI(llvm::MemoryBuffer::getMemBuffer(code), argc, argv, llvmdir, new DeclCollector()); } CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer, int argc, const char* const *argv, const char* llvmdir, DeclCollector* stateCollector) { // Create an instance builder, passing the llvmdir and arguments. // // Initialize the llvm library. llvm::InitializeNativeTarget(); llvm::InitializeAllAsmPrinters(); llvm::SmallString<512> resource_path; if (llvmdir) { resource_path = llvmdir; llvm::sys::path::append(resource_path,"lib", "clang", CLANG_VERSION_STRING); } else { // FIXME: The first arg really does need to be argv[0] on FreeBSD. // // Note: The second arg is not used for Apple, FreeBSD, Linux, // or cygwin, and can only be used on systems which support // the use of dladdr(). // // Note: On linux and cygwin this uses /proc/self/exe to find the path. // // Note: On Apple it uses _NSGetExecutablePath(). // // Note: On FreeBSD it uses getprogpath(). // // Note: Otherwise it uses dladdr(). // resource_path = CompilerInvocation::GetResourcesPath("cling", (void*)(intptr_t) locate_cling_executable ); } if (!llvm::sys::fs::is_directory(resource_path.str())) { llvm::errs() << "ERROR in cling::CIFactory::createCI():\n resource directory " << resource_path.str() << " not found!\n"; resource_path = ""; } DiagnosticOptions* DefaultDiagnosticOptions = new DiagnosticOptions(); DefaultDiagnosticOptions->ShowColors = llvm::sys::Process::StandardErrHasColors() ? 1 : 0; TextDiagnosticPrinter* DiagnosticPrinter = new TextDiagnosticPrinter(llvm::errs(), DefaultDiagnosticOptions); llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagIDs(new DiagnosticIDs()); DiagnosticsEngine* Diagnostics = new DiagnosticsEngine(DiagIDs, DefaultDiagnosticOptions, DiagnosticPrinter, /*Owns it*/ true); // LEAKS! std::vector<const char*> argvCompile(argv, argv + argc); // We do C++ by default; append right after argv[0] name // Only insert it if there is no other "-x": bool haveMinusX = false; for (const char* const* iarg = argv; !haveMinusX && iarg < argv + argc; ++iarg) { haveMinusX = !strcmp(*iarg, "-x"); } if (!haveMinusX) { argvCompile.insert(argvCompile.begin() + 1,"-x"); argvCompile.insert(argvCompile.begin() + 2, "c++"); } argvCompile.push_back("-c"); argvCompile.push_back("-"); clang::driver::Driver Driver(argv[0], llvm::sys::getDefaultTargetTriple(), "cling.out", *Diagnostics); //Driver.setWarnMissingInput(false); Driver.setCheckInputsExist(false); // think foo.C(12) llvm::ArrayRef<const char*>RF(&(argvCompile[0]), argvCompile.size()); llvm::OwningPtr<clang::driver::Compilation> Compilation(Driver.BuildCompilation(RF)); const clang::driver::ArgStringList* CC1Args = GetCC1Arguments(Diagnostics, Compilation.get()); if (CC1Args == NULL) { return 0; } clang::CompilerInvocation* Invocation = new clang::CompilerInvocation; clang::CompilerInvocation::CreateFromArgs(*Invocation, CC1Args->data() + 1, CC1Args->data() + CC1Args->size(), *Diagnostics); Invocation->getFrontendOpts().DisableFree = true; if (Invocation->getHeaderSearchOpts().UseBuiltinIncludes && !resource_path.empty()) { // Update ResourceDir // header search opts' entry for resource_path/include isn't // updated by providing a new resource path; update it manually. clang::HeaderSearchOptions& Opts = Invocation->getHeaderSearchOpts(); llvm::SmallString<512> oldResInc(Opts.ResourceDir); llvm::sys::path::append(oldResInc, "include"); llvm::SmallString<512> newResInc(resource_path); llvm::sys::path::append(newResInc, "include"); bool foundOldResInc = false; for (unsigned i = 0, e = Opts.UserEntries.size(); !foundOldResInc && i != e; ++i) { HeaderSearchOptions::Entry &E = Opts.UserEntries[i]; if (!E.IsFramework && E.Group == clang::frontend::System && E.IgnoreSysRoot && oldResInc.str() == E.Path) { E.Path = newResInc.c_str(); foundOldResInc = true; } } Opts.ResourceDir = resource_path.str(); } // Create and setup a compiler instance. CompilerInstance* CI = new CompilerInstance(); CI->setInvocation(Invocation); CI->createDiagnostics(DiagnosticPrinter, /*ShouldOwnClient=*/ false); { // // Buffer the error messages while we process // the compiler options. // // Set the language options, which cling needs SetClingCustomLangOpts(CI->getLangOpts()); CI->getInvocation().getPreprocessorOpts().addMacroDef("__CLING__"); if (CI->getLangOpts().CPlusPlus11 == 1) { // http://llvm.org/bugs/show_bug.cgi?id=13530 CI->getInvocation().getPreprocessorOpts() .addMacroDef("__CLING__CXX11"); } if (CI->getDiagnostics().hasErrorOccurred()) { delete CI; CI = 0; return 0; } } CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(), &Invocation->getTargetOpts())); if (!CI->hasTarget()) { delete CI; CI = 0; return 0; } CI->getTarget().setForcedLangOptions(CI->getLangOpts()); SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget()); if (CI->getTarget().getTriple().getOS() == llvm::Triple::Cygwin) { // clang "forgets" the basic arch part needed by winnt.h: if (CI->getTarget().getTriple().getArch() == llvm::Triple::x86) { CI->getInvocation().getPreprocessorOpts().addMacroDef("_X86_=1"); } else if (CI->getTarget().getTriple().getArch() == llvm::Triple::x86_64) { CI->getInvocation().getPreprocessorOpts().addMacroDef("__x86_64=1"); } else { llvm::errs() << "Warning: unhandled target architecture " << CI->getTarget().getTriple().getArchName() << '\n'; } } // Set up source and file managers CI->createFileManager(); SourceManager* SM = new SourceManager(CI->getDiagnostics(), CI->getFileManager(), /*UserFilesAreVolatile*/ true); CI->setSourceManager(SM); // FIXME: SM leaks. // As main file we want // * a virtual file that is claiming to be huge // * with an empty memory buffer attached (to bring the content) FileManager& FM = SM->getFileManager(); // Build the virtual file const char* Filename = "InteractiveInputLineIncluder.h"; const std::string& CGOptsMainFileName = CI->getInvocation().getCodeGenOpts().MainFileName; if (!CGOptsMainFileName.empty()) Filename = CGOptsMainFileName.c_str(); const FileEntry* FE = FM.getVirtualFile(Filename, 1U << 15U, time(0)); FileID MainFileID = SM->createMainFileID(FE, SrcMgr::C_User); const SrcMgr::SLocEntry& MainFileSLocE = SM->getSLocEntry(MainFileID); const SrcMgr::ContentCache* MainFileCC = MainFileSLocE.getFile().getContentCache(); if (!buffer) buffer = llvm::MemoryBuffer::getMemBuffer("/*CLING DEFAULT MEMBUF*/\n"); const_cast<SrcMgr::ContentCache*>(MainFileCC)->setBuffer(buffer); // Set up the preprocessor CI->createPreprocessor(); Preprocessor& PP = CI->getPreprocessor(); PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(), PP.getLangOpts()); // Set up the ASTContext ASTContext *Ctx = new ASTContext(CI->getLangOpts(), PP.getSourceManager(), &CI->getTarget(), PP.getIdentifierTable(), PP.getSelectorTable(), PP.getBuiltinInfo(), /*size_reserve*/0, /*DelayInit*/false); CI->setASTContext(Ctx); //FIXME: This is bad workaround for use-cases which need only a CI to parse //things, like pragmas. In that case we cannot controll the interpreter's // state collector thus detach from whatever possible. if (stateCollector) { // Add the callback keeping track of the macro definitions PP.addPPCallbacks(stateCollector); } else stateCollector = new DeclCollector(); // Set up the ASTConsumers CI->setASTConsumer(stateCollector); // Set up Sema CodeCompleteConsumer* CCC = 0; CI->createSema(TU_Complete, CCC); CI->takeASTConsumer(); // Transfer to ownership to the PP only // Set CodeGen options // CI->getCodeGenOpts().DebugInfo = 1; // want debug info // CI->getCodeGenOpts().EmitDeclMetadata = 1; // For unloading, for later CI->getCodeGenOpts().OptimizationLevel = 0; // see pure SSA, that comes out CI->getCodeGenOpts().CXXCtorDtorAliases = 0; // aliasing the complete // ctor to the base ctor causes // the JIT to crash // When asserts are on, TURN ON not compare the VerifyModule assert(CI->getCodeGenOpts().VerifyModule = 1); return CI; } void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) { Opts.EmitAllDecls = 0; // Otherwise if PCH attached will codegen all decls. Opts.Exceptions = 1; Opts.CXXExceptions = 1; Opts.Deprecated = 1; //Opts.Modules = 1; // C++11 is turned on if cling is built with C++11: it's an interperter; // cross-language compilation doesn't make sense. // Extracted from Boost/config/compiler. // SunProCC has no C++11. // VisualC's support is not obvious to extract from Boost... #if /*GCC*/ (defined(__GNUC__) && defined(__GXX_EXPERIMENTAL_CXX0X__)) \ || /*clang*/ (defined(__has_feature) && __has_feature(cxx_decltype)) \ || /*ICC*/ ((!(defined(_WIN32) || defined(_WIN64)) && defined(__STDC_HOSTED__) && defined(__INTEL_COMPILER) && (__STDC_HOSTED__ && (__INTEL_COMPILER <= 1200))) || defined(__GXX_EXPERIMENTAL_CPP0X__)) Opts.CPlusPlus11 = 1; #endif } void CIFactory::SetClingTargetLangOpts(LangOptions& Opts, const TargetInfo& Target) { if (Target.getTriple().getOS() == llvm::Triple::Win32) { Opts.MicrosoftExt = 1; Opts.MSCVersion = 1300; // Should fix http://llvm.org/bugs/show_bug.cgi?id=10528 Opts.DelayedTemplateParsing = 1; } else { Opts.MicrosoftExt = 0; } } } // end namespace <|endoftext|>
<commit_before> /* pbrt source code Copyright(c) 1998-2010 Matt Pharr and Greg Humphreys. This file is part of pbrt. pbrt 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. Note that the text contents of the book "Physically Based Rendering" are *not* licensed under the GNU GPL. pbrt is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ // integrators/dipolesubsurface.cpp* #include "integrators/dipolesubsurface.h" #include "scene.h" #include "montecarlo.h" #include "sampler.h" #include "progressreporter.h" #include "intersection.h" #include "paramset.h" #include "reflection.h" #include "octree.h" #include "camera.h" #include "floatfile.h" struct DiffusionReflectance; // DipoleSubsurfaceIntegrator Local Declarations struct SubsurfaceOctreeNode { // SubsurfaceOctreeNode Methods SubsurfaceOctreeNode() { isLeaf = true; sumArea = 0.f; for (int i = 0; i < 8; ++i) ips[i] = NULL; } void Insert(const BBox &nodeBound, IrradiancePoint *ip, MemoryArena &arena) { Point pMid = .5f * nodeBound.pMin + .5f * nodeBound.pMax; if (isLeaf) { // Add _IrradiancePoint_ to leaf octree node for (int i = 0; i < 8; ++i) { if (!ips[i]) { ips[i] = ip; return; } } // Convert leaf node to interior node, redistribute points isLeaf = false; IrradiancePoint *localIps[8]; for (int i = 0; i < 8; ++i) { localIps[i] = ips[i]; children[i] = NULL; } for (int i = 0; i < 8; ++i) { IrradiancePoint *ip = localIps[i]; // Add _IrradiancePoint_ _ip_ to interior octree node int child = (ip->p.x > pMid.x ? 4 : 0) + (ip->p.y > pMid.y ? 2 : 0) + (ip->p.z > pMid.z ? 1 : 0); if (!children[child]) children[child] = arena.Alloc<SubsurfaceOctreeNode>(); BBox childBound = octreeChildBound(child, nodeBound, pMid); children[child]->Insert(childBound, ip, arena); } /* fall through to interior case to insert the new point... */ } // Add _IrradiancePoint_ _ip_ to interior octree node int child = (ip->p.x > pMid.x ? 4 : 0) + (ip->p.y > pMid.y ? 2 : 0) + (ip->p.z > pMid.z ? 1 : 0); if (!children[child]) children[child] = arena.Alloc<SubsurfaceOctreeNode>(); BBox childBound = octreeChildBound(child, nodeBound, pMid); children[child]->Insert(childBound, ip, arena); } void InitHierarchy() { if (isLeaf) { // Init _SubsurfaceOctreeNode_ leaf from _IrradiancePoint_s float sumWt = 0.f; uint32_t i; for (i = 0; i < 8; ++i) { if (!ips[i]) break; float wt = ips[i]->E.y(); E += ips[i]->E; p += wt * ips[i]->p; sumWt += wt; sumArea += ips[i]->area; } if (sumWt > 0.f) p /= sumWt; E /= i; } else { // Init interior _SubsurfaceOctreeNode_ float sumWt = 0.f; uint32_t nChildren = 0; for (uint32_t i = 0; i < 8; ++i) { if (!children[i]) continue; ++nChildren; children[i]->InitHierarchy(); float wt = children[i]->E.y(); E += children[i]->E; p += wt * children[i]->p; sumWt += wt; sumArea += children[i]->sumArea; } if (sumWt > 0.f) p /= sumWt; E /= nChildren; } } Spectrum Mo(const BBox &nodeBound, const Point &p, const DiffusionReflectance &Rd, float maxError); // SubsurfaceOctreeNode Public Data Point p; bool isLeaf; Spectrum E; float sumArea; union { SubsurfaceOctreeNode *children[8]; IrradiancePoint *ips[8]; }; }; struct DiffusionReflectance { // DiffusionReflectance Public Methods DiffusionReflectance(const Spectrum &sigma_a, const Spectrum &sigmap_s, float eta) { A = (1.f + Fdr(eta)) / (1.f - Fdr(eta)); sigmap_t = sigma_a + sigmap_s; sigma_tr = Sqrt(3.f * sigma_a * sigmap_t); alphap = sigmap_s / sigmap_t; zpos = Spectrum(1.f) / sigmap_t; zneg = zpos * (1.f + (4.f/3.f) * A); } Spectrum operator()(float d2) const { Spectrum dpos = Sqrt(Spectrum(d2) + zpos * zpos); Spectrum dneg = Sqrt(Spectrum(d2) + zneg * zneg); Spectrum Rd = (1.f / (4.f * M_PI)) * ((zpos * (dpos * sigma_tr + Spectrum(1.f)) * Exp(-sigma_tr * dpos)) / (dpos * dpos * dpos) - (zneg * (dneg * sigma_tr + Spectrum(1.f)) * Exp(-sigma_tr * dneg)) / (dneg * dneg * dneg)); return Rd.Clamp(); } // DiffusionReflectance Data Spectrum zpos, zneg, sigmap_t, sigma_tr, alphap; float A; }; // DipoleSubsurfaceIntegrator Method Definitions DipoleSubsurfaceIntegrator::~DipoleSubsurfaceIntegrator() { delete[] lightSampleOffsets; delete[] bsdfSampleOffsets; } void DipoleSubsurfaceIntegrator::RequestSamples(Sampler *sampler, Sample *sample, const Scene *scene) { // Allocate and request samples for sampling all lights uint32_t nLights = scene->lights.size(); lightSampleOffsets = new LightSampleOffsets[nLights]; bsdfSampleOffsets = new BSDFSampleOffsets[nLights]; for (uint32_t i = 0; i < nLights; ++i) { const Light *light = scene->lights[i]; int nSamples = light->nSamples; if (sampler) nSamples = sampler->RoundSize(nSamples); lightSampleOffsets[i] = LightSampleOffsets(nSamples, sample); bsdfSampleOffsets[i] = BSDFSampleOffsets(nSamples, sample); } } void DipoleSubsurfaceIntegrator::Preprocess(const Scene *scene, const Camera *camera, const Renderer *renderer) { if (scene->lights.size() == 0) return; vector<SurfacePoint> pts; // Get _SurfacePoint_s for translucent objects in scene if (filename != "") { // Initialize _SurfacePoint_s from file vector<float> fpts; if (ReadFloatFile(filename.c_str(), &fpts)) { if ((fpts.size() % 8) != 0) Error("Excess values (%d) in points file \"%s\"", int(fpts.size() % 8), filename.c_str()); for (u_int i = 0; i < fpts.size(); i += 8) pts.push_back(SurfacePoint(Point(fpts[i], fpts[i+1], fpts[i+2]), Normal(fpts[i+3], fpts[i+4], fpts[i+5]), fpts[i+6], fpts[i+7])); } } if (pts.size() == 0) { Point pCamera = camera->CameraToWorld(camera->shutterOpen, Point(0, 0, 0)); FindPoissonPointDistribution(pCamera, camera->shutterOpen, minSampleDist, scene, &pts); } // Compute irradiance values at sample points RNG rng; MemoryArena arena; PBRT_SUBSURFACE_STARTED_COMPUTING_IRRADIANCE_VALUES(); ProgressReporter progress(pts.size(), "Computing Irradiances"); for (uint32_t i = 0; i < pts.size(); ++i) { SurfacePoint &sp = pts[i]; Spectrum E(0.f); for (uint32_t j = 0; j < scene->lights.size(); ++j) { // Add irradiance from light at point const Light *light = scene->lights[j]; Spectrum Elight = 0.f; int nSamples = RoundUpPow2(light->nSamples); uint32_t scramble[2] = { rng.RandomUInt(), rng.RandomUInt() }; uint32_t compScramble = rng.RandomUInt(); for (int s = 0; s < nSamples; ++s) { float lpos[2]; Sample02(s, scramble, lpos); float lcomp = VanDerCorput(s, compScramble); LightSample ls(lpos[0], lpos[1], lcomp); Vector wi; float lightPdf; VisibilityTester visibility; Spectrum Li = light->Sample_L(sp.p, sp.rayEpsilon, ls, camera->shutterOpen, &wi, &lightPdf, &visibility); if (Dot(wi, sp.n) <= 0.) continue; if (Li.IsBlack() || lightPdf == 0.f) continue; Li *= visibility.Transmittance(scene, renderer, NULL, rng, arena); if (visibility.Unoccluded(scene)) Elight += Li * AbsDot(wi, sp.n) / lightPdf; } E += Elight / nSamples; } if (E.y() > 0.f) { irradiancePoints.push_back(IrradiancePoint(sp, E)); PBRT_SUBSURFACE_COMPUTED_IRRADIANCE_AT_POINT(&sp, &E); } arena.FreeAll(); progress.Update(); } progress.Done(); PBRT_SUBSURFACE_FINISHED_COMPUTING_IRRADIANCE_VALUES(); // Create octree of clustered irradiance samples octree = octreeArena.Alloc<SubsurfaceOctreeNode>(); for (uint32_t i = 0; i < irradiancePoints.size(); ++i) octreeBounds = Union(octreeBounds, irradiancePoints[i].p); for (uint32_t i = 0; i < irradiancePoints.size(); ++i) octree->Insert(octreeBounds, &irradiancePoints[i], octreeArena); octree->InitHierarchy(); } Spectrum DipoleSubsurfaceIntegrator::Li(const Scene *scene, const Renderer *renderer, const RayDifferential &ray, const Intersection &isect, const Sample *sample, RNG &rng, MemoryArena &arena) const { Spectrum L(0.); Vector wo = -ray.d; // Compute emitted light if ray hit an area light source L += isect.Le(wo); // Evaluate BSDF at hit point BSDF *bsdf = isect.GetBSDF(ray, arena); const Point &p = bsdf->dgShading.p; const Normal &n = bsdf->dgShading.nn; // Evaluate BSSRDF and possibly compute subsurface scattering BSSRDF *bssrdf = isect.GetBSSRDF(ray, arena); if (bssrdf && octree) { Spectrum sigma_a = bssrdf->sigma_a(); Spectrum sigmap_s = bssrdf->sigma_prime_s(); Spectrum sigmap_t = sigmap_s + sigma_a; if (!sigmap_t.IsBlack()) { // Use hierarchical integration to evaluate reflection from dipole model PBRT_SUBSURFACE_STARTED_OCTREE_LOOKUP(const_cast<Point *>(&p)); DiffusionReflectance Rd(sigma_a, sigmap_s, bssrdf->eta()); Spectrum Mo = octree->Mo(octreeBounds, p, Rd, maxError); FresnelDielectric fresnel(1.f, bssrdf->eta()); Spectrum Ft = Spectrum(1.f) - fresnel.Evaluate(AbsDot(wo, n)); float Fdt = 1.f - Fdr(bssrdf->eta()); L += (INV_PI * Ft) * (Fdt * Mo); PBRT_SUBSURFACE_FINISHED_OCTREE_LOOKUP(); } } L += UniformSampleAllLights(scene, renderer, arena, p, n, wo, isect.rayEpsilon, ray.time, bsdf, sample, rng, lightSampleOffsets, bsdfSampleOffsets); if (ray.depth < maxSpecularDepth) { // Trace rays for specular reflection and refraction L += SpecularReflect(ray, bsdf, rng, isect, renderer, scene, sample, arena); L += SpecularTransmit(ray, bsdf, rng, isect, renderer, scene, sample, arena); } return L; } Spectrum SubsurfaceOctreeNode::Mo(const BBox &nodeBound, const Point &pt, const DiffusionReflectance &Rd, float maxError) { // Compute $M_\roman{o}$ at node if error is low enough float dw = sumArea / DistanceSquared(pt, p); if (dw < maxError && !nodeBound.Inside(pt)) { PBRT_SUBSURFACE_ADDED_INTERIOR_CONTRIBUTION(const_cast<SubsurfaceOctreeNode *>(this)); return Rd(DistanceSquared(pt, p)) * E * sumArea; } // Otherwise comupte $M_\roman{o}$ from points in leaf or recursively visit children Spectrum Mo = 0.f; if (isLeaf) { // Accumulate $M_\roman{o}$ from leaf node for (int i = 0; i < 8; ++i) { if (!ips[i]) break; PBRT_SUBSURFACE_ADDED_POINT_CONTRIBUTION(const_cast<IrradiancePoint *>(ips[i])); Mo += Rd(DistanceSquared(pt, ips[i]->p)) * ips[i]->E * ips[i]->area; } } else { // Recursively visit children nodes to compute $M_\roman{o}$ Point pMid = .5f * nodeBound.pMin + .5f * nodeBound.pMax; for (int child = 0; child < 8; ++child) { if (!children[child]) continue; BBox childBound = octreeChildBound(child, nodeBound, pMid); Mo += children[child]->Mo(childBound, pt, Rd, maxError); } } return Mo; } DipoleSubsurfaceIntegrator *CreateDipoleSubsurfaceIntegrator(const ParamSet &params) { int maxDepth = params.FindOneInt("maxdepth", 5); float maxError = params.FindOneFloat("maxerror", .05f); float minDist = params.FindOneFloat("minsampledistance", .25f); string pointsfile = params.FindOneString("pointsfile", ""); if (PbrtOptions.quickRender) { maxError *= 4.f; minDist *= 4.f; } return new DipoleSubsurfaceIntegrator(maxDepth, maxError, minDist, pointsfile); } <commit_msg>In DipoleSubsurfaceIntegrator, still create IrradiancePoints if incident irradiance is zero.<commit_after> /* pbrt source code Copyright(c) 1998-2010 Matt Pharr and Greg Humphreys. This file is part of pbrt. pbrt 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. Note that the text contents of the book "Physically Based Rendering" are *not* licensed under the GNU GPL. pbrt is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ // integrators/dipolesubsurface.cpp* #include "integrators/dipolesubsurface.h" #include "scene.h" #include "montecarlo.h" #include "sampler.h" #include "progressreporter.h" #include "intersection.h" #include "paramset.h" #include "reflection.h" #include "octree.h" #include "camera.h" #include "floatfile.h" struct DiffusionReflectance; // DipoleSubsurfaceIntegrator Local Declarations struct SubsurfaceOctreeNode { // SubsurfaceOctreeNode Methods SubsurfaceOctreeNode() { isLeaf = true; sumArea = 0.f; for (int i = 0; i < 8; ++i) ips[i] = NULL; } void Insert(const BBox &nodeBound, IrradiancePoint *ip, MemoryArena &arena) { Point pMid = .5f * nodeBound.pMin + .5f * nodeBound.pMax; if (isLeaf) { // Add _IrradiancePoint_ to leaf octree node for (int i = 0; i < 8; ++i) { if (!ips[i]) { ips[i] = ip; return; } } // Convert leaf node to interior node, redistribute points isLeaf = false; IrradiancePoint *localIps[8]; for (int i = 0; i < 8; ++i) { localIps[i] = ips[i]; children[i] = NULL; } for (int i = 0; i < 8; ++i) { IrradiancePoint *ip = localIps[i]; // Add _IrradiancePoint_ _ip_ to interior octree node int child = (ip->p.x > pMid.x ? 4 : 0) + (ip->p.y > pMid.y ? 2 : 0) + (ip->p.z > pMid.z ? 1 : 0); if (!children[child]) children[child] = arena.Alloc<SubsurfaceOctreeNode>(); BBox childBound = octreeChildBound(child, nodeBound, pMid); children[child]->Insert(childBound, ip, arena); } /* fall through to interior case to insert the new point... */ } // Add _IrradiancePoint_ _ip_ to interior octree node int child = (ip->p.x > pMid.x ? 4 : 0) + (ip->p.y > pMid.y ? 2 : 0) + (ip->p.z > pMid.z ? 1 : 0); if (!children[child]) children[child] = arena.Alloc<SubsurfaceOctreeNode>(); BBox childBound = octreeChildBound(child, nodeBound, pMid); children[child]->Insert(childBound, ip, arena); } void InitHierarchy() { if (isLeaf) { // Init _SubsurfaceOctreeNode_ leaf from _IrradiancePoint_s float sumWt = 0.f; uint32_t i; for (i = 0; i < 8; ++i) { if (!ips[i]) break; float wt = ips[i]->E.y(); E += ips[i]->E; p += wt * ips[i]->p; sumWt += wt; sumArea += ips[i]->area; } if (sumWt > 0.f) p /= sumWt; E /= i; } else { // Init interior _SubsurfaceOctreeNode_ float sumWt = 0.f; uint32_t nChildren = 0; for (uint32_t i = 0; i < 8; ++i) { if (!children[i]) continue; ++nChildren; children[i]->InitHierarchy(); float wt = children[i]->E.y(); E += children[i]->E; p += wt * children[i]->p; sumWt += wt; sumArea += children[i]->sumArea; } if (sumWt > 0.f) p /= sumWt; E /= nChildren; } } Spectrum Mo(const BBox &nodeBound, const Point &p, const DiffusionReflectance &Rd, float maxError); // SubsurfaceOctreeNode Public Data Point p; bool isLeaf; Spectrum E; float sumArea; union { SubsurfaceOctreeNode *children[8]; IrradiancePoint *ips[8]; }; }; struct DiffusionReflectance { // DiffusionReflectance Public Methods DiffusionReflectance(const Spectrum &sigma_a, const Spectrum &sigmap_s, float eta) { A = (1.f + Fdr(eta)) / (1.f - Fdr(eta)); sigmap_t = sigma_a + sigmap_s; sigma_tr = Sqrt(3.f * sigma_a * sigmap_t); alphap = sigmap_s / sigmap_t; zpos = Spectrum(1.f) / sigmap_t; zneg = zpos * (1.f + (4.f/3.f) * A); } Spectrum operator()(float d2) const { Spectrum dpos = Sqrt(Spectrum(d2) + zpos * zpos); Spectrum dneg = Sqrt(Spectrum(d2) + zneg * zneg); Spectrum Rd = (1.f / (4.f * M_PI)) * ((zpos * (dpos * sigma_tr + Spectrum(1.f)) * Exp(-sigma_tr * dpos)) / (dpos * dpos * dpos) - (zneg * (dneg * sigma_tr + Spectrum(1.f)) * Exp(-sigma_tr * dneg)) / (dneg * dneg * dneg)); return Rd.Clamp(); } // DiffusionReflectance Data Spectrum zpos, zneg, sigmap_t, sigma_tr, alphap; float A; }; // DipoleSubsurfaceIntegrator Method Definitions DipoleSubsurfaceIntegrator::~DipoleSubsurfaceIntegrator() { delete[] lightSampleOffsets; delete[] bsdfSampleOffsets; } void DipoleSubsurfaceIntegrator::RequestSamples(Sampler *sampler, Sample *sample, const Scene *scene) { // Allocate and request samples for sampling all lights uint32_t nLights = scene->lights.size(); lightSampleOffsets = new LightSampleOffsets[nLights]; bsdfSampleOffsets = new BSDFSampleOffsets[nLights]; for (uint32_t i = 0; i < nLights; ++i) { const Light *light = scene->lights[i]; int nSamples = light->nSamples; if (sampler) nSamples = sampler->RoundSize(nSamples); lightSampleOffsets[i] = LightSampleOffsets(nSamples, sample); bsdfSampleOffsets[i] = BSDFSampleOffsets(nSamples, sample); } } void DipoleSubsurfaceIntegrator::Preprocess(const Scene *scene, const Camera *camera, const Renderer *renderer) { if (scene->lights.size() == 0) return; vector<SurfacePoint> pts; // Get _SurfacePoint_s for translucent objects in scene if (filename != "") { // Initialize _SurfacePoint_s from file vector<float> fpts; if (ReadFloatFile(filename.c_str(), &fpts)) { if ((fpts.size() % 8) != 0) Error("Excess values (%d) in points file \"%s\"", int(fpts.size() % 8), filename.c_str()); for (u_int i = 0; i < fpts.size(); i += 8) pts.push_back(SurfacePoint(Point(fpts[i], fpts[i+1], fpts[i+2]), Normal(fpts[i+3], fpts[i+4], fpts[i+5]), fpts[i+6], fpts[i+7])); } } if (pts.size() == 0) { Point pCamera = camera->CameraToWorld(camera->shutterOpen, Point(0, 0, 0)); FindPoissonPointDistribution(pCamera, camera->shutterOpen, minSampleDist, scene, &pts); } // Compute irradiance values at sample points RNG rng; MemoryArena arena; PBRT_SUBSURFACE_STARTED_COMPUTING_IRRADIANCE_VALUES(); ProgressReporter progress(pts.size(), "Computing Irradiances"); for (uint32_t i = 0; i < pts.size(); ++i) { SurfacePoint &sp = pts[i]; Spectrum E(0.f); for (uint32_t j = 0; j < scene->lights.size(); ++j) { // Add irradiance from light at point const Light *light = scene->lights[j]; Spectrum Elight = 0.f; int nSamples = RoundUpPow2(light->nSamples); uint32_t scramble[2] = { rng.RandomUInt(), rng.RandomUInt() }; uint32_t compScramble = rng.RandomUInt(); for (int s = 0; s < nSamples; ++s) { float lpos[2]; Sample02(s, scramble, lpos); float lcomp = VanDerCorput(s, compScramble); LightSample ls(lpos[0], lpos[1], lcomp); Vector wi; float lightPdf; VisibilityTester visibility; Spectrum Li = light->Sample_L(sp.p, sp.rayEpsilon, ls, camera->shutterOpen, &wi, &lightPdf, &visibility); if (Dot(wi, sp.n) <= 0.) continue; if (Li.IsBlack() || lightPdf == 0.f) continue; Li *= visibility.Transmittance(scene, renderer, NULL, rng, arena); if (visibility.Unoccluded(scene)) Elight += Li * AbsDot(wi, sp.n) / lightPdf; } E += Elight / nSamples; } irradiancePoints.push_back(IrradiancePoint(sp, E)); PBRT_SUBSURFACE_COMPUTED_IRRADIANCE_AT_POINT(&sp, &E); arena.FreeAll(); progress.Update(); } progress.Done(); PBRT_SUBSURFACE_FINISHED_COMPUTING_IRRADIANCE_VALUES(); // Create octree of clustered irradiance samples octree = octreeArena.Alloc<SubsurfaceOctreeNode>(); for (uint32_t i = 0; i < irradiancePoints.size(); ++i) octreeBounds = Union(octreeBounds, irradiancePoints[i].p); for (uint32_t i = 0; i < irradiancePoints.size(); ++i) octree->Insert(octreeBounds, &irradiancePoints[i], octreeArena); octree->InitHierarchy(); } Spectrum DipoleSubsurfaceIntegrator::Li(const Scene *scene, const Renderer *renderer, const RayDifferential &ray, const Intersection &isect, const Sample *sample, RNG &rng, MemoryArena &arena) const { Spectrum L(0.); Vector wo = -ray.d; // Compute emitted light if ray hit an area light source L += isect.Le(wo); // Evaluate BSDF at hit point BSDF *bsdf = isect.GetBSDF(ray, arena); const Point &p = bsdf->dgShading.p; const Normal &n = bsdf->dgShading.nn; // Evaluate BSSRDF and possibly compute subsurface scattering BSSRDF *bssrdf = isect.GetBSSRDF(ray, arena); if (bssrdf && octree) { Spectrum sigma_a = bssrdf->sigma_a(); Spectrum sigmap_s = bssrdf->sigma_prime_s(); Spectrum sigmap_t = sigmap_s + sigma_a; if (!sigmap_t.IsBlack()) { // Use hierarchical integration to evaluate reflection from dipole model PBRT_SUBSURFACE_STARTED_OCTREE_LOOKUP(const_cast<Point *>(&p)); DiffusionReflectance Rd(sigma_a, sigmap_s, bssrdf->eta()); Spectrum Mo = octree->Mo(octreeBounds, p, Rd, maxError); FresnelDielectric fresnel(1.f, bssrdf->eta()); Spectrum Ft = Spectrum(1.f) - fresnel.Evaluate(AbsDot(wo, n)); float Fdt = 1.f - Fdr(bssrdf->eta()); L += (INV_PI * Ft) * (Fdt * Mo); PBRT_SUBSURFACE_FINISHED_OCTREE_LOOKUP(); } } L += UniformSampleAllLights(scene, renderer, arena, p, n, wo, isect.rayEpsilon, ray.time, bsdf, sample, rng, lightSampleOffsets, bsdfSampleOffsets); if (ray.depth < maxSpecularDepth) { // Trace rays for specular reflection and refraction L += SpecularReflect(ray, bsdf, rng, isect, renderer, scene, sample, arena); L += SpecularTransmit(ray, bsdf, rng, isect, renderer, scene, sample, arena); } return L; } Spectrum SubsurfaceOctreeNode::Mo(const BBox &nodeBound, const Point &pt, const DiffusionReflectance &Rd, float maxError) { // Compute $M_\roman{o}$ at node if error is low enough float dw = sumArea / DistanceSquared(pt, p); if (dw < maxError && !nodeBound.Inside(pt)) { PBRT_SUBSURFACE_ADDED_INTERIOR_CONTRIBUTION(const_cast<SubsurfaceOctreeNode *>(this)); return Rd(DistanceSquared(pt, p)) * E * sumArea; } // Otherwise comupte $M_\roman{o}$ from points in leaf or recursively visit children Spectrum Mo = 0.f; if (isLeaf) { // Accumulate $M_\roman{o}$ from leaf node for (int i = 0; i < 8; ++i) { if (!ips[i]) break; PBRT_SUBSURFACE_ADDED_POINT_CONTRIBUTION(const_cast<IrradiancePoint *>(ips[i])); Mo += Rd(DistanceSquared(pt, ips[i]->p)) * ips[i]->E * ips[i]->area; } } else { // Recursively visit children nodes to compute $M_\roman{o}$ Point pMid = .5f * nodeBound.pMin + .5f * nodeBound.pMax; for (int child = 0; child < 8; ++child) { if (!children[child]) continue; BBox childBound = octreeChildBound(child, nodeBound, pMid); Mo += children[child]->Mo(childBound, pt, Rd, maxError); } } return Mo; } DipoleSubsurfaceIntegrator *CreateDipoleSubsurfaceIntegrator(const ParamSet &params) { int maxDepth = params.FindOneInt("maxdepth", 5); float maxError = params.FindOneFloat("maxerror", .05f); float minDist = params.FindOneFloat("minsampledistance", .25f); string pointsfile = params.FindOneString("pointsfile", ""); if (PbrtOptions.quickRender) { maxError *= 4.f; minDist *= 4.f; } return new DipoleSubsurfaceIntegrator(maxDepth, maxError, minDist, pointsfile); } <|endoftext|>
<commit_before>/* * RingBufferSubHistory.cpp * * Created on: 20.05.2016 * Author: hartung */ #include "synchronization/RingBufferSubHistory.hpp" namespace Synchronization { size_type RingBufferSubHistory::size() const { return _numAddedElems; } real_type RingBufferSubHistory::getNewestTime() const { return _entries[_lastInsertedElem].getTime(); } FMI::ValueCollection RingBufferSubHistory::interpolate(const real_type& time) { while(_entries[_curIndex].getTime() < time) { if(++_curIndex == _entries.size()) _curIndex = 0; } if(std::abs(_entries[_curIndex].getTime()-time) < _interpolation.getTolerance()) return _entries[_curIndex].getValueCollection(); tuple<size_type,size_type> range = checkValidEntries(); return _interpolation.interpolateHistory(_entries,range,_curIndex,time); } FMI::ValueCollection RingBufferSubHistory::operator [](const real_type& time) { return interpolate(time); } const Interpolation& RingBufferSubHistory::getInterpolation() const { return _interpolation; } RingBufferSubHistory::RingBufferSubHistory(const Interpolation& interpolation, const FMI::ValueCollection& bufferScheme, size_type size) : _curIndex(0), _lastInsertedElem(size - 1), _entries(std::vector<HistoryEntry>(size, HistoryEntry(bufferScheme))), _interpolation(interpolation), _numAddedElems(0) { } bool_type RingBufferSubHistory::insert(const HistoryEntry& in) { bool res = true; //LOGGER_WRITE("Insert " + to_string(in.getTime()) + " into history.",Util::LC_SOLVER, Util::LL_DEBUG); if (in.getTime() >= _entries[_lastInsertedElem].getTime()) { if (++_lastInsertedElem == _entries.size()) _lastInsertedElem = 0; _entries[_lastInsertedElem] = in; ++_numAddedElems; } else { throw std::runtime_error("RingBufferSubHistory: Can't insert values older than the newest in the history"); res = false; } return res; } size_type RingBufferSubHistory::deleteOlderThan(const HistoryEntry& in) { // ring buffer, it deletes it naturally return 1u; } tuple<size_type, size_type> RingBufferSubHistory::checkValidEntries() const { if(_numAddedElems > 1) { return std::make_tuple(((_curIndex == 0) ? _entries.size()-1 : _curIndex-1),_curIndex); } else throw std::runtime_error("RingBufferSubHistory: Not enough data for interpolation."); } } /* namespace Synchronization */ <commit_msg>Harmonize files<commit_after>/* * RingBufferSubHistory.cpp * * Created on: 20.05.2016 * Author: hartung */ #include "synchronization/RingBufferSubHistory.hpp" namespace Synchronization { size_type RingBufferSubHistory::size() const { return _numAddedElems; } real_type RingBufferSubHistory::getNewestTime() const { return _entries[_lastInsertedElem].getTime(); } FMI::ValueCollection RingBufferSubHistory::interpolate(const real_type & time) { while (_entries[_curIndex].getTime() < time) { if (++_curIndex == _entries.size()) _curIndex = 0; } if (std::abs(_entries[_curIndex].getTime() - time) < _interpolation.getTolerance()) return _entries[_curIndex].getValueCollection(); tuple<size_type, size_type> range = checkValidEntries(); return _interpolation.interpolateHistory(_entries, range, _curIndex, time); } FMI::ValueCollection RingBufferSubHistory::operator [](const real_type& time) { return interpolate(time); } const Interpolation & RingBufferSubHistory::getInterpolation() const { return _interpolation; } RingBufferSubHistory::RingBufferSubHistory(const Interpolation & interpolation, const FMI::ValueCollection & bufferScheme, size_type size) : _curIndex(0), _lastInsertedElem(size - 1), _entries(std::vector<HistoryEntry>(size, HistoryEntry(bufferScheme))), _interpolation(interpolation), _numAddedElems(0) { } bool_type RingBufferSubHistory::insert(const HistoryEntry & in) { bool res = true; //LOGGER_WRITE("Insert " + to_string(in.getTime()) + " into history.",Util::LC_SOLVER, Util::LL_DEBUG); if (in.getTime() >= _entries[_lastInsertedElem].getTime()) { if (++_lastInsertedElem == _entries.size()) _lastInsertedElem = 0; _entries[_lastInsertedElem] = in; ++_numAddedElems; } else { throw runtime_error("RingBufferSubHistory: Can't insert values older than the newest in the history"); res = false; } return res; } size_type RingBufferSubHistory::deleteOlderThan(const HistoryEntry & in) { // ring buffer, it deletes it naturally return 1u; } tuple<size_type, size_type> RingBufferSubHistory::checkValidEntries() const { if (_numAddedElems > 1) { std::cout << "_numAddedElems = " << _numAddedElems << std::endl; return std::make_tuple(((_curIndex == 0) ? _entries.size() - 1 : _curIndex - 1), _curIndex); } else { std::cout << "---------------------------------------------------------\n"; throw runtime_error("RingBufferSubHistory: Not enough data for interpolation."); } } } /* namespace Synchronization */ <|endoftext|>
<commit_before>/* Copyright 2022 The TensorFlow 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 "tensorflow/lite/kernels/internal/reference/add.h" #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/kernels/internal/quantization_util.h" #include "tensorflow/lite/kernels/internal/reference/integer_ops/add.h" #include "tensorflow/lite/kernels/internal/reference/process_broadcast_shapes.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" #include "tensorflow/lite/kernels/op_macros.h" #include "tensorflow/lite/micro/kernels/add.h" #include "tensorflow/lite/micro/kernels/kernel_util.h" #include "tensorflow/lite/micro/kernels/xtensa/xtensa.h" #include "tensorflow/lite/micro/kernels/xtensa/xtensa_add.h" #include "tensorflow/lite/micro/memory_helpers.h" #include "tensorflow/lite/micro/micro_error_reporter.h" namespace tflite { TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_OK(context, AddPrepare(context, node)); #if defined(VISION_P6) TF_LITE_ENSURE_OK(context, AddPrepareVision(context, node)); #endif // VISION_P6 return kTfLiteOk; } void EvalAdd(TfLiteContext* context, TfLiteNode* node, TfLiteAddParams* params, const OpDataAdd* data, const TfLiteEvalTensor* input1, const TfLiteEvalTensor* input2, TfLiteEvalTensor* output) { // printf("MCP DEBUG EvalAdd\n"); tflite::ArithmeticParams op_params; SetActivationParams(data->output_activation_min_f32, data->output_activation_max_f32, &op_params); if (data->requires_broadcast) { reference_ops::BroadcastAdd4DSlow( op_params, tflite::micro::GetTensorShape(input1), tflite::micro::GetTensorData<float>(input1), tflite::micro::GetTensorShape(input2), tflite::micro::GetTensorData<float>(input2), tflite::micro::GetTensorShape(output), tflite::micro::GetTensorData<float>(output)); } else { reference_ops::Add(op_params, tflite::micro::GetTensorShape(input1), tflite::micro::GetTensorData<float>(input1), tflite::micro::GetTensorShape(input2), tflite::micro::GetTensorData<float>(input2), tflite::micro::GetTensorShape(output), tflite::micro::GetTensorData<float>(output)); } } TfLiteStatus EvalAddQuantized(TfLiteContext* context, TfLiteNode* node, TfLiteAddParams* params, const OpDataAdd* data, const TfLiteEvalTensor* input1, const TfLiteEvalTensor* input2, TfLiteEvalTensor* output) { tflite::ArithmeticParams op_params; op_params.left_shift = data->left_shift; op_params.input1_offset = data->input1_offset; op_params.input1_multiplier = data->input1_multiplier; op_params.input1_shift = data->input1_shift; op_params.input2_offset = data->input2_offset; op_params.input2_multiplier = data->input2_multiplier; op_params.input2_shift = data->input2_shift; op_params.output_offset = data->output_offset; op_params.output_multiplier = data->output_multiplier; op_params.output_shift = data->output_shift; SetActivationParams(data->output_activation_min, data->output_activation_max, &op_params); bool need_broadcast = reference_ops::ProcessBroadcastShapes( tflite::micro::GetTensorShape(input1), tflite::micro::GetTensorShape(input2), &op_params); switch (output->type) { case kTfLiteInt8: { #if defined(VISION_P6) const auto& op_data = *(reinterpret_cast<XtensaAddOpData*>(node->user_data)); AddEvalQuantizedVision(context, node, *params, op_data, input1, input2, output); #else // if defined(VISION_P6) if (need_broadcast) { reference_integer_ops::BroadcastAdd4DSlow( op_params, tflite::micro::GetTensorShape(input1), tflite::micro::GetTensorData<int8_t>(input1), tflite::micro::GetTensorShape(input2), tflite::micro::GetTensorData<int8_t>(input2), tflite::micro::GetTensorShape(output), tflite::micro::GetTensorData<int8_t>(output)); } else { reference_integer_ops::Add( op_params, tflite::micro::GetTensorShape(input1), tflite::micro::GetTensorData<int8_t>(input1), tflite::micro::GetTensorShape(input2), tflite::micro::GetTensorData<int8_t>(input2), tflite::micro::GetTensorShape(output), tflite::micro::GetTensorData<int8_t>(output)); } #endif // if (defined(VISION_P6) break; } case kTfLiteInt16: { if (need_broadcast) { reference_ops::BroadcastAdd4DSlow( op_params, tflite::micro::GetTensorShape(input1), tflite::micro::GetTensorData<int16_t>(input1), tflite::micro::GetTensorShape(input2), tflite::micro::GetTensorData<int16_t>(input2), tflite::micro::GetTensorShape(output), tflite::micro::GetTensorData<int16_t>(output)); } else { #if defined(HIFI4_INTERNAL) int err; const RuntimeShape& input1_shape = tflite::micro::GetTensorShape(input1); const RuntimeShape& input2_shape = tflite::micro::GetTensorShape(input2); const RuntimeShape& output_shape = tflite::micro::GetTensorShape(output); const int flat_size = MatchingElementsSize(input1_shape, input2_shape, output_shape); err = xa_nn_elm_add_asym16sxasym16s_asym16s( tflite::micro::GetTensorData<int16_t>(output), op_params.output_offset, op_params.output_shift, op_params.output_multiplier, op_params.quantized_activation_min, op_params.quantized_activation_max, tflite::micro::GetTensorData<int16_t>(input1), op_params.input1_offset, op_params.input1_shift, op_params.input1_multiplier, tflite::micro::GetTensorData<int16_t>(input2), op_params.input2_offset, op_params.input2_shift, op_params.input2_multiplier, op_params.left_shift, flat_size); TF_LITE_ENSURE(context, err == 0); #else reference_ops::Add(op_params, tflite::micro::GetTensorShape(input1), tflite::micro::GetTensorData<int16_t>(input1), tflite::micro::GetTensorShape(input2), tflite::micro::GetTensorData<int16_t>(input2), tflite::micro::GetTensorShape(output), tflite::micro::GetTensorData<int16_t>(output), false); #endif } break; } default: MicroPrintf("Type %s (%d) not supported.", TfLiteTypeGetName(output->type), output->type); return kTfLiteError; } return kTfLiteOk; } void* AddInit(TfLiteContext* context, const char* buffer, size_t length) { TFLITE_DCHECK(context->AllocatePersistentBuffer != nullptr); void* data = context->AllocatePersistentBuffer(context, sizeof(OpDataAdd)); #if defined(VISION_P6) if (InitXtensaContext()) { return nullptr; } #endif // defined(VISION_P6) return data; } TfLiteStatus AddEval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteAddParams*>(node->builtin_data); TFLITE_DCHECK(node->user_data != nullptr); const OpDataAdd* data = static_cast<const OpDataAdd*>(node->user_data); const TfLiteEvalTensor* input1 = tflite::micro::GetEvalInput(context, node, kAddInputTensor1); const TfLiteEvalTensor* input2 = tflite::micro::GetEvalInput(context, node, kAddInputTensor2); TfLiteEvalTensor* output = tflite::micro::GetEvalOutput(context, node, kAddOutputTensor); if (output->type == kTfLiteFloat32) { EvalAdd(context, node, params, data, input1, input2, output); } else if (output->type == kTfLiteInt8 || output->type == kTfLiteInt16) { TF_LITE_ENSURE_OK(context, EvalAddQuantized(context, node, params, data, input1, input2, output)); } else { MicroPrintf("Type %s (%d) not supported.", TfLiteTypeGetName(output->type), output->type); return kTfLiteError; } return kTfLiteOk; } TfLiteRegistration Register_ADD() { return tflite::micro::RegisterOp(AddInit, Prepare, AddEval); } } // namespace tflite <commit_msg>Add Memory fix (#1233)<commit_after>/* Copyright 2022 The TensorFlow 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 "tensorflow/lite/kernels/internal/reference/add.h" #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/kernels/internal/quantization_util.h" #include "tensorflow/lite/kernels/internal/reference/integer_ops/add.h" #include "tensorflow/lite/kernels/internal/reference/process_broadcast_shapes.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" #include "tensorflow/lite/kernels/op_macros.h" #include "tensorflow/lite/micro/kernels/add.h" #include "tensorflow/lite/micro/kernels/kernel_util.h" #include "tensorflow/lite/micro/kernels/xtensa/xtensa.h" #include "tensorflow/lite/micro/kernels/xtensa/xtensa_add.h" #include "tensorflow/lite/micro/memory_helpers.h" #include "tensorflow/lite/micro/micro_error_reporter.h" namespace tflite { TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_OK(context, AddPrepare(context, node)); #if defined(VISION_P6) TF_LITE_ENSURE_OK(context, AddPrepareVision(context, node)); #endif // VISION_P6 return kTfLiteOk; } void EvalAdd(TfLiteContext* context, TfLiteNode* node, TfLiteAddParams* params, const OpDataAdd* data, const TfLiteEvalTensor* input1, const TfLiteEvalTensor* input2, TfLiteEvalTensor* output) { // printf("MCP DEBUG EvalAdd\n"); tflite::ArithmeticParams op_params; SetActivationParams(data->output_activation_min_f32, data->output_activation_max_f32, &op_params); if (data->requires_broadcast) { reference_ops::BroadcastAdd4DSlow( op_params, tflite::micro::GetTensorShape(input1), tflite::micro::GetTensorData<float>(input1), tflite::micro::GetTensorShape(input2), tflite::micro::GetTensorData<float>(input2), tflite::micro::GetTensorShape(output), tflite::micro::GetTensorData<float>(output)); } else { reference_ops::Add(op_params, tflite::micro::GetTensorShape(input1), tflite::micro::GetTensorData<float>(input1), tflite::micro::GetTensorShape(input2), tflite::micro::GetTensorData<float>(input2), tflite::micro::GetTensorShape(output), tflite::micro::GetTensorData<float>(output)); } } TfLiteStatus EvalAddQuantized(TfLiteContext* context, TfLiteNode* node, TfLiteAddParams* params, const OpDataAdd* data, const TfLiteEvalTensor* input1, const TfLiteEvalTensor* input2, TfLiteEvalTensor* output) { tflite::ArithmeticParams op_params; op_params.left_shift = data->left_shift; op_params.input1_offset = data->input1_offset; op_params.input1_multiplier = data->input1_multiplier; op_params.input1_shift = data->input1_shift; op_params.input2_offset = data->input2_offset; op_params.input2_multiplier = data->input2_multiplier; op_params.input2_shift = data->input2_shift; op_params.output_offset = data->output_offset; op_params.output_multiplier = data->output_multiplier; op_params.output_shift = data->output_shift; SetActivationParams(data->output_activation_min, data->output_activation_max, &op_params); bool need_broadcast = reference_ops::ProcessBroadcastShapes( tflite::micro::GetTensorShape(input1), tflite::micro::GetTensorShape(input2), &op_params); switch (output->type) { case kTfLiteInt8: { #if defined(VISION_P6) const auto& op_data = *(reinterpret_cast<XtensaAddOpData*>(node->user_data)); AddEvalQuantizedVision(context, node, *params, op_data, input1, input2, output); #else // if defined(VISION_P6) if (need_broadcast) { reference_integer_ops::BroadcastAdd4DSlow( op_params, tflite::micro::GetTensorShape(input1), tflite::micro::GetTensorData<int8_t>(input1), tflite::micro::GetTensorShape(input2), tflite::micro::GetTensorData<int8_t>(input2), tflite::micro::GetTensorShape(output), tflite::micro::GetTensorData<int8_t>(output)); } else { reference_integer_ops::Add( op_params, tflite::micro::GetTensorShape(input1), tflite::micro::GetTensorData<int8_t>(input1), tflite::micro::GetTensorShape(input2), tflite::micro::GetTensorData<int8_t>(input2), tflite::micro::GetTensorShape(output), tflite::micro::GetTensorData<int8_t>(output)); } #endif // if (defined(VISION_P6) break; } case kTfLiteInt16: { if (need_broadcast) { reference_ops::BroadcastAdd4DSlow( op_params, tflite::micro::GetTensorShape(input1), tflite::micro::GetTensorData<int16_t>(input1), tflite::micro::GetTensorShape(input2), tflite::micro::GetTensorData<int16_t>(input2), tflite::micro::GetTensorShape(output), tflite::micro::GetTensorData<int16_t>(output)); } else { #if defined(HIFI4_INTERNAL) int err; const RuntimeShape& input1_shape = tflite::micro::GetTensorShape(input1); const RuntimeShape& input2_shape = tflite::micro::GetTensorShape(input2); const RuntimeShape& output_shape = tflite::micro::GetTensorShape(output); const int flat_size = MatchingElementsSize(input1_shape, input2_shape, output_shape); err = xa_nn_elm_add_asym16sxasym16s_asym16s( tflite::micro::GetTensorData<int16_t>(output), op_params.output_offset, op_params.output_shift, op_params.output_multiplier, op_params.quantized_activation_min, op_params.quantized_activation_max, tflite::micro::GetTensorData<int16_t>(input1), op_params.input1_offset, op_params.input1_shift, op_params.input1_multiplier, tflite::micro::GetTensorData<int16_t>(input2), op_params.input2_offset, op_params.input2_shift, op_params.input2_multiplier, op_params.left_shift, flat_size); TF_LITE_ENSURE(context, err == 0); #else reference_ops::Add(op_params, tflite::micro::GetTensorShape(input1), tflite::micro::GetTensorData<int16_t>(input1), tflite::micro::GetTensorShape(input2), tflite::micro::GetTensorData<int16_t>(input2), tflite::micro::GetTensorShape(output), tflite::micro::GetTensorData<int16_t>(output), false); #endif } break; } default: MicroPrintf("Type %s (%d) not supported.", TfLiteTypeGetName(output->type), output->type); return kTfLiteError; } return kTfLiteOk; } void* AddInit(TfLiteContext* context, const char* buffer, size_t length) { TFLITE_DCHECK(context->AllocatePersistentBuffer != nullptr); void* data; #if defined(VISION_P6) data = context->AllocatePersistentBuffer(context, sizeof(XtensaAddOpData)); if (InitXtensaContext()) { return nullptr; } #else data = context->AllocatePersistentBuffer(context, sizeof(OpDataAdd)); #endif // defined(VISION_P6) return data; } TfLiteStatus AddEval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteAddParams*>(node->builtin_data); TFLITE_DCHECK(node->user_data != nullptr); const OpDataAdd* data = static_cast<const OpDataAdd*>(node->user_data); const TfLiteEvalTensor* input1 = tflite::micro::GetEvalInput(context, node, kAddInputTensor1); const TfLiteEvalTensor* input2 = tflite::micro::GetEvalInput(context, node, kAddInputTensor2); TfLiteEvalTensor* output = tflite::micro::GetEvalOutput(context, node, kAddOutputTensor); if (output->type == kTfLiteFloat32) { EvalAdd(context, node, params, data, input1, input2, output); } else if (output->type == kTfLiteInt8 || output->type == kTfLiteInt16) { TF_LITE_ENSURE_OK(context, EvalAddQuantized(context, node, params, data, input1, input2, output)); } else { MicroPrintf("Type %s (%d) not supported.", TfLiteTypeGetName(output->type), output->type); return kTfLiteError; } return kTfLiteOk; } TfLiteRegistration Register_ADD() { return tflite::micro::RegisterOp(AddInit, Prepare, AddEval); } } // namespace tflite <|endoftext|>
<commit_before>// // Copyright (c) 2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include <cassert> #include <vector> #include "EGLWindow.h" #include "OSWindow.h" #ifdef _WIN32 #include "win32/Win32Timer.h" #include "win32/Win32Window.h" #else #error unsupported OS. #endif EGLPlatformParameters::EGLPlatformParameters() : renderer(EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE), majorVersion(EGL_DONT_CARE), minorVersion(EGL_DONT_CARE), deviceType(EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) { } EGLPlatformParameters::EGLPlatformParameters(EGLint renderer) : renderer(renderer), majorVersion(EGL_DONT_CARE), minorVersion(EGL_DONT_CARE), deviceType(EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) { } EGLPlatformParameters::EGLPlatformParameters(EGLint renderer, EGLint majorVersion, EGLint minorVersion, EGLint useWarp) : renderer(renderer), majorVersion(majorVersion), minorVersion(minorVersion), deviceType(useWarp) { } EGLWindow::EGLWindow(size_t width, size_t height, EGLint glesMajorVersion, const EGLPlatformParameters &platform) : mSurface(EGL_NO_SURFACE), mContext(EGL_NO_CONTEXT), mDisplay(EGL_NO_DISPLAY), mClientVersion(glesMajorVersion), mPlatform(platform), mWidth(width), mHeight(height), mRedBits(-1), mGreenBits(-1), mBlueBits(-1), mAlphaBits(-1), mDepthBits(-1), mStencilBits(-1), mMultisample(false), mSwapInterval(-1) { } EGLWindow::~EGLWindow() { destroyGL(); } void EGLWindow::swap() { eglSwapBuffers(mDisplay, mSurface); } EGLConfig EGLWindow::getConfig() const { return mConfig; } EGLDisplay EGLWindow::getDisplay() const { return mDisplay; } EGLSurface EGLWindow::getSurface() const { return mSurface; } EGLContext EGLWindow::getContext() const { return mContext; } bool EGLWindow::initializeGL(OSWindow *osWindow) { PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(eglGetProcAddress("eglGetPlatformDisplayEXT")); if (!eglGetPlatformDisplayEXT) { return false; } const EGLint displayAttributes[] = { EGL_PLATFORM_ANGLE_TYPE_ANGLE, mPlatform.renderer, EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, mPlatform.majorVersion, EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, mPlatform.minorVersion, EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE, mPlatform.deviceType, EGL_NONE, }; mDisplay = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, osWindow->getNativeDisplay(), displayAttributes); if (mDisplay == EGL_NO_DISPLAY) { destroyGL(); return false; } EGLint majorVersion, minorVersion; if (!eglInitialize(mDisplay, &majorVersion, &minorVersion)) { destroyGL(); return false; } eglBindAPI(EGL_OPENGL_ES_API); if (eglGetError() != EGL_SUCCESS) { destroyGL(); return false; } const EGLint configAttributes[] = { EGL_RED_SIZE, (mRedBits >= 0) ? mRedBits : EGL_DONT_CARE, EGL_GREEN_SIZE, (mGreenBits >= 0) ? mGreenBits : EGL_DONT_CARE, EGL_BLUE_SIZE, (mBlueBits >= 0) ? mBlueBits : EGL_DONT_CARE, EGL_ALPHA_SIZE, (mAlphaBits >= 0) ? mAlphaBits : EGL_DONT_CARE, EGL_DEPTH_SIZE, (mDepthBits >= 0) ? mDepthBits : EGL_DONT_CARE, EGL_STENCIL_SIZE, (mStencilBits >= 0) ? mStencilBits : EGL_DONT_CARE, EGL_SAMPLE_BUFFERS, mMultisample ? 1 : 0, EGL_NONE }; EGLint configCount; if (!eglChooseConfig(mDisplay, configAttributes, &mConfig, 1, &configCount) || (configCount != 1)) { destroyGL(); return false; } eglGetConfigAttrib(mDisplay, mConfig, EGL_RED_SIZE, &mRedBits); eglGetConfigAttrib(mDisplay, mConfig, EGL_GREEN_SIZE, &mGreenBits); eglGetConfigAttrib(mDisplay, mConfig, EGL_BLUE_SIZE, &mBlueBits); eglGetConfigAttrib(mDisplay, mConfig, EGL_ALPHA_SIZE, &mBlueBits); eglGetConfigAttrib(mDisplay, mConfig, EGL_DEPTH_SIZE, &mDepthBits); eglGetConfigAttrib(mDisplay, mConfig, EGL_STENCIL_SIZE, &mStencilBits); std::vector<EGLint> surfaceAttributes; if (strstr(eglQueryString(mDisplay, EGL_EXTENSIONS), "EGL_NV_post_sub_buffer") != nullptr) { surfaceAttributes.push_back(EGL_POST_SUB_BUFFER_SUPPORTED_NV); surfaceAttributes.push_back(EGL_TRUE); } surfaceAttributes.push_back(EGL_NONE); surfaceAttributes.push_back(EGL_NONE); mSurface = eglCreateWindowSurface(mDisplay, mConfig, osWindow->getNativeWindow(), &surfaceAttributes[0]); if (mSurface == EGL_NO_SURFACE) { eglGetError(); // Clear error and try again mSurface = eglCreateWindowSurface(mDisplay, mConfig, NULL, NULL); } if (eglGetError() != EGL_SUCCESS) { destroyGL(); return false; } EGLint contextAttibutes[] = { EGL_CONTEXT_CLIENT_VERSION, mClientVersion, EGL_NONE }; mContext = eglCreateContext(mDisplay, mConfig, NULL, contextAttibutes); if (eglGetError() != EGL_SUCCESS) { destroyGL(); return false; } eglMakeCurrent(mDisplay, mSurface, mSurface, mContext); if (eglGetError() != EGL_SUCCESS) { destroyGL(); return false; } if (mSwapInterval != -1) { eglSwapInterval(mDisplay, mSwapInterval); } return true; } void EGLWindow::destroyGL() { if (mSurface != EGL_NO_SURFACE) { assert(mDisplay != EGL_NO_DISPLAY); eglDestroySurface(mDisplay, mSurface); mSurface = EGL_NO_SURFACE; } if (mContext != EGL_NO_CONTEXT) { assert(mDisplay != EGL_NO_DISPLAY); eglDestroyContext(mDisplay, mContext); mContext = EGL_NO_CONTEXT; } if (mDisplay != EGL_NO_DISPLAY) { eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglTerminate(mDisplay); mDisplay = EGL_NO_DISPLAY; } } bool EGLWindow::isGLInitialized() const { return mSurface != EGL_NO_SURFACE && mContext != EGL_NO_CONTEXT && mDisplay != EGL_NO_DISPLAY; }<commit_msg>Fix pointer to int conversion warning in EGLWindow.cpp<commit_after>// // Copyright (c) 2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include <cassert> #include <vector> #include "EGLWindow.h" #include "OSWindow.h" #ifdef _WIN32 #include "win32/Win32Timer.h" #include "win32/Win32Window.h" #else #error unsupported OS. #endif EGLPlatformParameters::EGLPlatformParameters() : renderer(EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE), majorVersion(EGL_DONT_CARE), minorVersion(EGL_DONT_CARE), deviceType(EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) { } EGLPlatformParameters::EGLPlatformParameters(EGLint renderer) : renderer(renderer), majorVersion(EGL_DONT_CARE), minorVersion(EGL_DONT_CARE), deviceType(EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) { } EGLPlatformParameters::EGLPlatformParameters(EGLint renderer, EGLint majorVersion, EGLint minorVersion, EGLint useWarp) : renderer(renderer), majorVersion(majorVersion), minorVersion(minorVersion), deviceType(useWarp) { } EGLWindow::EGLWindow(size_t width, size_t height, EGLint glesMajorVersion, const EGLPlatformParameters &platform) : mSurface(EGL_NO_SURFACE), mContext(EGL_NO_CONTEXT), mDisplay(EGL_NO_DISPLAY), mClientVersion(glesMajorVersion), mPlatform(platform), mWidth(width), mHeight(height), mRedBits(-1), mGreenBits(-1), mBlueBits(-1), mAlphaBits(-1), mDepthBits(-1), mStencilBits(-1), mMultisample(false), mSwapInterval(-1) { } EGLWindow::~EGLWindow() { destroyGL(); } void EGLWindow::swap() { eglSwapBuffers(mDisplay, mSurface); } EGLConfig EGLWindow::getConfig() const { return mConfig; } EGLDisplay EGLWindow::getDisplay() const { return mDisplay; } EGLSurface EGLWindow::getSurface() const { return mSurface; } EGLContext EGLWindow::getContext() const { return mContext; } bool EGLWindow::initializeGL(OSWindow *osWindow) { PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(eglGetProcAddress("eglGetPlatformDisplayEXT")); if (!eglGetPlatformDisplayEXT) { return false; } const EGLint displayAttributes[] = { EGL_PLATFORM_ANGLE_TYPE_ANGLE, mPlatform.renderer, EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, mPlatform.majorVersion, EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, mPlatform.minorVersion, EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE, mPlatform.deviceType, EGL_NONE, }; mDisplay = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, osWindow->getNativeDisplay(), displayAttributes); if (mDisplay == EGL_NO_DISPLAY) { destroyGL(); return false; } EGLint majorVersion, minorVersion; if (!eglInitialize(mDisplay, &majorVersion, &minorVersion)) { destroyGL(); return false; } eglBindAPI(EGL_OPENGL_ES_API); if (eglGetError() != EGL_SUCCESS) { destroyGL(); return false; } const EGLint configAttributes[] = { EGL_RED_SIZE, (mRedBits >= 0) ? mRedBits : EGL_DONT_CARE, EGL_GREEN_SIZE, (mGreenBits >= 0) ? mGreenBits : EGL_DONT_CARE, EGL_BLUE_SIZE, (mBlueBits >= 0) ? mBlueBits : EGL_DONT_CARE, EGL_ALPHA_SIZE, (mAlphaBits >= 0) ? mAlphaBits : EGL_DONT_CARE, EGL_DEPTH_SIZE, (mDepthBits >= 0) ? mDepthBits : EGL_DONT_CARE, EGL_STENCIL_SIZE, (mStencilBits >= 0) ? mStencilBits : EGL_DONT_CARE, EGL_SAMPLE_BUFFERS, mMultisample ? 1 : 0, EGL_NONE }; EGLint configCount; if (!eglChooseConfig(mDisplay, configAttributes, &mConfig, 1, &configCount) || (configCount != 1)) { destroyGL(); return false; } eglGetConfigAttrib(mDisplay, mConfig, EGL_RED_SIZE, &mRedBits); eglGetConfigAttrib(mDisplay, mConfig, EGL_GREEN_SIZE, &mGreenBits); eglGetConfigAttrib(mDisplay, mConfig, EGL_BLUE_SIZE, &mBlueBits); eglGetConfigAttrib(mDisplay, mConfig, EGL_ALPHA_SIZE, &mBlueBits); eglGetConfigAttrib(mDisplay, mConfig, EGL_DEPTH_SIZE, &mDepthBits); eglGetConfigAttrib(mDisplay, mConfig, EGL_STENCIL_SIZE, &mStencilBits); std::vector<EGLint> surfaceAttributes; if (strstr(eglQueryString(mDisplay, EGL_EXTENSIONS), "EGL_NV_post_sub_buffer") != nullptr) { surfaceAttributes.push_back(EGL_POST_SUB_BUFFER_SUPPORTED_NV); surfaceAttributes.push_back(EGL_TRUE); } surfaceAttributes.push_back(EGL_NONE); surfaceAttributes.push_back(EGL_NONE); mSurface = eglCreateWindowSurface(mDisplay, mConfig, osWindow->getNativeWindow(), &surfaceAttributes[0]); if (eglGetError() != EGL_SUCCESS) { destroyGL(); return false; } ASSERT(mSurface != EGL_NO_SURFACE); EGLint contextAttibutes[] = { EGL_CONTEXT_CLIENT_VERSION, mClientVersion, EGL_NONE }; mContext = eglCreateContext(mDisplay, mConfig, NULL, contextAttibutes); if (eglGetError() != EGL_SUCCESS) { destroyGL(); return false; } eglMakeCurrent(mDisplay, mSurface, mSurface, mContext); if (eglGetError() != EGL_SUCCESS) { destroyGL(); return false; } if (mSwapInterval != -1) { eglSwapInterval(mDisplay, mSwapInterval); } return true; } void EGLWindow::destroyGL() { if (mSurface != EGL_NO_SURFACE) { assert(mDisplay != EGL_NO_DISPLAY); eglDestroySurface(mDisplay, mSurface); mSurface = EGL_NO_SURFACE; } if (mContext != EGL_NO_CONTEXT) { assert(mDisplay != EGL_NO_DISPLAY); eglDestroyContext(mDisplay, mContext); mContext = EGL_NO_CONTEXT; } if (mDisplay != EGL_NO_DISPLAY) { eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglTerminate(mDisplay); mDisplay = EGL_NO_DISPLAY; } } bool EGLWindow::isGLInitialized() const { return mSurface != EGL_NO_SURFACE && mContext != EGL_NO_CONTEXT && mDisplay != EGL_NO_DISPLAY; }<|endoftext|>
<commit_before>// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s class C {}; // expected-no-diagnostics void f(C i) { auto lambda = [&] { f(i); }; typedef decltype(lambda) T; T* blah = new T(lambda); (*blah)(); delete blah; } <commit_msg>Propagating prior merge from 'llvm.org/master'.<commit_after>// RUN: %clang_analyze_cc1 -analyzer-checker=core -std=c++11 -verify %s class C {}; // expected-no-diagnostics void f(C i) { auto lambda = [&] { f(i); }; typedef decltype(lambda) T; T* blah = new T(lambda); (*blah)(); delete blah; } <|endoftext|>
<commit_before>#include <iostream> #include <stdexcept> #include <string> #include <boost/unordered_set.hpp> #include <boost/scoped_ptr.hpp> #include <boost/shared_ptr.hpp> extern "C" { #include <libxslt/xslt.h> #include <libxml/parser.h> #include <libxml/xpath.h> #include <libexslt/exslt.h> } #include <AlpinoCorpus/CorpusReader.hh> #include <AlpinoCorpus/Entry.hh> #include <AlpinoCorpus/Error.hh> #include <AlpinoCorpus/macros.hh> #include "../src/util/textfile.hh" // XXX - hmpf #include <EqualsPrevious.hh> #include <ProgramOptions.hh> #include <Stylesheet.hh> #include <util.hh> using alpinocorpus::CorpusReader; using alpinocorpus::Either; void transformCorpus(boost::shared_ptr<CorpusReader> reader, std::string const &query, std::string const &stylesheet) { std::list<CorpusReader::MarkerQuery> markerQueries; if (!query.empty()) { // Markers CorpusReader::MarkerQuery activeMarker(query, "active", "1"); markerQueries.push_back(activeMarker); } CorpusReader::EntryIterator i; if (!query.empty()) i = reader->queryWithStylesheet(CorpusReader::XPATH, query, stylesheet, markerQueries); else i = reader->entriesWithStylesheet(stylesheet); boost::unordered_set<std::string> seen; while (i.hasNext()) { alpinocorpus::Entry e = i.next(*reader); if (seen.find(e.name) == seen.end()) { seen.insert(e.name); std::cout << e.contents; } } } void transformEntry(boost::shared_ptr<CorpusReader> reader, std::string const &query, std::string const &stylesheet, std::string const &entry) { Stylesheet compiledStylesheet(stylesheet); std::list<CorpusReader::MarkerQuery> markerQueries; if (!query.empty()) { // Markers CorpusReader::MarkerQuery activeMarker(query, "active", "1"); markerQueries.push_back(activeMarker); } std::cout << compiledStylesheet.transform(reader->read(entry, markerQueries)); } void usage(std::string const &programName) { std::cerr << "Usage: " << programName << " [OPTION] stylesheet treebanks" << std::endl << std::endl << " -g entry\tApply the stylesheet to a single entry" << std::endl << " -m filename\tLoad macro file" << std::endl << " -q query\tFilter the treebank using the given query" << std::endl << std::endl; } int main (int argc, char *argv[]) { xmlInitMemory(); xmlInitParser(); // EXSLT extensions exsltRegisterAll(); // XPath xmlXPathInit(); boost::scoped_ptr<ProgramOptions> opts; try { opts.reset(new ProgramOptions(argc, const_cast<char const **>(argv), "g:m:q:")); } catch (std::exception &e) { std::cerr << e.what() << std::endl; return 1; } if (opts->arguments().size() < 2) { usage(opts->programName()); return 1; } std::string stylesheet; try { stylesheet = alpinocorpus::util::readFile(opts->arguments().at(0)); } catch (std::runtime_error &e) { std::cerr << "Could not read stylesheet: " << e.what() << std::endl; return 1; } boost::shared_ptr<CorpusReader> reader; try { if (opts->arguments().size() == 2) reader = boost::shared_ptr<CorpusReader>( openCorpus(opts->arguments().at(1), true)); else reader = boost::shared_ptr<CorpusReader>( openCorpora(opts->arguments().begin() + 1, opts->arguments().end(), true)); } catch (std::runtime_error &e) { std::cerr << "Could not open corpus: " << e.what() << std::endl; return 1; } alpinocorpus::Macros macros; if (opts->option('m')) { std::string macrosFn = opts->optionValue('m'); try { macros = alpinocorpus::loadMacros(macrosFn); } catch (std::runtime_error &e) { std::cerr << e.what() << std::endl; return 1; } } std::string query; if (opts->option('q')) { query = alpinocorpus::expandMacros(macros, opts->optionValue('q')); Either<std::string, alpinocorpus::Empty> valid = reader->isValidQuery(CorpusReader::XPATH, false, query); if (valid.isLeft()) { std::cerr << "Invalid (or unwanted) query: " << query << std::endl << std::endl; std::cerr << valid.left() << std::endl; return 1; } } try { if (opts->option('g')) transformEntry(reader, query, stylesheet, opts->optionValue('g')); else transformCorpus(reader, query, stylesheet); } catch (std::runtime_error &e) { std::cerr << "Error while transforming corpus: " << e.what() << std::endl; } } <commit_msg>Fix result code on transformation error<commit_after>#include <iostream> #include <stdexcept> #include <string> #include <boost/unordered_set.hpp> #include <boost/scoped_ptr.hpp> #include <boost/shared_ptr.hpp> extern "C" { #include <libxslt/xslt.h> #include <libxml/parser.h> #include <libxml/xpath.h> #include <libexslt/exslt.h> } #include <AlpinoCorpus/CorpusReader.hh> #include <AlpinoCorpus/Entry.hh> #include <AlpinoCorpus/Error.hh> #include <AlpinoCorpus/macros.hh> #include "../src/util/textfile.hh" // XXX - hmpf #include <EqualsPrevious.hh> #include <ProgramOptions.hh> #include <Stylesheet.hh> #include <util.hh> using alpinocorpus::CorpusReader; using alpinocorpus::Either; void transformCorpus(boost::shared_ptr<CorpusReader> reader, std::string const &query, std::string const &stylesheet) { std::list<CorpusReader::MarkerQuery> markerQueries; if (!query.empty()) { // Markers CorpusReader::MarkerQuery activeMarker(query, "active", "1"); markerQueries.push_back(activeMarker); } CorpusReader::EntryIterator i; if (!query.empty()) i = reader->queryWithStylesheet(CorpusReader::XPATH, query, stylesheet, markerQueries); else i = reader->entriesWithStylesheet(stylesheet); boost::unordered_set<std::string> seen; while (i.hasNext()) { alpinocorpus::Entry e = i.next(*reader); if (seen.find(e.name) == seen.end()) { seen.insert(e.name); std::cout << e.contents; } } } void transformEntry(boost::shared_ptr<CorpusReader> reader, std::string const &query, std::string const &stylesheet, std::string const &entry) { Stylesheet compiledStylesheet(stylesheet); std::list<CorpusReader::MarkerQuery> markerQueries; if (!query.empty()) { // Markers CorpusReader::MarkerQuery activeMarker(query, "active", "1"); markerQueries.push_back(activeMarker); } std::cout << compiledStylesheet.transform(reader->read(entry, markerQueries)); } void usage(std::string const &programName) { std::cerr << "Usage: " << programName << " [OPTION] stylesheet treebanks" << std::endl << std::endl << " -g entry\tApply the stylesheet to a single entry" << std::endl << " -m filename\tLoad macro file" << std::endl << " -q query\tFilter the treebank using the given query" << std::endl << std::endl; } int main (int argc, char *argv[]) { xmlInitMemory(); xmlInitParser(); // EXSLT extensions exsltRegisterAll(); // XPath xmlXPathInit(); boost::scoped_ptr<ProgramOptions> opts; try { opts.reset(new ProgramOptions(argc, const_cast<char const **>(argv), "g:m:q:")); } catch (std::exception &e) { std::cerr << e.what() << std::endl; return 1; } if (opts->arguments().size() < 2) { usage(opts->programName()); return 1; } std::string stylesheet; try { stylesheet = alpinocorpus::util::readFile(opts->arguments().at(0)); } catch (std::runtime_error &e) { std::cerr << "Could not read stylesheet: " << e.what() << std::endl; return 1; } boost::shared_ptr<CorpusReader> reader; try { if (opts->arguments().size() == 2) reader = boost::shared_ptr<CorpusReader>( openCorpus(opts->arguments().at(1), true)); else reader = boost::shared_ptr<CorpusReader>( openCorpora(opts->arguments().begin() + 1, opts->arguments().end(), true)); } catch (std::runtime_error &e) { std::cerr << "Could not open corpus: " << e.what() << std::endl; return 1; } alpinocorpus::Macros macros; if (opts->option('m')) { std::string macrosFn = opts->optionValue('m'); try { macros = alpinocorpus::loadMacros(macrosFn); } catch (std::runtime_error &e) { std::cerr << e.what() << std::endl; return 1; } } std::string query; if (opts->option('q')) { query = alpinocorpus::expandMacros(macros, opts->optionValue('q')); Either<std::string, alpinocorpus::Empty> valid = reader->isValidQuery(CorpusReader::XPATH, false, query); if (valid.isLeft()) { std::cerr << "Invalid (or unwanted) query: " << query << std::endl << std::endl; std::cerr << valid.left() << std::endl; return 1; } } try { if (opts->option('g')) transformEntry(reader, query, stylesheet, opts->optionValue('g')); else transformCorpus(reader, query, stylesheet); } catch (std::runtime_error &e) { std::cerr << "Error while transforming corpus: " << e.what() << std::endl; return 1; } } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "serialconfig.h" #include "qlineeditlabel.h" #include <QtDebug> #include <QMessageBox> #include <QPushButton> #include <QLayout> #include <QStandardPaths> #define SETTING_BTNLBL "buttonLabel/" #define SETTING_WINDOW "window/" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), mSd(parent), mSettings("iconux.org","qShowDesigner") { ui->setupUi(this); //QString configpath = QStandardPaths::standardLocations(QStandardPaths::ConfigLocation).first(); //mSettings = new QSettings(configpath + "/qShowDesigner.ini", QSettings::IniFormat); //qDebug() << "Loaded config file " << configpath + "/qShowDesigner.ini"; mStatusLabel = new QLabel(this); ui->statusBar->addWidget(mStatusLabel, 1); ui->statusBar->setSizeGripEnabled(false); mStatusLabel->setText("Not Connected"); ui->gridLayout->setColumnStretch(1,1); // set each button text to numbers 1 through 12 // load each button label text from settings or initialize to Scene # for(int row = 0; row < 12; row++) { QString btnStr = QString::number(row+1); QString lblText = "Scene " + btnStr; QPushButton *sceneBtn = new QPushButton(btnStr, this); sceneBtn->setMaximumWidth(50); ui->gridLayout->addWidget(sceneBtn, row, 0); // connect each button to the same slot which selects the scene connect( sceneBtn, SIGNAL(released()), this, SLOT(on_btn_num_released())); QLineEditLabel *lel = new QLineEditLabel(this); lel->showAsLabel(); lel->setText( mSettings.value(SETTING_BTNLBL + btnStr, lblText).toString()); ui->gridLayout->addWidget(lel, row, 1); connect( lel, SIGNAL(editingFinished()), this, SLOT(on_editing_finished())); } // load always on top setting ui->actionAlways_on_top->setChecked(mSettings.value(SETTING_WINDOW "alwaysontop", false).toBool()); /*for(int row = 0; row < ui->gridLayout->rowCount(); row++) { QLayoutItem *item = ui->gridLayout->itemAtPosition(row, 1); QLineEditLabel *label = qobject_cast<QLineEditLabel*> (item->widget()); if ( !label ) { continue; } QString lblText = "Scene " + QString::number(row+1); label->setText( lblText ); }*/ connect( &mSd, SIGNAL(pageChanged(quint16)), this, SLOT(on_page_changed(quint16))); } MainWindow::~MainWindow() { delete ui; } void MainWindow::contextMenuEvent(QContextMenuEvent *event) { } void MainWindow::on_action_Connect_triggered() { SerialConfig sc(this); sc.exec(); if (sc.result() == QDialog::Accepted) { mStatusLabel->setText("Connecting..."); if (!mSd.ConnectToShowDesigner(sc.GetPort())) { mStatusLabel->setText("Not Connected"); ui->statusBar->showMessage("Connection Failed"); ShowErrorMessage("Failed to Connect to Show Designer", mSd.GetErrorString()); } else { mStatusLabel->setText("Connected"); } } } void MainWindow::on_actionExit_triggered() { close(); } void MainWindow::on_btn_num_released() { QPushButton *clickedButton = qobject_cast<QPushButton*>(sender()); QString buttonNumber = clickedButton->text(); int btnNum = buttonNumber.toInt(); qDebug() << "Button " << btnNum << " was released"; if (!mSd.PushButton(btnNum)) { ui->statusBar->showMessage("Failed to set scene"); } for (int row = 0; row < ui->gridLayout->rowCount(); row++) { QLayoutItem *item = ui->gridLayout->itemAtPosition(row, 0); QPushButton *btn = qobject_cast<QPushButton*> (item->widget()); btn->setStyleSheet(""); } clickedButton->setStyleSheet("background-color:red"); } void MainWindow::on_actionAlways_on_top_triggered() { Qt::WindowFlags flags = windowFlags(); if (ui->actionAlways_on_top->isChecked()) { flags |= Qt::WindowStaysOnTopHint; // for Linux/X11, need to also set flag to bypass window manager //flags |= Qt::X11BypassWindowManagerHint; } else { flags &= ~Qt::WindowStaysOnTopHint; //flags &= ~Qt::X11BypassWindowManagerHint; } mSettings.setValue(SETTING_WINDOW "alwaysontop", ui->actionAlways_on_top->isChecked()); show(); } void MainWindow::on_editing_finished() { Save(); } void MainWindow::on_page_changed(quint16 pageNo) { ui->lePage->setText(QString::number((uint)pageNo)); } void MainWindow::ShowErrorMessage(const QString &text, const QString &informativeText) { QMessageBox msgBox; msgBox.setText(text); msgBox.setInformativeText(informativeText); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); int ret = msgBox.exec(); } void MainWindow::Save() { qDebug() << "Saving settings"; for (int row = 0; row < ui->gridLayout->rowCount(); row++) { QString rowStr = QString::number(row+1); QLayoutItem *item = ui->gridLayout->itemAtPosition(row, 1); QLineEditLabel *label = qobject_cast<QLineEditLabel*> (item->widget()); mSettings.setValue(SETTING_BTNLBL + rowStr, label->text()); } mSettings.sync(); qDebug() << mSettings.status(); } void MainWindow::on_btnDown_clicked() { mSd.RequestPageDown(); } void MainWindow::on_btnUp_clicked() { mSd.RequestPageUp(); } <commit_msg>Fixed window flags not set when selecting always on top<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "serialconfig.h" #include "qlineeditlabel.h" #include <QtDebug> #include <QMessageBox> #include <QPushButton> #include <QLayout> #include <QStandardPaths> #define SETTING_BTNLBL "buttonLabel/" #define SETTING_WINDOW "window/" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), mSd(parent), mSettings("iconux.org","qShowDesigner") { ui->setupUi(this); //QString configpath = QStandardPaths::standardLocations(QStandardPaths::ConfigLocation).first(); //mSettings = new QSettings(configpath + "/qShowDesigner.ini", QSettings::IniFormat); //qDebug() << "Loaded config file " << configpath + "/qShowDesigner.ini"; mStatusLabel = new QLabel(this); ui->statusBar->addWidget(mStatusLabel, 1); ui->statusBar->setSizeGripEnabled(false); mStatusLabel->setText("Not Connected"); ui->gridLayout->setColumnStretch(1,1); // set each button text to numbers 1 through 12 // load each button label text from settings or initialize to Scene # for(int row = 0; row < 12; row++) { QString btnStr = QString::number(row+1); QString lblText = "Scene " + btnStr; QPushButton *sceneBtn = new QPushButton(btnStr, this); sceneBtn->setMaximumWidth(50); ui->gridLayout->addWidget(sceneBtn, row, 0); // connect each button to the same slot which selects the scene connect( sceneBtn, SIGNAL(released()), this, SLOT(on_btn_num_released())); QLineEditLabel *lel = new QLineEditLabel(this); lel->showAsLabel(); lel->setText( mSettings.value(SETTING_BTNLBL + btnStr, lblText).toString()); ui->gridLayout->addWidget(lel, row, 1); connect( lel, SIGNAL(editingFinished()), this, SLOT(on_editing_finished())); } // load always on top setting ui->actionAlways_on_top->setChecked(mSettings.value(SETTING_WINDOW "alwaysontop", false).toBool()); connect( &mSd, SIGNAL(pageChanged(quint16)), this, SLOT(on_page_changed(quint16))); } MainWindow::~MainWindow() { delete ui; } void MainWindow::contextMenuEvent(QContextMenuEvent *event) { } void MainWindow::on_action_Connect_triggered() { SerialConfig sc(this); sc.exec(); if (sc.result() == QDialog::Accepted) { mStatusLabel->setText("Connecting..."); if (!mSd.ConnectToShowDesigner(sc.GetPort())) { mStatusLabel->setText("Not Connected"); ui->statusBar->showMessage("Connection Failed"); ShowErrorMessage("Failed to Connect to Show Designer", mSd.GetErrorString()); } else { mStatusLabel->setText("Connected"); } } } void MainWindow::on_actionExit_triggered() { close(); } void MainWindow::on_btn_num_released() { QPushButton *clickedButton = qobject_cast<QPushButton*>(sender()); QString buttonNumber = clickedButton->text(); int btnNum = buttonNumber.toInt(); qDebug() << "Button " << btnNum << " was released"; if (!mSd.PushButton(btnNum)) { ui->statusBar->showMessage("Failed to set scene"); } for (int row = 0; row < ui->gridLayout->rowCount(); row++) { QLayoutItem *item = ui->gridLayout->itemAtPosition(row, 0); QPushButton *btn = qobject_cast<QPushButton*> (item->widget()); btn->setStyleSheet(""); } clickedButton->setStyleSheet("background-color:red"); } void MainWindow::on_actionAlways_on_top_triggered() { Qt::WindowFlags flags = windowFlags(); if (ui->actionAlways_on_top->isChecked()) { flags |= Qt::WindowStaysOnTopHint; // for Linux/X11, need to also set flag to bypass window manager // flags |= Qt::X11BypassWindowManagerHint; } else { flags &= ~Qt::WindowStaysOnTopHint; // flags &= ~Qt::X11BypassWindowManagerHint; } setWindowFlags( flags ); mSettings.setValue(SETTING_WINDOW "alwaysontop", ui->actionAlways_on_top->isChecked()); show(); } void MainWindow::on_editing_finished() { Save(); } void MainWindow::on_page_changed(quint16 pageNo) { ui->lePage->setText(QString::number((uint)pageNo)); } void MainWindow::ShowErrorMessage(const QString &text, const QString &informativeText) { QMessageBox msgBox; msgBox.setText(text); msgBox.setInformativeText(informativeText); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); int ret = msgBox.exec(); } void MainWindow::Save() { qDebug() << "Saving settings"; for (int row = 0; row < ui->gridLayout->rowCount(); row++) { QString rowStr = QString::number(row+1); QLayoutItem *item = ui->gridLayout->itemAtPosition(row, 1); QLineEditLabel *label = qobject_cast<QLineEditLabel*> (item->widget()); mSettings.setValue(SETTING_BTNLBL + rowStr, label->text()); } mSettings.sync(); qDebug() << mSettings.status(); } void MainWindow::on_btnDown_clicked() { mSd.RequestPageDown(); } void MainWindow::on_btnUp_clicked() { mSd.RequestPageUp(); } <|endoftext|>
<commit_before>#include "argmap.hpp" #include "commands.hpp" #include "completion.hpp" #include "odbx-sql.hpp" #include <opendbx/api> #include <stdexcept> #include <iostream> #include <sstream> #include <string> #include <cstddef> #include <cstdlib> #include <clocale> #include <readline/readline.h> #include <readline/history.h> #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef ENABLE_NLS # ifdef HAVE_LIBINTL_H # include <libintl.h> # endif #else # define gettext(string) string #endif using namespace OpenDBX; using std::string; using std::cout; using std::cerr; using std::endl; string help( ArgMap& A, const string& progname ) { return "\nOpenDBX SQL shell, version " + string( PACKAGE_VERSION ) + "\n\n" + progname + " [options]\n\n" + A.help() + "\n"; } // hack to access completion Completion* g_comp = NULL; char* complete( const char* text, int state ) { char* match = NULL; if( g_comp != NULL ) { if( state == 0 ) { g_comp->find( text ); } if( ( match = (char*) g_comp->get() ) != NULL ) { return strdup( match ); } } return match; } void output( Result& result, struct format* fparam ) { odbxres stat; unsigned long fields; while( ( stat = result.getResult( NULL, 25 ) ) != ODBX_RES_DONE ) { switch( stat ) { case ODBX_RES_TIMEOUT: case ODBX_RES_NOROWS: continue; default: break; } fields = result.columnCount(); if( fparam->header == true && fields > 0 ) { cout << result.columnName( 0 ); for( unsigned long i = 1; i < fields; i++ ) { cout << fparam->separator << result.columnName( i ); } cout << endl << "---" << endl; } while( result.getRow() != ODBX_ROW_DONE ) { if( fields > 0 ) { if( result.fieldValue( 0 ) == NULL ) { cout << "NULL"; } else { cout << fparam->delimiter << result.fieldValue( 0 ) << fparam->delimiter; } for( unsigned long i = 1; i < fields; i++ ) { if( result.fieldValue( i ) == NULL ) { cout << fparam->separator << "NULL"; } else { cout << fparam->separator << fparam->delimiter << result.fieldValue( i ) << fparam->delimiter; } } } cout << endl; } } } void loopstmts( Conn& conn, struct format* fparam, bool iactive ) { char* line; size_t len; string sql; const char* fprompt = ""; const char* cprompt = ""; Commands cmd( conn ); if( iactive ) { cout << gettext( "Interactive SQL shell, use .help to list available commands" ) << endl; fprompt = "sql> "; cprompt = " -> "; using_history(); } while( ( line = readline( fprompt ) ) != NULL ) { len = strlen( line ); if( len == 0 ) { free( line ); continue;} if( line[0] == '.' ) { cmd.exec( string( line ), fparam ); continue; } sql = string( line, len ); ::free( line ); if( sql[len-1] != ';' ) { while( ( line = readline( cprompt ) ) != NULL ) { len = strlen( line ); sql += "\n" + string( line, len ); free( line ); if( sql[sql.size()-1] == ';' ) { break; } } } if( iactive ) { add_history( sql.c_str() ); } if( sql[sql.size()-1] == ';' ) { sql.erase( sql.size()-1, 1 ); } try { Stmt stmt = conn.create( sql ); Result result = stmt.execute(); output( result, fparam ); result.finish(); } catch( OpenDBX::Exception& oe ) { cerr << gettext( "Warning: " ) << oe.what() << endl; if( oe.getType() < 0 ) { return; } } } } int main( int argc, char* argv[] ) { try { ArgMap A; string config; setlocale( LC_ALL, "" ); textdomain( "opendbx-utils" ); bindtextdomain( "opendbx-utils", LOCALEDIR ); if( !A.checkArgv( argc, argv, "--config", config ) ) { if( !A.checkArgv( argc, argv, "-c", config ) ) { config = ""; } } A.set( "help", "?", string( gettext( "print this help" ) ), false ); A.set( "backend", "b", string( gettext( "name of the backend or path to the backend library" ) ) ) = "mysql"; A.set( "config", "c", string( gettext( "read configuration from file" ) ) ) = config; A.set( "database", "d", string( gettext( "database name or database file name" ) ) ); A.set( "delimiter", "f", string( gettext( "start/end field delimiter in output" ) ) ) = "\""; A.set( "host", "h", string( gettext( "host name, IP address or path to the database server" ) ) ) = "localhost"; A.set( "interactive", "i", string( gettext( "interactive mode" ) ), false ); A.set( "keywordfile", "k", string( gettext( "SQL keyword file for command completion" ) ) ) = KEYWORDFILE; A.set( "port", "p", string( gettext( "port name or number of the database server" ) ) ); A.set( "separator", "s", string( gettext( "separator between fields in output" ) ) ) = "|"; A.set( "username", "u", string( gettext( "user name for authentication" ) ) ); string& password = A.set( "password", "w", string( gettext( "with prompt asking for the passphrase" ) ), false ); if( A.asString( "config" ) != "" ) { A.parseFile( A.asString( "config" ) ); } A.parseArgv( argc, argv ); if( A.mustDo( "help" ) ) { std::cout << help( A, string( argv[0] ) ); return 0; } if( A.mustDo( "password" ) ) { std::cout << gettext( "Password: " ); std::cin >> password; } struct format fparam; fparam.delimiter = A.asString( "delimiter" ); fparam.separator = A.asString( "separator" ); fparam.header = true; g_comp = new Completion( A.asString( "keywordfile" ) ); rl_completion_entry_function = &complete; Conn conn( A.asString( "backend" ), A.asString( "host" ), A.asString( "port" ) ); conn.bind( A.asString( "database" ), A.asString( "username" ), A.asString( "password" ) ); loopstmts( conn, &fparam, A.mustDo( "interactive" ) ); conn.finish(); delete g_comp; } catch( std::runtime_error &e ) { cerr << gettext( "Error: " ) << e.what() << endl; return 1; } catch( ... ) { cerr << gettext( "Error: Caught unknown exception" ) << endl; return 1; } return 0; } <commit_msg>use gettext functions only if gettext is enabled<commit_after>#include "argmap.hpp" #include "commands.hpp" #include "completion.hpp" #include "odbx-sql.hpp" #include <opendbx/api> #include <stdexcept> #include <iostream> #include <sstream> #include <string> #include <cstddef> #include <cstdlib> #include <clocale> #include <readline/readline.h> #include <readline/history.h> #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef ENABLE_NLS # ifdef HAVE_LIBINTL_H # include <libintl.h> # endif #else # define gettext(string) string #endif using namespace OpenDBX; using std::string; using std::cout; using std::cerr; using std::endl; string help( ArgMap& A, const string& progname ) { return "\nOpenDBX SQL shell, version " + string( PACKAGE_VERSION ) + "\n\n" + progname + " [options]\n\n" + A.help() + "\n"; } // hack to access completion Completion* g_comp = NULL; char* complete( const char* text, int state ) { char* match = NULL; if( g_comp != NULL ) { if( state == 0 ) { g_comp->find( text ); } if( ( match = (char*) g_comp->get() ) != NULL ) { return strdup( match ); } } return match; } void output( Result& result, struct format* fparam ) { odbxres stat; unsigned long fields; while( ( stat = result.getResult( NULL, 25 ) ) != ODBX_RES_DONE ) { switch( stat ) { case ODBX_RES_TIMEOUT: case ODBX_RES_NOROWS: continue; default: break; } fields = result.columnCount(); if( fparam->header == true && fields > 0 ) { cout << result.columnName( 0 ); for( unsigned long i = 1; i < fields; i++ ) { cout << fparam->separator << result.columnName( i ); } cout << endl << "---" << endl; } while( result.getRow() != ODBX_ROW_DONE ) { if( fields > 0 ) { if( result.fieldValue( 0 ) == NULL ) { cout << "NULL"; } else { cout << fparam->delimiter << result.fieldValue( 0 ) << fparam->delimiter; } for( unsigned long i = 1; i < fields; i++ ) { if( result.fieldValue( i ) == NULL ) { cout << fparam->separator << "NULL"; } else { cout << fparam->separator << fparam->delimiter << result.fieldValue( i ) << fparam->delimiter; } } } cout << endl; } } } void loopstmts( Conn& conn, struct format* fparam, bool iactive ) { char* line; size_t len; string sql; const char* fprompt = ""; const char* cprompt = ""; Commands cmd( conn ); if( iactive ) { cout << gettext( "Interactive SQL shell, use .help to list available commands" ) << endl; fprompt = "sql> "; cprompt = " -> "; using_history(); } while( ( line = readline( fprompt ) ) != NULL ) { len = strlen( line ); if( len == 0 ) { free( line ); continue;} if( line[0] == '.' ) { cmd.exec( string( line ), fparam ); continue; } sql = string( line, len ); ::free( line ); if( sql[len-1] != ';' ) { while( ( line = readline( cprompt ) ) != NULL ) { len = strlen( line ); sql += "\n" + string( line, len ); free( line ); if( sql[sql.size()-1] == ';' ) { break; } } } if( iactive ) { add_history( sql.c_str() ); } if( sql[sql.size()-1] == ';' ) { sql.erase( sql.size()-1, 1 ); } try { Stmt stmt = conn.create( sql ); Result result = stmt.execute(); output( result, fparam ); result.finish(); } catch( OpenDBX::Exception& oe ) { cerr << gettext( "Warning: " ) << oe.what() << endl; if( oe.getType() < 0 ) { return; } } } } int main( int argc, char* argv[] ) { try { ArgMap A; string config; #ifdef ENABLE_NLS setlocale( LC_ALL, "" ); textdomain( "opendbx-utils" ); bindtextdomain( "opendbx-utils", LOCALEDIR ); #endif if( !A.checkArgv( argc, argv, "--config", config ) ) { if( !A.checkArgv( argc, argv, "-c", config ) ) { config = ""; } } A.set( "help", "?", string( gettext( "print this help" ) ), false ); A.set( "backend", "b", string( gettext( "name of the backend or path to the backend library" ) ) ) = "mysql"; A.set( "config", "c", string( gettext( "read configuration from file" ) ) ) = config; A.set( "database", "d", string( gettext( "database name or database file name" ) ) ); A.set( "delimiter", "f", string( gettext( "start/end field delimiter in output" ) ) ) = "\""; A.set( "host", "h", string( gettext( "host name, IP address or path to the database server" ) ) ) = "localhost"; A.set( "interactive", "i", string( gettext( "interactive mode" ) ), false ); A.set( "keywordfile", "k", string( gettext( "SQL keyword file for command completion" ) ) ) = KEYWORDFILE; A.set( "port", "p", string( gettext( "port name or number of the database server" ) ) ); A.set( "separator", "s", string( gettext( "separator between fields in output" ) ) ) = "|"; A.set( "username", "u", string( gettext( "user name for authentication" ) ) ); string& password = A.set( "password", "w", string( gettext( "with prompt asking for the passphrase" ) ), false ); if( A.asString( "config" ) != "" ) { A.parseFile( A.asString( "config" ) ); } A.parseArgv( argc, argv ); if( A.mustDo( "help" ) ) { std::cout << help( A, string( argv[0] ) ); return 0; } if( A.mustDo( "password" ) ) { std::cout << gettext( "Password: " ); std::cin >> password; } struct format fparam; fparam.delimiter = A.asString( "delimiter" ); fparam.separator = A.asString( "separator" ); fparam.header = true; g_comp = new Completion( A.asString( "keywordfile" ) ); rl_completion_entry_function = &complete; Conn conn( A.asString( "backend" ), A.asString( "host" ), A.asString( "port" ) ); conn.bind( A.asString( "database" ), A.asString( "username" ), A.asString( "password" ) ); loopstmts( conn, &fparam, A.mustDo( "interactive" ) ); conn.finish(); delete g_comp; } catch( std::runtime_error &e ) { cerr << gettext( "Error: " ) << e.what() << endl; return 1; } catch( ... ) { cerr << gettext( "Error: Caught unknown exception" ) << endl; return 1; } return 0; } <|endoftext|>
<commit_before>/* * Copyright 2010-2012 PathScale, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 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. */ /** * guard.cc: Functions for thread-safe static initialisation. * * Static values in C++ can be initialised lazily their first use. This file * contains functions that are used to ensure that two threads attempting to * initialize the same static do not call the constructor twice. This is * important because constructors can have side effects, so calling the * constructor twice may be very bad. * * Statics that require initialisation are protected by a 64-bit value. Any * platform that can do 32-bit atomic test and set operations can use this * value as a low-overhead lock. Because statics (in most sane code) are * accessed far more times than they are initialised, this lock implementation * is heavily optimised towards the case where the static has already been * initialised. */ #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <assert.h> #include "atomic.h" // Older GCC doesn't define __LITTLE_ENDIAN__ #ifndef __LITTLE_ENDIAN__ // If __BYTE_ORDER__ is defined, use that instead # ifdef __BYTE_ORDER__ # if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ # define __LITTLE_ENDIAN__ # endif // x86 and ARM are the most common little-endian CPUs, so let's have a // special case for them (ARM is already special cased). Assume everything // else is big endian. # elif defined(__x86_64) || defined(__i386) # define __LITTLE_ENDIAN__ # endif #endif /* * The least significant bit of the guard variable indicates that the object * has been initialised, the most significant bit is used for a spinlock. */ #ifdef __arm__ // ARM ABI - 32-bit guards. typedef uint32_t guard_t; static const uint32_t LOCKED = static_cast<guard_t>(1) << 31; static const uint32_t INITIALISED = 1; #else typedef uint64_t guard_t; # if defined(__LITTLE_ENDIAN__) static const guard_t LOCKED = static_cast<guard_t>(1) << 63; static const guard_t INITIALISED = 1; # else static const guard_t LOCKED = 1; static const guard_t INITIALISED = static_cast<guard_t>(1) << 56; # endif #endif /** * Acquires a lock on a guard, returning 0 if the object has already been * initialised, and 1 if it has not. If the object is already constructed then * this function just needs to read a byte from memory and return. */ extern "C" int __cxa_guard_acquire(volatile guard_t *guard_object) { // Not an atomic read, doesn't establish a happens-before relationship, but // if one is already established and we end up seeing an initialised state // then it's a fast path, otherwise we'll do something more expensive than // this test anyway... if ((INITIALISED == *guard_object)) { return 0; } // Spin trying to do the initialisation while (1) { // Loop trying to move the value of the guard from 0 (not // locked, not initialised) to the locked-uninitialised // position. switch (__sync_val_compare_and_swap(guard_object, 0, LOCKED)) { // If the old value was 0, we succeeded, so continue // initialising case 0: return 1; // If this was already initialised, return and let the caller skip // initialising it again. case INITIALISED: return 0; // If it is locked by another thread, relinquish the CPU and try // again later. case LOCKED: case LOCKED | INITIALISED: sched_yield(); break; // If it is some other value, then something has gone badly wrong. // Give up. default: fprintf(stderr, "Invalid state detected attempting to lock static initialiser.\n"); abort(); } } //__builtin_unreachable(); return 0; } /** * Releases the lock without marking the object as initialised. This function * is called if initialising a static causes an exception to be thrown. */ extern "C" void __cxa_guard_abort(volatile guard_t *guard_object) { __attribute__((unused)) bool reset = __sync_bool_compare_and_swap(guard_object, LOCKED, 0); assert(reset); } /** * Releases the guard and marks the object as initialised. This function is * called after successful initialisation of a static. */ extern "C" void __cxa_guard_release(volatile guard_t *guard_object) { __attribute__((unused)) bool reset = __sync_bool_compare_and_swap(guard_object, LOCKED, INITIALISED); assert(reset); } <commit_msg>Reorganize code to use only 32bit atomic ops for 32bit platforms. 32bit PowerPC for example lacks 64bit CAS.<commit_after>/* * Copyright 2010-2012 PathScale, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 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. */ /** * guard.cc: Functions for thread-safe static initialisation. * * Static values in C++ can be initialised lazily their first use. This file * contains functions that are used to ensure that two threads attempting to * initialize the same static do not call the constructor twice. This is * important because constructors can have side effects, so calling the * constructor twice may be very bad. * * Statics that require initialisation are protected by a 64-bit value. Any * platform that can do 32-bit atomic test and set operations can use this * value as a low-overhead lock. Because statics (in most sane code) are * accessed far more times than they are initialised, this lock implementation * is heavily optimised towards the case where the static has already been * initialised. */ #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <assert.h> #include "atomic.h" // Older GCC doesn't define __LITTLE_ENDIAN__ #ifndef __LITTLE_ENDIAN__ // If __BYTE_ORDER__ is defined, use that instead # ifdef __BYTE_ORDER__ # if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ # define __LITTLE_ENDIAN__ # endif // x86 and ARM are the most common little-endian CPUs, so let's have a // special case for them (ARM is already special cased). Assume everything // else is big endian. # elif defined(__x86_64) || defined(__i386) # define __LITTLE_ENDIAN__ # endif #endif /* * The least significant bit of the guard variable indicates that the object * has been initialised, the most significant bit is used for a spinlock. */ #ifdef __arm__ // ARM ABI - 32-bit guards. typedef uint32_t guard_t; typedef uint32_t lock_t; static const uint32_t LOCKED = static_cast<guard_t>(1) << 31; static const uint32_t INITIALISED = 1; #define LOCK_PART(guard) (guard) #define INIT_PART(guard) (guard) #elif defined(_LP64) typedef uint64_t guard_t; typedef uint64_t lock_t; # if defined(__LITTLE_ENDIAN__) static const guard_t LOCKED = static_cast<guard_t>(1) << 63; static const guard_t INITIALISED = 1; # else static const guard_t LOCKED = 1; static const guard_t INITIALISED = static_cast<guard_t>(1) << 56; # endif #define LOCK_PART(guard) (guard) #define INIT_PART(guard) (guard) #else # if defined(__LITTLE_ENDIAN__) typedef struct { uint32_t init_half; uint32_t lock_half; } guard_t; typedef uint32_t lock_t; static const uint32_t LOCKED = static_cast<lock_t>(1) << 31; static const uint32_t INITIALISED = 1; # else typedef struct { uint32_t init_half; uint32_t lock_half; } guard_t; static const uint32_t LOCKED = 1; static const uint32_t INITIALISED = static_cast<lock_t>(1) << 24; # endif #define LOCK_PART(guard) (&(guard)->lock_half) #define INIT_PART(guard) (&(guard)->init_half) #endif static const lock_t INITIAL = 0; /** * Acquires a lock on a guard, returning 0 if the object has already been * initialised, and 1 if it has not. If the object is already constructed then * this function just needs to read a byte from memory and return. */ extern "C" int __cxa_guard_acquire(volatile guard_t *guard_object) { lock_t old; // Not an atomic read, doesn't establish a happens-before relationship, but // if one is already established and we end up seeing an initialised state // then it's a fast path, otherwise we'll do something more expensive than // this test anyway... if (INITIALISED == *INIT_PART(guard_object)) return 0; // Spin trying to do the initialisation for (;;) { // Loop trying to move the value of the guard from 0 (not // locked, not initialised) to the locked-uninitialised // position. old = __sync_val_compare_and_swap(LOCK_PART(guard_object), INITIAL, LOCKED); if (old == INITIAL) { // Lock obtained. If lock and init bit are // in separate words, check for init race. if (INIT_PART(guard_object) == LOCK_PART(guard_object)) return 1; if (INITIALISED != *INIT_PART(guard_object)) return 1; // No need for a memory barrier here, // see first comment. *LOCK_PART(guard_object) = INITIAL; return 0; } // If lock and init bit are in the same word, check again // if we are done. if (INIT_PART(guard_object) == LOCK_PART(guard_object) && old == INITIALISED) return 0; assert(old == LOCKED); // Another thread holds the lock. // If lock and init bit are in different words, check // if we are done before yielding and looping. if (INIT_PART(guard_object) != LOCK_PART(guard_object) && INITIALISED == *INIT_PART(guard_object)) return 0; sched_yield(); } } /** * Releases the lock without marking the object as initialised. This function * is called if initialising a static causes an exception to be thrown. */ extern "C" void __cxa_guard_abort(volatile guard_t *guard_object) { __attribute__((unused)) bool reset = __sync_bool_compare_and_swap(LOCK_PART(guard_object), LOCKED, INITIAL); assert(reset); } /** * Releases the guard and marks the object as initialised. This function is * called after successful initialisation of a static. */ extern "C" void __cxa_guard_release(volatile guard_t *guard_object) { lock_t old; if (INIT_PART(guard_object) == LOCK_PART(guard_object)) old = LOCKED; else old = INITIAL; __attribute__((unused)) bool reset = __sync_bool_compare_and_swap(INIT_PART(guard_object), old, INITIALISED); assert(reset); if (INIT_PART(guard_object) != LOCK_PART(guard_object)) *LOCK_PART(guard_object) = INITIAL; } <|endoftext|>
<commit_before>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // ok is an experimental test harness, maybe to replace DM. Key features: // * work is balanced across separate processes for stability and isolation; // * ok is entirely opt-in. No more maintaining huge --blacklists. #include "SkGraphics.h" #include "SkOSFile.h" #include "SkPicture.h" #include "SkSurface.h" #include "gm.h" #include <chrono> #include <functional> #include <future> #include <list> #include <map> #include <memory> #include <regex> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <thread> #if !defined(__has_include) #define __has_include(x) 0 #endif static thread_local const char* tls_name = ""; #if __has_include(<execinfo.h>) && __has_include(<fcntl.h>) && __has_include(<signal.h>) #include <execinfo.h> #include <fcntl.h> #include <signal.h> static int crash_stacktrace_fd = 2/*stderr*/; static void setup_crash_handler() { static void (*original_handlers[32])(int); for (int sig : std::vector<int>{ SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV }) { original_handlers[sig] = signal(sig, [](int sig) { auto ez_write = [](const char* str) { write(crash_stacktrace_fd, str, strlen(str)); }; ez_write("\ncaught signal "); switch (sig) { #define CASE(s) case s: ez_write(#s); break CASE(SIGABRT); CASE(SIGBUS); CASE(SIGFPE); CASE(SIGILL); CASE(SIGSEGV); #undef CASE } ez_write(" while running '"); ez_write(tls_name); ez_write("'\n"); void* stack[128]; int frames = backtrace(stack, sizeof(stack)/sizeof(*stack)); backtrace_symbols_fd(stack, frames, crash_stacktrace_fd); signal(sig, original_handlers[sig]); raise(sig); }); } } static void defer_crash_stacktraces() { crash_stacktrace_fd = fileno(tmpfile()); atexit([] { lseek(crash_stacktrace_fd, 0, SEEK_SET); char buf[1024]; while (size_t bytes = read(crash_stacktrace_fd, buf, sizeof(buf))) { write(2, buf, bytes); } }); } #else static void setup_crash_handler() {} static void defer_crash_stacktraces() {} #endif enum class Status { OK, Failed, Crashed, Skipped, None }; struct Engine { virtual ~Engine() {} virtual bool spawn(std::function<Status(void)>) = 0; virtual Status wait_one() = 0; }; struct SerialEngine : Engine { Status last = Status::None; bool spawn(std::function<Status(void)> fn) override { last = fn(); return true; } Status wait_one() override { Status s = last; last = Status::None; return s; } }; struct ThreadEngine : Engine { std::list<std::future<Status>> live; bool spawn(std::function<Status(void)> fn) override { live.push_back(std::async(std::launch::async, fn)); return true; } Status wait_one() override { if (live.empty()) { return Status::None; } for (;;) { for (auto it = live.begin(); it != live.end(); it++) { if (it->wait_for(std::chrono::seconds::zero()) == std::future_status::ready) { Status s = it->get(); live.erase(it); return s; } } } } }; #if defined(_MSC_VER) using ForkEngine = ThreadEngine; #else #include <sys/wait.h> #include <unistd.h> struct ForkEngine : Engine { bool spawn(std::function<Status(void)> fn) override { switch (fork()) { case 0: _exit((int)fn()); case -1: return false; default: return true; } } Status wait_one() override { do { int status; if (wait(&status) > 0) { return WIFEXITED(status) ? (Status)WEXITSTATUS(status) : Status::Crashed; } } while (errno == EINTR); return Status::None; } }; #endif struct Src { virtual ~Src() {} virtual std::string name() = 0; virtual SkISize size() = 0; virtual void draw(SkCanvas*) = 0; }; struct Stream { virtual ~Stream() {} virtual std::unique_ptr<Src> next() = 0; }; struct Options { std::map<std::string, std::string> kv; explicit Options(std::string str) { std::string k,v, *curr = &k; for (auto c : str) { switch(c) { case ',': kv[k] = v; curr = &(k = ""); break; case '=': curr = &(v = ""); break; default: *curr += c; } } kv[k] = v; } std::string lookup(std::string k, std::string fallback) { for (auto it = kv.find(k); it != kv.end(); ) { return it->second; } return fallback; } }; struct GMStream : Stream { const skiagm::GMRegistry* registry = skiagm::GMRegistry::Head(); struct GMSrc : Src { skiagm::GM* (*factory)(void*); std::unique_ptr<skiagm::GM> gm; std::string name() override { gm.reset(factory(nullptr)); return gm->getName(); } SkISize size() override { return gm->getISize(); } void draw(SkCanvas* canvas) override { canvas->clear(0xffffffff); canvas->concat(gm->getInitialTransform()); gm->draw(canvas); } }; std::unique_ptr<Src> next() override { if (!registry) { return nullptr; } GMSrc src; src.factory = registry->factory(); registry = registry->next(); return std::unique_ptr<Src>{new GMSrc{std::move(src)}}; } }; struct SKPStream : Stream { std::string dir; std::vector<std::string> skps; explicit SKPStream(Options options) : dir(options.lookup("dir", "skps")) { SkOSFile::Iter it{dir.c_str(), ".skp"}; for (SkString path; it.next(&path); ) { skps.push_back(path.c_str()); } } struct SKPSrc : Src { std::string dir, path; sk_sp<SkPicture> pic; std::string name() override { return path; } SkISize size() override { auto skp = SkData::MakeFromFileName((dir+"/"+path).c_str()); pic = SkPicture::MakeFromData(skp.get()); return pic->cullRect().roundOut().size(); } void draw(SkCanvas* canvas) override { canvas->clear(0xffffffff); pic->playback(canvas); } }; std::unique_ptr<Src> next() override { if (skps.empty()) { return nullptr; } SKPSrc src; src.dir = dir; src.path = skps.back(); skps.pop_back(); return std::unique_ptr<Src>{new SKPSrc{std::move(src)}}; } }; struct { const char* name; std::unique_ptr<Stream> (*factory)(Options); } streams[] = { {"gm", [](Options options) { return std::unique_ptr<Stream>{new GMStream}; }}, {"skp", [](Options options) { return std::unique_ptr<Stream>{new SKPStream{options}}; }}, }; int main(int argc, char** argv) { SkGraphics::Init(); setup_crash_handler(); int jobs {1}; std::regex match {".*"}; std::regex search {".*"}; std::string write_dir {""}; std::unique_ptr<Stream> stream; auto help = [&] { std::string stream_types; for (auto st : streams) { if (!stream_types.empty()) { stream_types += ", "; } stream_types += st.name; } printf("%s [-j N] [-m regex] [-s regex] [-w dir] [-h] stream[:k=v,k=v,...] \n" " -j: Run at most N processes at any time. \n" " If <0, use -N threads instead. \n" " If 0, use one thread in one process. \n" " If 1 (default) or -1, auto-detect N. \n" " -m: Run only names matching regex exactly. \n" " -s: Run only names matching regex anywhere. \n" " -w: If set, write .pngs into dir. \n" " -h: Print this message and exit. \n" " stream: content to draw: %s \n" " Some streams have options, e.g. skp:dir=skps \n", argv[0], stream_types.c_str()); return 1; }; for (int i = 1; i < argc; i++) { if (0 == strcmp("-j", argv[i])) { jobs = atoi(argv[++i]); } if (0 == strcmp("-m", argv[i])) { match = argv[++i] ; } if (0 == strcmp("-s", argv[i])) { search = argv[++i] ; } if (0 == strcmp("-w", argv[i])) { write_dir = argv[++i] ; } if (0 == strcmp("-h", argv[i])) { return help(); } for (auto st : streams) { size_t len = strlen(st.name); if (0 == strncmp(st.name, argv[i], len)) { switch (argv[i][len]) { case ':': len++; case '\0': stream = st.factory(Options{argv[i]+len}); } } } } if (!stream) { return help(); } std::unique_ptr<Engine> engine; if (jobs == 0) { engine.reset(new SerialEngine); } if (jobs > 0) { engine.reset(new ForkEngine); defer_crash_stacktraces(); } if (jobs < 0) { engine.reset(new ThreadEngine); jobs = -jobs; } if (jobs == 1) { jobs = std::thread::hardware_concurrency(); } if (!write_dir.empty()) { sk_mkdir(write_dir.c_str()); } int ok = 0, failed = 0, crashed = 0, skipped = 0; auto update_stats = [&](Status s) { switch (s) { case Status::OK: ok++; break; case Status::Failed: failed++; break; case Status::Crashed: crashed++; break; case Status::Skipped: skipped++; break; case Status::None: return; } const char* leader = "\r"; auto print = [&](int count, const char* label) { if (count) { printf("%s%d %s", leader, count, label); leader = ", "; } }; print(ok, "ok"); print(failed, "failed"); print(crashed, "crashed"); print(skipped, "skipped"); fflush(stdout); }; auto spawn = [&](std::function<Status(void)> fn) { if (--jobs < 0) { update_stats(engine->wait_one()); } while (!engine->spawn(fn)) { update_stats(engine->wait_one()); } }; for (std::unique_ptr<Src> owned = stream->next(); owned; owned = stream->next()) { Src* raw = owned.release(); // Can't move std::unique_ptr into a lambda in C++11. :( spawn([=] { std::unique_ptr<Src> src{raw}; auto name = src->name(); tls_name = name.c_str(); if (!std::regex_match (name, match) || !std::regex_search(name, search)) { return Status::Skipped; } auto size = src->size(); auto surface = SkSurface::MakeRasterN32Premul(size.width(), size.height()); auto canvas = surface->getCanvas(); src->draw(canvas); canvas->restoreToCount(0); if (!write_dir.empty()) { auto image = surface->makeImageSnapshot(); sk_sp<SkData> png{image->encode()}; std::string path = write_dir + "/" + name + ".png"; SkFILEWStream{path.c_str()}.write(png->data(), png->size()); } return Status::OK; }); } for (Status s = Status::OK; s != Status::None; ) { s = engine->wait_one(); update_stats(s); } printf("\n"); return (failed || crashed) ? 1 : 0; } <commit_msg>ok: introduce the idea of Dsts<commit_after>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // ok is an experimental test harness, maybe to replace DM. Key features: // * work is balanced across separate processes for stability and isolation; // * ok is entirely opt-in. No more maintaining huge --blacklists. #include "SkGraphics.h" #include "SkOSFile.h" #include "SkPicture.h" #include "SkSurface.h" #include "gm.h" #include <chrono> #include <functional> #include <future> #include <list> #include <map> #include <memory> #include <regex> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <thread> #if !defined(__has_include) #define __has_include(x) 0 #endif static thread_local const char* tls_name = ""; #if __has_include(<execinfo.h>) && __has_include(<fcntl.h>) && __has_include(<signal.h>) #include <execinfo.h> #include <fcntl.h> #include <signal.h> static int crash_stacktrace_fd = 2/*stderr*/; static void setup_crash_handler() { static void (*original_handlers[32])(int); for (int sig : std::vector<int>{ SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV }) { original_handlers[sig] = signal(sig, [](int sig) { auto ez_write = [](const char* str) { write(crash_stacktrace_fd, str, strlen(str)); }; ez_write("\ncaught signal "); switch (sig) { #define CASE(s) case s: ez_write(#s); break CASE(SIGABRT); CASE(SIGBUS); CASE(SIGFPE); CASE(SIGILL); CASE(SIGSEGV); #undef CASE } ez_write(" while running '"); ez_write(tls_name); ez_write("'\n"); void* stack[128]; int frames = backtrace(stack, sizeof(stack)/sizeof(*stack)); backtrace_symbols_fd(stack, frames, crash_stacktrace_fd); signal(sig, original_handlers[sig]); raise(sig); }); } } static void defer_crash_stacktraces() { crash_stacktrace_fd = fileno(tmpfile()); atexit([] { lseek(crash_stacktrace_fd, 0, SEEK_SET); char buf[1024]; while (size_t bytes = read(crash_stacktrace_fd, buf, sizeof(buf))) { write(2, buf, bytes); } }); } #else static void setup_crash_handler() {} static void defer_crash_stacktraces() {} #endif enum class Status { OK, Failed, Crashed, Skipped, None }; struct Engine { virtual ~Engine() {} virtual bool spawn(std::function<Status(void)>) = 0; virtual Status wait_one() = 0; }; struct SerialEngine : Engine { Status last = Status::None; bool spawn(std::function<Status(void)> fn) override { last = fn(); return true; } Status wait_one() override { Status s = last; last = Status::None; return s; } }; struct ThreadEngine : Engine { std::list<std::future<Status>> live; bool spawn(std::function<Status(void)> fn) override { live.push_back(std::async(std::launch::async, fn)); return true; } Status wait_one() override { if (live.empty()) { return Status::None; } for (;;) { for (auto it = live.begin(); it != live.end(); it++) { if (it->wait_for(std::chrono::seconds::zero()) == std::future_status::ready) { Status s = it->get(); live.erase(it); return s; } } } } }; #if defined(_MSC_VER) using ForkEngine = ThreadEngine; #else #include <sys/wait.h> #include <unistd.h> struct ForkEngine : Engine { bool spawn(std::function<Status(void)> fn) override { switch (fork()) { case 0: _exit((int)fn()); case -1: return false; default: return true; } } Status wait_one() override { do { int status; if (wait(&status) > 0) { return WIFEXITED(status) ? (Status)WEXITSTATUS(status) : Status::Crashed; } } while (errno == EINTR); return Status::None; } }; #endif struct Src { virtual ~Src() {} virtual std::string name() = 0; virtual SkISize size() = 0; virtual void draw(SkCanvas*) = 0; }; struct Stream { virtual ~Stream() {} virtual std::unique_ptr<Src> next() = 0; }; struct Options { std::map<std::string, std::string> kv; explicit Options(std::string str = "") { std::string k,v, *curr = &k; for (auto c : str) { switch(c) { case ',': kv[k] = v; curr = &(k = ""); break; case '=': curr = &(v = ""); break; default: *curr += c; } } kv[k] = v; } std::string lookup(std::string k, std::string fallback = "") { for (auto it = kv.find(k); it != kv.end(); ) { return it->second; } return fallback; } }; template <typename T> static std::unique_ptr<T> move_unique(T& v) { return std::unique_ptr<T>{new T{std::move(v)}}; } struct GMStream : Stream { const skiagm::GMRegistry* registry = skiagm::GMRegistry::Head(); static std::unique_ptr<Stream> Create(Options) { GMStream stream; return move_unique(stream); } struct GMSrc : Src { skiagm::GM* (*factory)(void*); std::unique_ptr<skiagm::GM> gm; std::string name() override { gm.reset(factory(nullptr)); return gm->getName(); } SkISize size() override { return gm->getISize(); } void draw(SkCanvas* canvas) override { canvas->clear(0xffffffff); canvas->concat(gm->getInitialTransform()); gm->draw(canvas); } }; std::unique_ptr<Src> next() override { if (!registry) { return nullptr; } GMSrc src; src.factory = registry->factory(); registry = registry->next(); return move_unique(src); } }; struct SKPStream : Stream { std::string dir; std::vector<std::string> skps; static std::unique_ptr<Stream> Create(Options options) { SKPStream stream; stream.dir = options.lookup("dir", "skps"); SkOSFile::Iter it{stream.dir.c_str(), ".skp"}; for (SkString path; it.next(&path); ) { stream.skps.push_back(path.c_str()); } return move_unique(stream); } struct SKPSrc : Src { std::string dir, path; sk_sp<SkPicture> pic; std::string name() override { return path; } SkISize size() override { auto skp = SkData::MakeFromFileName((dir+"/"+path).c_str()); pic = SkPicture::MakeFromData(skp.get()); return pic->cullRect().roundOut().size(); } void draw(SkCanvas* canvas) override { canvas->clear(0xffffffff); pic->playback(canvas); } }; std::unique_ptr<Src> next() override { if (skps.empty()) { return nullptr; } SKPSrc src; src.dir = dir; src.path = skps.back(); skps.pop_back(); return move_unique(src); } }; struct Dst { virtual ~Dst() {} virtual SkCanvas* canvas() = 0; virtual void write(std::string path_prefix) = 0; }; struct SWDst : Dst { sk_sp<SkSurface> surface; static std::unique_ptr<Dst> Create(SkISize size, Options options) { SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height()); if (options.lookup("ct") == "565") { info = info.makeColorType(kRGB_565_SkColorType); } if (options.lookup("ct") == "f16") { info = info.makeColorType(kRGBA_F16_SkColorType); } SWDst dst; dst.surface = SkSurface::MakeRaster(info); return move_unique(dst); } SkCanvas* canvas() override { return surface->getCanvas(); } void write(std::string path_prefix) override { auto image = surface->makeImageSnapshot(); sk_sp<SkData> png{image->encode()}; SkFILEWStream{(path_prefix + ".png").c_str()}.write(png->data(), png->size()); } }; struct { const char* name; std::unique_ptr<Stream> (*factory)(Options); } streams[] = { {"gm", GMStream::Create }, {"skp", SKPStream::Create }, }; struct { const char* name; std::unique_ptr<Dst> (*factory)(SkISize, Options); } dsts[] = { {"sw", SWDst::Create }, }; int main(int argc, char** argv) { SkGraphics::Init(); setup_crash_handler(); int jobs {1}; std::regex match {".*"}; std::regex search {".*"}; std::string write_dir {""}; std::unique_ptr<Stream> stream; std::unique_ptr<Dst> (*dst_factory)(SkISize, Options) = nullptr; Options dst_options; auto help = [&] { std::string stream_types, dst_types; for (auto s : streams) { if (!stream_types.empty()) { stream_types += ", "; } stream_types += s.name; } for (auto d : dsts) { if (!dst_types.empty()) { dst_types += ", "; } dst_types += d.name; } printf("%s [-j N] [-m regex] [-s regex] [-w dir] [-h] src[:k=v,...] dst[:k=v,...] \n" " -j: Run at most N processes at any time. \n" " If <0, use -N threads instead. \n" " If 0, use one thread in one process. \n" " If 1 (default) or -1, auto-detect N. \n" " -m: Run only names matching regex exactly. \n" " -s: Run only names matching regex anywhere. \n" " -w: If set, write .pngs into dir. \n" " -h: Print this message and exit. \n" " src: content to draw: %s \n" " dst: how to draw that content: %s \n" " Some srcs and dsts have options, e.g. skp:dir=skps sw:ct=565 \n", argv[0], stream_types.c_str(), dst_types.c_str()); return 1; }; for (int i = 1; i < argc; i++) { if (0 == strcmp("-j", argv[i])) { jobs = atoi(argv[++i]); } if (0 == strcmp("-m", argv[i])) { match = argv[++i] ; } if (0 == strcmp("-s", argv[i])) { search = argv[++i] ; } if (0 == strcmp("-w", argv[i])) { write_dir = argv[++i] ; } if (0 == strcmp("-h", argv[i])) { return help(); } for (auto s : streams) { size_t len = strlen(s.name); if (0 == strncmp(s.name, argv[i], len)) { switch (argv[i][len]) { case ':': len++; case '\0': stream = s.factory(Options{argv[i]+len}); } } } for (auto d : dsts) { size_t len = strlen(d.name); if (0 == strncmp(d.name, argv[i], len)) { switch (argv[i][len]) { case ':': len++; case '\0': dst_factory = d.factory; dst_options = Options{argv[i]+len}; } } } } if (!stream || !dst_factory) { return help(); } std::unique_ptr<Engine> engine; if (jobs == 0) { engine.reset(new SerialEngine); } if (jobs > 0) { engine.reset(new ForkEngine); defer_crash_stacktraces(); } if (jobs < 0) { engine.reset(new ThreadEngine); jobs = -jobs; } if (jobs == 1) { jobs = std::thread::hardware_concurrency(); } if (!write_dir.empty()) { sk_mkdir(write_dir.c_str()); } int ok = 0, failed = 0, crashed = 0, skipped = 0; auto update_stats = [&](Status s) { switch (s) { case Status::OK: ok++; break; case Status::Failed: failed++; break; case Status::Crashed: crashed++; break; case Status::Skipped: skipped++; break; case Status::None: return; } const char* leader = "\r"; auto print = [&](int count, const char* label) { if (count) { printf("%s%d %s", leader, count, label); leader = ", "; } }; print(ok, "ok"); print(failed, "failed"); print(crashed, "crashed"); print(skipped, "skipped"); fflush(stdout); }; auto spawn = [&](std::function<Status(void)> fn) { if (--jobs < 0) { update_stats(engine->wait_one()); } while (!engine->spawn(fn)) { update_stats(engine->wait_one()); } }; for (std::unique_ptr<Src> owned = stream->next(); owned; owned = stream->next()) { Src* raw = owned.release(); // Can't move std::unique_ptr into a lambda in C++11. :( spawn([=] { std::unique_ptr<Src> src{raw}; auto name = src->name(); tls_name = name.c_str(); if (!std::regex_match (name, match) || !std::regex_search(name, search)) { return Status::Skipped; } auto dst = dst_factory(src->size(), dst_options); auto canvas = dst->canvas(); src->draw(canvas); canvas->restoreToCount(0); if (!write_dir.empty()) { dst->write(write_dir + "/" + name); } return Status::OK; }); } for (Status s = Status::OK; s != Status::None; ) { s = engine->wait_one(); update_stats(s); } printf("\n"); return (failed || crashed) ? 1 : 0; } <|endoftext|>
<commit_before>/* c2ffi Copyright (C) 2013 Ryan Pavlik This file is part of c2ffi. c2ffi 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. c2ffi 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 c2ffi. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <llvm/Support/Host.h> #include <llvm/ADT/IntrusiveRefCntPtr.h> #include <clang/Basic/DiagnosticOptions.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/FrontendTool/Utils.h> #include <clang/Basic/TargetOptions.h> #include <clang/Basic/TargetInfo.h> #include <clang/Basic/FileManager.h> #include <clang/Basic/SourceManager.h> #include <clang/Lex/HeaderSearch.h> #include <clang/Lex/Preprocessor.h> #include <clang/Basic/Diagnostic.h> #include <clang/AST/ASTContext.h> #include <clang/AST/ASTConsumer.h> #include <clang/Parse/Parser.h> #include <clang/Parse/ParseAST.h> #include <sys/stat.h> #include "c2ffi/init.h" using namespace c2ffi; void c2ffi::add_include(clang::CompilerInstance &ci, const char *path, bool is_angled, bool show_error) { struct stat buf; if(stat(path, &buf) < 0 || !S_ISDIR(buf.st_mode)) { if(show_error) { std::cerr << "Error: Not a directory: "; if(is_angled) std::cerr << "-i "; else std::cerr << "-I "; std::cerr << path << std::endl; exit(1); } return; } const clang::DirectoryEntry *dirent = ci.getFileManager().getDirectory(path); clang::DirectoryLookup lookup(dirent, clang::SrcMgr::C_System, false); ci.getPreprocessor().getHeaderSearchInfo() .AddSearchPath(lookup, is_angled); } void c2ffi::add_includes(clang::CompilerInstance &ci, c2ffi::IncludeVector &v, bool is_angled, bool show_error) { for(c2ffi::IncludeVector::iterator i = v.begin(); i != v.end(); i++) add_include(ci, (*i).c_str(), is_angled, show_error); } void c2ffi::init_ci(config &c, clang::CompilerInstance &ci) { using clang::DiagnosticOptions; using clang::TextDiagnosticPrinter; using clang::TargetOptions; using clang::TargetInfo; ci.getInvocation().setLangDefaults(ci.getLangOpts(), c.kind, clang::LangStandard::lang_unspecified); DiagnosticOptions *dopt = new DiagnosticOptions; TextDiagnosticPrinter *tpd = new TextDiagnosticPrinter(llvm::outs(), dopt, true); ci.createDiagnostics(tpd); llvm::IntrusiveRefCntPtr<TargetOptions> *pto = new llvm::IntrusiveRefCntPtr<TargetOptions>(new TargetOptions()); (*pto)->Triple = llvm::sys::getDefaultTargetTriple(); TargetInfo *pti = TargetInfo::CreateTargetInfo(ci.getDiagnostics(), pto->getPtr()); ci.setTarget(pti); ci.createFileManager(); ci.createSourceManager(ci.getFileManager()); ci.createPreprocessor(); ci.getPreprocessorOpts().UsePredefines = false; } <commit_msg>Errors to stderr not stdout<commit_after>/* c2ffi Copyright (C) 2013 Ryan Pavlik This file is part of c2ffi. c2ffi 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. c2ffi 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 c2ffi. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <llvm/Support/Host.h> #include <llvm/ADT/IntrusiveRefCntPtr.h> #include <clang/Basic/DiagnosticOptions.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/FrontendTool/Utils.h> #include <clang/Basic/TargetOptions.h> #include <clang/Basic/TargetInfo.h> #include <clang/Basic/FileManager.h> #include <clang/Basic/SourceManager.h> #include <clang/Lex/HeaderSearch.h> #include <clang/Lex/Preprocessor.h> #include <clang/Basic/Diagnostic.h> #include <clang/AST/ASTContext.h> #include <clang/AST/ASTConsumer.h> #include <clang/Parse/Parser.h> #include <clang/Parse/ParseAST.h> #include <sys/stat.h> #include "c2ffi/init.h" using namespace c2ffi; void c2ffi::add_include(clang::CompilerInstance &ci, const char *path, bool is_angled, bool show_error) { struct stat buf; if(stat(path, &buf) < 0 || !S_ISDIR(buf.st_mode)) { if(show_error) { std::cerr << "Error: Not a directory: "; if(is_angled) std::cerr << "-i "; else std::cerr << "-I "; std::cerr << path << std::endl; exit(1); } return; } const clang::DirectoryEntry *dirent = ci.getFileManager().getDirectory(path); clang::DirectoryLookup lookup(dirent, clang::SrcMgr::C_System, false); ci.getPreprocessor().getHeaderSearchInfo() .AddSearchPath(lookup, is_angled); } void c2ffi::add_includes(clang::CompilerInstance &ci, c2ffi::IncludeVector &v, bool is_angled, bool show_error) { for(c2ffi::IncludeVector::iterator i = v.begin(); i != v.end(); i++) add_include(ci, (*i).c_str(), is_angled, show_error); } void c2ffi::init_ci(config &c, clang::CompilerInstance &ci) { using clang::DiagnosticOptions; using clang::TextDiagnosticPrinter; using clang::TargetOptions; using clang::TargetInfo; ci.getInvocation().setLangDefaults(ci.getLangOpts(), c.kind, clang::LangStandard::lang_unspecified); DiagnosticOptions *dopt = new DiagnosticOptions; TextDiagnosticPrinter *tpd = new TextDiagnosticPrinter(llvm::errs(), dopt, true); ci.createDiagnostics(tpd); llvm::IntrusiveRefCntPtr<TargetOptions> *pto = new llvm::IntrusiveRefCntPtr<TargetOptions>(new TargetOptions()); (*pto)->Triple = llvm::sys::getDefaultTargetTriple(); TargetInfo *pti = TargetInfo::CreateTargetInfo(ci.getDiagnostics(), pto->getPtr()); ci.setTarget(pti); ci.createFileManager(); ci.createSourceManager(ci.getFileManager()); ci.createPreprocessor(); ci.getPreprocessorOpts().UsePredefines = false; } <|endoftext|>
<commit_before>#ifndef SIMHASH_HASH_H #define SIMHASH_HASH_H /* Simply holds references to all of our hash functions */ #include "hashes/jenkins.h" #include "hashes/murmur.h" #include "hashes/fnv.h" /* Include a reference to the tokenizer to use */ #include "tokenizers/strspn.h" /* For hash_t */ #include "common.h" #include "cyclic.hpp" #include <vector> namespace Simhash { /** * Compute a similarity hash for the provided string using a rolling hash * function and a provided hash window * * @param tokens - An NULL-terminated array of character pointers to the * nul-terminated tokens comprising the text. * * @return hash representative of the content of the text */ template <typename Hash=jenkins> class Simhash { private: class Accumulator { private: static const size_t BITS = sizeof(hash_t) * 8; size_t window; Cyclic<hash_t> cyclic; std::vector<int64_t> v; public: Accumulator() : window(3), cyclic(window), v(BITS, 0) {} void update(hash_t hash) { hash = cyclic.push(hash); for (int j = (BITS - 1); j >= 0; --j) { v[j] += (hash & 1) ? 1 : -1; hash >>= 1; } } /* With counts appropriately tallied, create a 1 bit for each of * the counts that's positive. That result is the hash. */ hash_t result() { hash_t hash(0); for (size_t j = 0; j < BITS; ++j) { if (v[j] > 0) { hash |= (static_cast<hash_t>(1) << j); } } return hash; } }; public: typedef Hash hash_type; /* Alias of operator() * * Some languages have difficulty making use of operator(), and so this * it made available for those languages */ inline hash_t hash(char **tokens) { return operator()(tokens); } /* Return a simhash value using a moving window */ hash_t operator()(char **tokens) { Hash hasher; Accumulator accumulator; for (char **tp = tokens; *tp != NULL; ++tp) { size_t len = strlen(*tp); if (len > 0) { accumulator.update(hasher(*tp, len, 0)); } } return accumulator.result(); } /* As above, but operate on a vector of unsigned 64-bit numbers, not strings. */ hash_t hash_fp(uint64_t *vec, int len) { Hash hasher; Accumulator accumulator; for (int i = 0; i < len; ++i) { accumulator.update( hasher(reinterpret_cast<char*>(vec+i), sizeof(uint64_t), 0)); } return accumulator.result(); } /* As above, but operate on a vector of signed 64-bit integers. For * some language bindings, casting and function overloading can be * difficult to use, which is why it's given a new name */ hash_t hash_fps(int64_t *vec, int len) { return hash_fp(reinterpret_cast<uint64_t*>(vec), len); } template <typename Tokenizer> hash_t hash_tokenizer(const char* string, const Tokenizer& tokenizer) { Hash hasher; Accumulator accumulator; StringToken token; for (tokenizer(string, token) ; token.length != 0 ; tokenizer(token.start + token.length, token)) { accumulator.update(hasher(token.start, token.length, 0)); } return accumulator.result(); } }; } #endif <commit_msg>Improve simhash performance<commit_after>#ifndef SIMHASH_HASH_H #define SIMHASH_HASH_H /* Simply holds references to all of our hash functions */ #include "hashes/jenkins.h" #include "hashes/murmur.h" #include "hashes/fnv.h" /* Include a reference to the tokenizer to use */ #include "tokenizers/strspn.h" /* For hash_t */ #include "common.h" #include "cyclic.hpp" #include <vector> namespace Simhash { /** * Compute a similarity hash for the provided string using a rolling hash * function and a provided hash window * * @param tokens - An NULL-terminated array of character pointers to the * nul-terminated tokens comprising the text. * * @return hash representative of the content of the text */ template <typename Hash=jenkins> class Simhash { private: class Accumulator { private: static const size_t BITS = sizeof(hash_t) * 8; size_t window; Cyclic<hash_t> cyclic; std::vector<size_t> v; size_t hash_count; public: Accumulator() : window(3), cyclic(window), v(BITS, 0), hash_count(0) {} void update(hash_t hash) { hash = cyclic.push(hash); ++hash_count; for (size_t j = 0; j < BITS; ++j) { v[j] += hash & 1; hash >>= 1; } } /* With counts appropriately tallied, create a 1 bit for each of * the counts that's over threshold. That result is the hash. */ hash_t result() { size_t threshold = hash_count / 2; hash_t hash(0); for (size_t j = 0; j < BITS; ++j) { if (v[j] > threshold) { hash |= (static_cast<hash_t>(1) << j); } } return hash; } }; public: typedef Hash hash_type; /* Alias of operator() * * Some languages have difficulty making use of operator(), and so this * it made available for those languages */ inline hash_t hash(char **tokens) { return operator()(tokens); } /* Return a simhash value using a moving window */ hash_t operator()(char **tokens) { Hash hasher; Accumulator accumulator; for (char **tp = tokens; *tp != NULL; ++tp) { size_t len = strlen(*tp); if (len > 0) { accumulator.update(hasher(*tp, len, 0)); } } return accumulator.result(); } /* As above, but operate on a vector of unsigned 64-bit numbers, not strings. */ hash_t hash_fp(uint64_t *vec, int len) { Hash hasher; Accumulator accumulator; for (int i = 0; i < len; ++i) { accumulator.update( hasher(reinterpret_cast<char*>(vec+i), sizeof(uint64_t), 0)); } return accumulator.result(); } /* As above, but operate on a vector of signed 64-bit integers. For * some language bindings, casting and function overloading can be * difficult to use, which is why it's given a new name */ hash_t hash_fps(int64_t *vec, int len) { return hash_fp(reinterpret_cast<uint64_t*>(vec), len); } template <typename Tokenizer> hash_t hash_tokenizer(const char* string, const Tokenizer& tokenizer) { Hash hasher; Accumulator accumulator; StringToken token; for (tokenizer(string, token) ; token.length != 0 ; tokenizer(token.start + token.length, token)) { accumulator.update(hasher(token.start, token.length, 0)); } return accumulator.result(); } }; } #endif <|endoftext|>
<commit_before> //@HEADER // *************************************************** // // HPCG: High Performance Conjugate Gradient Benchmark // // Contact: // Michael A. Heroux ( maherou@sandia.gov) // Jack Dongarra (dongarra@eecs.utk.edu) // Piotr Luszczek (luszczek@eecs.utk.edu) // // *************************************************** //@HEADER #ifndef HPCG_NO_MPI #include <mpi.h> #endif #ifndef HPCG_NO_OPENMP #include <omp.h> #endif #ifdef _WIN32 const char* NULLDEVICE="nul"; #else const char* NULLDEVICE="/dev/null"; #endif #include <ctime> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include "hpcg.hpp" #include "ReadHpcgDat.hpp" std::ofstream HPCG_fout; //!< output file stream for logging activities during HPCG run static int startswith(const char * s, const char * prefix) { size_t n = strlen( prefix ); if (strncmp( s, prefix, n )) return 0; return 1; } /*! Initializes an HPCG run by obtaining problem parameters (from a file or command line) and then broadcasts them to all nodes. It also initializes login I/O streams that are used throughout the HPCG run. Only MPI rank 0 performs I/O operations. The function assumes that MPI has already been initialized for MPI runs. @param[in] argc_p the pointer to the "argc" parameter passed to the main() function @param[in] argv_p the pointer to the "argv" parameter passed to the main() function @param[out] params the reference to the data structures that is filled the basic parameters of the run @return returns 0 upon success and non-zero otherwise @see HPCG_Finalize */ int HPCG_Init(int * argc_p, char ** *argv_p, HPCG_Params & params) { int argc = *argc_p; char ** argv = *argv_p; char fname[80]; int i, j, *iparams; char cparams[][6] = {"--nx=", "--ny=", "--nz=", "--rt=", "--pz=", "--zl=", "--zu="}; time_t rawtime; tm * ptm; const int nparams = (sizeof cparams) / (sizeof cparams[0]); bool broadcastParams = false; // Make true if parameters read from file. iparams = (int *)malloc(sizeof(int) * nparams); // Initialize iparams for (i = 0; i < nparams; ++i) iparams[i] = 0; /* for sequential and some MPI implementations it's OK to read first three args */ for (i = 0; i < nparams; ++i) if (argc <= i+1 || sscanf(argv[i+1], "%d", iparams+i) != 1 || iparams[i] < 10) iparams[i] = 0; /* for some MPI environments, command line arguments may get complicated so we need a prefix */ for (i = 1; i <= argc && argv[i]; ++i) for (j = 0; j < nparams; ++j) if (startswith(argv[i], cparams[j])) if (sscanf(argv[i]+strlen(cparams[j]), "%d", iparams+j) != 1 || iparams[j] < 10) iparams[j] = 0; // Check if --rt was specified on the command line int * rt = iparams+3; // Assume runtime was not specified and will be read from the hpcg.dat file if (! iparams[3]) rt = 0; // If --rt was specified, we already have the runtime, so don't read it from file if (! iparams[0] && ! iparams[1] && ! iparams[2]) { /* no geometry arguments on the command line */ ReadHpcgDat(iparams, rt); broadcastParams = true; } // Check for small or unspecified nx, ny, nz values // If any dimension is less than 16, make it the max over the other two dimensions, or 16, whichever is largest for (i = 0; i < 3; ++i) { if (iparams[i] < 16) for (j = 1; j <= 2; ++j) if (iparams[(i+j)%3] > iparams[i]) iparams[i] = iparams[(i+j)%3]; if (iparams[i] < 16) iparams[i] = 16; } // Broadcast values of iparams to all MPI processes #ifndef HPCG_NO_MPI if (broadcastParams) { MPI_Bcast( iparams, nparams, MPI_INT, 0, MPI_COMM_WORLD ); } #endif params.nx = iparams[0]; params.ny = iparams[1]; params.nz = iparams[2]; params.runningTime = iparams[3]; params.pz = iparams[4]; params.zl = iparams[5]; params.zu = iparams[6]; #ifndef HPCG_NO_MPI MPI_Comm_rank( MPI_COMM_WORLD, &params.comm_rank ); MPI_Comm_size( MPI_COMM_WORLD, &params.comm_size ); #else params.comm_rank = 0; params.comm_size = 1; #endif #ifdef HPCG_NO_OPENMP params.numThreads = 1; #else #pragma omp parallel params.numThreads = omp_get_num_threads(); #endif time ( &rawtime ); ptm = localtime(&rawtime); sprintf( fname, "hpcg_log_%04d.%02d.%02d.%02d.%02d.%02d.txt", 1900 + ptm->tm_year, ptm->tm_mon+1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec ); if (0 == params.comm_rank) { HPCG_fout.open(fname); } else { #if defined(HPCG_DEBUG) || defined(HPCG_DETAILED_DEBUG) char local[15]; sprintf( local, "%d_", params.comm_rank ); sprintf( fname, "hpcg_log_%s%04.d%02d.%02d.%02d.%02d.%02d.txt", local, 1900 + ptm->tm_year, ptm->tm_mon+1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec ); HPCG_fout.open(fname); #else HPCG_fout.open(NULLDEVICE); #endif } free( iparams ); return 0; } <commit_msg>Fix logic error that always set pz=0<commit_after> //@HEADER // *************************************************** // // HPCG: High Performance Conjugate Gradient Benchmark // // Contact: // Michael A. Heroux ( maherou@sandia.gov) // Jack Dongarra (dongarra@eecs.utk.edu) // Piotr Luszczek (luszczek@eecs.utk.edu) // // *************************************************** //@HEADER #ifndef HPCG_NO_MPI #include <mpi.h> #endif #ifndef HPCG_NO_OPENMP #include <omp.h> #endif #ifdef _WIN32 const char* NULLDEVICE="nul"; #else const char* NULLDEVICE="/dev/null"; #endif #include <ctime> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include "hpcg.hpp" #include "ReadHpcgDat.hpp" std::ofstream HPCG_fout; //!< output file stream for logging activities during HPCG run static int startswith(const char * s, const char * prefix) { size_t n = strlen( prefix ); if (strncmp( s, prefix, n )) return 0; return 1; } /*! Initializes an HPCG run by obtaining problem parameters (from a file or command line) and then broadcasts them to all nodes. It also initializes login I/O streams that are used throughout the HPCG run. Only MPI rank 0 performs I/O operations. The function assumes that MPI has already been initialized for MPI runs. @param[in] argc_p the pointer to the "argc" parameter passed to the main() function @param[in] argv_p the pointer to the "argv" parameter passed to the main() function @param[out] params the reference to the data structures that is filled the basic parameters of the run @return returns 0 upon success and non-zero otherwise @see HPCG_Finalize */ int HPCG_Init(int * argc_p, char ** *argv_p, HPCG_Params & params) { int argc = *argc_p; char ** argv = *argv_p; char fname[80]; int i, j, *iparams; char cparams[][6] = {"--nx=", "--ny=", "--nz=", "--rt=", "--pz=", "--zl=", "--zu="}; time_t rawtime; tm * ptm; const int nparams = (sizeof cparams) / (sizeof cparams[0]); bool broadcastParams = false; // Make true if parameters read from file. iparams = (int *)malloc(sizeof(int) * nparams); // Initialize iparams for (i = 0; i < nparams; ++i) iparams[i] = 0; /* for sequential and some MPI implementations it's OK to read first three args */ for (i = 0; i < nparams; ++i) if (argc <= i+1 || sscanf(argv[i+1], "%d", iparams+i) != 1 || iparams[i] < 10) iparams[i] = 0; /* for some MPI environments, command line arguments may get complicated so we need a prefix */ for (i = 1; i <= argc && argv[i]; ++i) for (j = 0; j < nparams; ++j) if (startswith(argv[i], cparams[j])) if (sscanf(argv[i]+strlen(cparams[j]), "%d", iparams+j) != 1 /*|| iparams[j] < 10*/) iparams[j] = 0; // Check if --rt was specified on the command line int * rt = iparams+3; // Assume runtime was not specified and will be read from the hpcg.dat file if (! iparams[3]) rt = 0; // If --rt was specified, we already have the runtime, so don't read it from file if (! iparams[0] && ! iparams[1] && ! iparams[2]) { /* no geometry arguments on the command line */ ReadHpcgDat(iparams, rt); broadcastParams = true; } // Check for small or unspecified nx, ny, nz values // If any dimension is less than 16, make it the max over the other two dimensions, or 16, whichever is largest for (i = 0; i < 3; ++i) { if (iparams[i] < 16) for (j = 1; j <= 2; ++j) if (iparams[(i+j)%3] > iparams[i]) iparams[i] = iparams[(i+j)%3]; if (iparams[i] < 16) iparams[i] = 16; } // Broadcast values of iparams to all MPI processes #ifndef HPCG_NO_MPI if (broadcastParams) { MPI_Bcast( iparams, nparams, MPI_INT, 0, MPI_COMM_WORLD ); } #endif params.nx = iparams[0]; params.ny = iparams[1]; params.nz = iparams[2]; params.runningTime = iparams[3]; params.pz = iparams[4]; params.zl = iparams[5]; params.zu = iparams[6]; #ifndef HPCG_NO_MPI MPI_Comm_rank( MPI_COMM_WORLD, &params.comm_rank ); MPI_Comm_size( MPI_COMM_WORLD, &params.comm_size ); #else params.comm_rank = 0; params.comm_size = 1; #endif #ifdef HPCG_NO_OPENMP params.numThreads = 1; #else #pragma omp parallel params.numThreads = omp_get_num_threads(); #endif // for (i = 0; i < nparams; ++i) std::cout << "rank = "<< params.comm_rank << " iparam["<<i<<"] = " << iparams[i] << "\n"; time ( &rawtime ); ptm = localtime(&rawtime); sprintf( fname, "hpcg_log_%04d.%02d.%02d.%02d.%02d.%02d.txt", 1900 + ptm->tm_year, ptm->tm_mon+1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec ); if (0 == params.comm_rank) { HPCG_fout.open(fname); } else { #if defined(HPCG_DEBUG) || defined(HPCG_DETAILED_DEBUG) char local[15]; sprintf( local, "%d_", params.comm_rank ); sprintf( fname, "hpcg_log_%s%04.d%02d.%02d.%02d.%02d.%02d.txt", local, 1900 + ptm->tm_year, ptm->tm_mon+1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec ); HPCG_fout.open(fname); #else HPCG_fout.open(NULLDEVICE); #endif } free( iparams ); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2014 Kamil Michalak <kmichalak8@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "inc/json.hpp" <commit_msg>Remove json.cpp file<commit_after><|endoftext|>
<commit_before>#include "turnmark.h" #define ANALOG_HIGH 460 #define ANALOG_LOW 10 Turnmark::Turnmark(int pin, void (*callback)(void*, CarriageType), void* context) { this->pin = pin; this->callback = callback; this->callbackContext = context; atTurnmark = false; for (int i=0; i<3; i++) lastState[i] = INPUT_NEUTRAL; } InputState Turnmark::analogToState(int value) { if (value >= ANALOG_HIGH) return INPUT_HIGH; else if (value >= ANALOG_LOW) return INPUT_NEUTRAL; else return INPUT_LOW; } void Turnmark::onTurnmark() { atTurnmark = true; callback(callbackContext, lastCarriageType); } void Turnmark::pushState(InputState state) { lastState[2] = lastState[1]; lastState[1] = lastState[0]; lastState[0] = state; } CarriageType Turnmark::carriageType() { return lastCarriageType; } boolean Turnmark::isAtMark() { return atTurnmark; } int Turnmark::countStates(InputState state) { int count = 0; for (int i=0; i<3; i++) { if (lastState[i] == state) count++; } return count; } void Turnmark::update() { atTurnmark = false; int analog = analogRead(pin); InputState state = analogToState(analog); if (state == INPUT_NEUTRAL && lastState[0] != INPUT_NEUTRAL) { int highCount = countStates(INPUT_HIGH); int lowCount = countStates(INPUT_LOW); if (highCount > 0 && lowCount > 0) { lastCarriageType = G_CARRIAGE; onTurnmark(); } else if (highCount > 0) { lastCarriageType = K_CARRIAGE; onTurnmark(); } else if (lowCount > 0) { lastCarriageType = L_CARRIAGE; onTurnmark(); } } pushState(state); } <commit_msg>Reset Neutral after detection.<commit_after>#include "turnmark.h" #define ANALOG_HIGH 460 #define ANALOG_LOW 50 Turnmark::Turnmark(int pin, void (*callback)(void*, CarriageType), void* context) { this->pin = pin; this->callback = callback; this->callbackContext = context; atTurnmark = false; for (int i=0; i<3; i++) lastState[i] = INPUT_NEUTRAL; } InputState Turnmark::analogToState(int value) { if (value >= ANALOG_HIGH) return INPUT_HIGH; else if (value >= ANALOG_LOW) return INPUT_NEUTRAL; else return INPUT_LOW; } void Turnmark::onTurnmark() { atTurnmark = true; for (int i=0; i<3; i++) lastState[i] = INPUT_NEUTRAL; callback(callbackContext, lastCarriageType); } void Turnmark::pushState(InputState state) { lastState[2] = lastState[1]; lastState[1] = lastState[0]; lastState[0] = state; } CarriageType Turnmark::carriageType() { return lastCarriageType; } boolean Turnmark::isAtMark() { return atTurnmark; } int Turnmark::countStates(InputState state) { int count = 0; for (int i=0; i<3; i++) { if (lastState[i] == state) count++; } return count; } void Turnmark::update() { atTurnmark = false; int analog = analogRead(pin); InputState state = analogToState(analog); if (state == INPUT_NEUTRAL && lastState[0] != INPUT_NEUTRAL) { int highCount = countStates(INPUT_HIGH); int lowCount = countStates(INPUT_LOW); if (highCount > 0 && lowCount > 0) { lastCarriageType = G_CARRIAGE; onTurnmark(); } else if (highCount > 0) { lastCarriageType = K_CARRIAGE; onTurnmark(); } else if (lowCount > 0) { lastCarriageType = L_CARRIAGE; onTurnmark(); } } pushState(state); } <|endoftext|>
<commit_before>#include <sys/types.h> #include <dirent.h> #include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <regex> #include <vector> #include <string> #include "list.h" #include "bpftrace.h" namespace bpftrace { const std::string kprobe_path = "/sys/kernel/debug/tracing/available_filter_functions"; const std::string tp_path = "/sys/kernel/debug/tracing/events"; std::string replace_all(const std::string &str, const std::string &from, const std::string &to) { std::string result(str); std::string::size_type index = 0, from_len = from.size(), to_len = to.size(); while ((index = result.find(from, index)) != std::string::npos) { result.replace(index, from_len, to); index += to_len; } return result; } bool search_probe(const std::string &probe, const std::string& search) { try { std::string glob = "*"; std::string regex = ".*"; std::string s = replace_all(search,glob,regex); glob = "?"; regex = "."; s = replace_all(s,glob,regex); s = "^" + s + "$"; std::regex re(s, std::regex::icase | std::regex::grep | std::regex::nosubs); if (std::regex_search(probe, re)) return false; else return true; } catch(std::regex_error& e) { return true; } } void list_dir(const std::string path, std::vector<std::string> &files) { // yes, I know about std::filesystem::directory_iterator, but no, it wasn't available DIR *dp; struct dirent *dep; if ((dp = opendir(path.c_str())) == NULL) return; while ((dep = readdir(dp)) != NULL) files.push_back(std::string(dep->d_name)); closedir(dp); } void list_probes_from_list(const std::vector<ProbeListItem> &probes_list, const std::string &probetype, const std::string &search) { for (auto &probeListItem : probes_list) { if (!search.empty()) { if (search_probe(probeListItem.path, search) && search_probe(probeListItem.alias, search)) continue; } std::cout << probetype << ":" << probeListItem.path << ":" << std::endl; } } void list_probes(const std::string &search) { unsigned int i, j; std::string line, probe; // software list_probes_from_list(SW_PROBE_LIST, "software", search); // hardware list_probes_from_list(HW_PROBE_LIST, "hardware", search); // tracepoints std::vector<std::string> cats = std::vector<std::string>(); list_dir(tp_path, cats); for (i = 0; i < cats.size(); i++) { if (cats[i] == "." || cats[i] == ".." || cats[i] == "enable" || cats[i] == "filter") continue; std::vector<std::string> events = std::vector<std::string>(); list_dir(tp_path + "/" + cats[i], events); for (j = 0; j < events.size(); j++) { if (events[j] == "." || events[j] == ".." || events[j] == "enable" || events[j] == "filter") continue; probe = "tracepoint:" + cats[i] + ":" + events[j]; if (!search.empty()) { if (search_probe(probe, search)) continue; } std::cout << probe << std::endl; } } // kprobes std::ifstream file(kprobe_path); if (file.fail()) { std::cerr << strerror(errno) << ": " << kprobe_path << std::endl; return; } size_t loc; while (std::getline(file, line)) { loc = line.find_first_of(" "); if (loc == std::string::npos) probe = "kprobe:" + line; else probe = "kprobe:" + line.substr(0, loc); if (!search.empty()) { if (search_probe(probe, search)) continue; } std::cout << probe << std::endl; } } void list_probes() { const std::string search = ""; list_probes(search); } } // namespace bpftrace <commit_msg>Probe list optimizations and improvements<commit_after>#include <sys/types.h> #include <dirent.h> #include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <regex> #include <vector> #include <string> #include "list.h" #include "bpftrace.h" namespace bpftrace { const std::string kprobe_path = "/sys/kernel/debug/tracing/available_filter_functions"; const std::string tp_path = "/sys/kernel/debug/tracing/events"; std::string replace_all(const std::string &str, const std::string &from, const std::string &to) { std::string result(str); std::string::size_type index = 0, from_len = from.size(), to_len = to.size(); while ((index = result.find(from, index)) != std::string::npos) { result.replace(index, from_len, to); index += to_len; } return result; } inline bool search_probe(const std::string &probe, const std::regex& re) { try { if (std::regex_search(probe, re)) return false; else return true; } catch(std::regex_error& e) { return true; } } void list_dir(const std::string path, std::vector<std::string> &files) { // yes, I know about std::filesystem::directory_iterator, but no, it wasn't available DIR *dp; struct dirent *dep; if ((dp = opendir(path.c_str())) == NULL) return; while ((dep = readdir(dp)) != NULL) files.push_back(std::string(dep->d_name)); closedir(dp); } void list_probes_from_list(const std::vector<ProbeListItem> &probes_list, const std::string &probetype, const std::string &search, const std::regex& re) { std::string probe; for (auto &probeListItem : probes_list) { probe = probetype + ":" + probeListItem.path + ":"; if (!search.empty()) { if (search_probe(probe, re)) continue; } std::cout << probe << std::endl; } } void list_probes(const std::string &search) { unsigned int i, j; std::string line, probe; std::string glob = "*"; std::string regex = ".*"; std::string s = replace_all(search,glob,regex); glob = "?"; regex = "."; s = replace_all(s,glob,regex); s = "^" + s + "$"; std::regex re(s, std::regex::icase | std::regex::grep | std::regex::nosubs | std::regex::optimize); // software list_probes_from_list(SW_PROBE_LIST, "software", search, re); // hardware list_probes_from_list(HW_PROBE_LIST, "hardware", search, re); // tracepoints std::vector<std::string> cats = std::vector<std::string>(); list_dir(tp_path, cats); for (i = 0; i < cats.size(); i++) { if (cats[i] == "." || cats[i] == ".." || cats[i] == "enable" || cats[i] == "filter") continue; std::vector<std::string> events = std::vector<std::string>(); list_dir(tp_path + "/" + cats[i], events); for (j = 0; j < events.size(); j++) { if (events[j] == "." || events[j] == ".." || events[j] == "enable" || events[j] == "filter") continue; probe = "tracepoint:" + cats[i] + ":" + events[j]; if (!search.empty()) { if (search_probe(probe, re)) continue; } std::cout << probe << std::endl; } } // kprobes std::ifstream file(kprobe_path); if (file.fail()) { std::cerr << strerror(errno) << ": " << kprobe_path << std::endl; return; } size_t loc; while (std::getline(file, line)) { loc = line.find_first_of(" "); if (loc == std::string::npos) probe = "kprobe:" + line; else probe = "kprobe:" + line.substr(0, loc); if (!search.empty()) { if (search_probe(probe, re)) continue; } std::cout << probe << std::endl; } } void list_probes() { const std::string search = ""; list_probes(search); } } // namespace bpftrace <|endoftext|>
<commit_before>/* * Lexer.cc * * Author: Lunatic */ #include "lexer.h" #include "alarm.h" namespace Script { Lexer::~Lexer() { } void Lexer::forward() { if (text[offset++] == '\n') { row++; col = 0; } else { col++; } } void Lexer::skip_space() { while (text[offset] == ' ' || text[offset] == '\t') { forward(); } } bool Lexer::get_name(std::string& name) { bool found = false; if (('a' <= text[offset] && text[offset] <= 'z') || text[offset] == '_') { found = true; do { name += text[offset]; forward(); } while (!finish() && (('a' <= text[offset] && text[offset] <= 'z') || text[offset] == '_' || ('0' <= text[offset] && text[offset] <= '9'))); if (finish()) { error("语法错误"); } } return found; } bool Lexer::get_string(std::string& name) { bool found = false; if (text[offset] == '\"') { found = true; do { name += text[offset]; forward(); } while (!finish() && text[offset] != '\"'); if (finish()) { error("语法错误"); } } return found; } //bool Lexer::get_real(std::string& name) { // bool found = false; // if (get_int(name) && text[offset] == '.') { // name += '.'; // forward(); // if (finish()) { // error("语法错误"); // } // if (get_int(name)) { // found = true; // } // } // return found; //} bool Lexer::get_num(std::string& name, bool& is_int) { bool found = false; is_int = true; if ((found = get_int(name)) && text[offset] == '.') { is_int = false; name += '.'; forward(); if (finish()) { error("语法错误", Position(row, col)); } if (get_int(name)) { found = true; } else error("语法错误", Position(row, col)); } return found; } bool Lexer::get_int(std::string& name) { bool found = false; if ('0' <= text[offset] && text[offset] <= '9') { found = true; do { name += text[offset]; forward(); } while (!finish() && '0' <= text[offset] && text[offset] <= '9'); if (finish()) { error("语法错误", Position(row, col)); } } return found; } Token Lexer::next_token() { std::string name; skip_space(); bool isint; if (get_name(name)) return Token(kName, name, row, col); if (get_string(name)) return Token(kString, name, row, col); if (get_num(name, isint)) return isint ? Token(kInt, name, row, col) : Token(kReal, name, row, col); if (text[offset] == ':') return Token(kString, name, row, col); else error("语法错误", Position(row, col)); return Token(kString, name, row, col); //���ɴ� } } /* namespace Script */ <commit_msg>取消提前结束检查 推迟到上层<commit_after>/* * Lexer.cc * * Author: Lunatic */ #include "lexer.h" #include "alarm.h" namespace Script { Lexer::~Lexer() { } void Lexer::forward() { if (text[offset++] == '\n') { row++; col = 0; } else { col++; } } void Lexer::skip_space() { while (text[offset] == ' ' || text[offset] == '\t') { forward(); } } bool Lexer::get_name(std::string& name) { bool found = false; if (('a' <= text[offset] && text[offset] <= 'z') || text[offset] == '_') { found = true; do { name += text[offset]; forward(); } while (!finish() && (('a' <= text[offset] && text[offset] <= 'z') || text[offset] == '_' || ('0' <= text[offset] && text[offset] <= '9'))); } return found; } bool Lexer::get_string(std::string& name) { bool found = false; if (text[offset] == '\"') { found = true; do { name += text[offset]; forward(); } while (!finish() && text[offset] != '\"'); } return found; } bool Lexer::get_num(std::string& name, bool& is_int) { bool found = false; is_int = true; if ((found = get_int(name)) && text[offset] == '.') { is_int = false; name += '.'; forward(); if (!finish() && get_int(name)) { found = true; } else error("语法错误", Position(row, col)); } return found; } bool Lexer::get_int(std::string& name) { bool found = false; if ('0' <= text[offset] && text[offset] <= '9') { found = true; do { name += text[offset]; forward(); } while (!finish() && '0' <= text[offset] && text[offset] <= '9'); } return found; } // > < = >= <= != bool Lexer::get_cmp(std::string& name) { switch (text[offset]) { case '=': case '!': name += text[offset]; forward(); if (text[offset] != '=') error("语法错误", Position(row, col)); name += text[offset]; break; case '<': case '>': name += text[offset]; if(text[offset + 1] == '=') { forward(); name += text[offset]; } } return !name.empty(); } Token Lexer::next_token() { std::string name; skip_space(); bool isint; if (get_name(name)) return Token(kName, name, row, col); if (get_string(name)) return Token(kString, name, row, col); if (get_num(name, isint)) return isint ? Token(kInt, name, row, col) : Token(kReal, name, row, col); if (get_cmp(name)) return Token(KCmp, name, row, col); if (text[offset] == ':') return Token(kString, name, row, col); else error("语法错误", Position(row, col)); return Token(kString, name, row, col); //���ɴ� } } /* namespace Script */ <|endoftext|>
<commit_before>/** * ClassInfo.cpp * * Implementation for the class info * * @author Emiel Bruijntjes <emiel.bruijntjes@copernica.com> * @copyright 2013 Copernica BV */ #include "includes.h" /** * Set up namespace */ namespace Php { /** * Function that is called to clean up space that is occupied by the object * @param object The object to be deallocated */ static void deallocate_object(void *object TSRMLS_DC) { // allocate memory for the object MixedObject *obj = (MixedObject *)object; // deallocate the cpp object if (obj->cpp) delete obj->cpp; // get rid of the object properties // @todo if we enable the following two lines, segmentation // faults and memory corruption occurs. however, the online // documentation does it like this //zend_hash_destroy(obj->php.properties); //FREE_HASHTABLE(obj->php.properties); // deallocate the entire object efree(obj); } /** * Function that is called to create space for a cloned object * @param object The object to be cloned * @param clone The address that should become the clone */ static void clone_object(void *object, void **clone TSRMLS_DC) { std::cout << "clone_object" << std::endl; // @todo implementation } /** * Function that is called when an instance of the class needs to be created. * This function will create the C++ class, and the PHP object * @param type Pointer to the class */ static zend_object_value create_object(zend_class_entry *type TSRMLS_DC) { // allocate memory for the object MixedObject *object = (MixedObject *)emalloc(sizeof(MixedObject)); // find base object zend_class_entry *base = type; while (base->parent) base = base->parent; // retrieve the classinfo object _ClassInfo *info = (_ClassInfo *)base->info.user.doc_comment; // store the class object->php.ce = type; // the original create_object fills the initial object with the default properties, // we're going to do exactly the same. start with setting up a hashtable for the props ALLOC_HASHTABLE(object->php.properties); // initialize the hash table zend_hash_init(object->php.properties, 0, NULL, ZVAL_PTR_DTOR, 0); // initialize the properties object_properties_init(&(object->php), type); // the thing we're going to return zend_object_value result; // use default object handlers result.handlers = zend_get_std_object_handlers(); // put the object in the storage, and assign a method for deallocating and cloning result.handle = zend_objects_store_put(object, NULL, deallocate_object, clone_object TSRMLS_CC); // finally, construct the cpp object object->cpp = info->construct(); std::cout << "Allocate object" << std::endl; std::cout << object->cpp << " " << object << std::endl; // done return result; } /** * Constructor * @param name */ _ClassInfo::_ClassInfo(const char *name) : _name(name), _entry(NULL) { } /** * Destructor */ _ClassInfo::~_ClassInfo() { } /** * Initialize the class * @param mixed Optional threading ID */ void _ClassInfo::initialize(TSRMLS_DC) { // the class entry zend_class_entry entry; // initialize the class entry INIT_CLASS_ENTRY_EX(entry, _name.c_str(), _name.size(), methods()); // we need a special constructor entry.create_object = create_object; // register the class _entry = zend_register_internal_class(&entry TSRMLS_CC); // store pointer to the class in the unused doc_comment member _entry->info.user.doc_comment = (const char *)this; // initialize the entry initialize(_entry); } /** * End of namespace */ } <commit_msg>Removed debug messages from classinfo.cpp<commit_after>/** * ClassInfo.cpp * * Implementation for the class info * * @author Emiel Bruijntjes <emiel.bruijntjes@copernica.com> * @copyright 2013 Copernica BV */ #include "includes.h" /** * Set up namespace */ namespace Php { /** * Function that is called to clean up space that is occupied by the object * @param object The object to be deallocated */ static void deallocate_object(void *object TSRMLS_DC) { // allocate memory for the object MixedObject *obj = (MixedObject *)object; // deallocate the cpp object if (obj->cpp) delete obj->cpp; // get rid of the object properties // @todo if we enable the following two lines, segmentation // faults and memory corruption occurs. however, the online // documentation does it like this //zend_hash_destroy(obj->php.properties); //FREE_HASHTABLE(obj->php.properties); // deallocate the entire object efree(obj); } /** * Function that is called to create space for a cloned object * @param object The object to be cloned * @param clone The address that should become the clone */ static void clone_object(void *object, void **clone TSRMLS_DC) { std::cout << "clone_object" << std::endl; // @todo implementation } /** * Function that is called when an instance of the class needs to be created. * This function will create the C++ class, and the PHP object * @param type Pointer to the class */ static zend_object_value create_object(zend_class_entry *type TSRMLS_DC) { // allocate memory for the object MixedObject *object = (MixedObject *)emalloc(sizeof(MixedObject)); // find base object zend_class_entry *base = type; while (base->parent) base = base->parent; // retrieve the classinfo object _ClassInfo *info = (_ClassInfo *)base->info.user.doc_comment; // store the class object->php.ce = type; // the original create_object fills the initial object with the default properties, // we're going to do exactly the same. start with setting up a hashtable for the props ALLOC_HASHTABLE(object->php.properties); // initialize the hash table zend_hash_init(object->php.properties, 0, NULL, ZVAL_PTR_DTOR, 0); // initialize the properties object_properties_init(&(object->php), type); // the thing we're going to return zend_object_value result; // use default object handlers result.handlers = zend_get_std_object_handlers(); // put the object in the storage, and assign a method for deallocating and cloning result.handle = zend_objects_store_put(object, NULL, deallocate_object, clone_object TSRMLS_CC); // finally, construct the cpp object object->cpp = info->construct(); //std::cout << "Allocate object" << std::endl; //std::cout << object->cpp << " " << object << std::endl; // done return result; } /** * Constructor * @param name */ _ClassInfo::_ClassInfo(const char *name) : _name(name), _entry(NULL) { } /** * Destructor */ _ClassInfo::~_ClassInfo() { } /** * Initialize the class * @param mixed Optional threading ID */ void _ClassInfo::initialize(TSRMLS_DC) { // the class entry zend_class_entry entry; // initialize the class entry INIT_CLASS_ENTRY_EX(entry, _name.c_str(), _name.size(), methods()); // we need a special constructor entry.create_object = create_object; // register the class _entry = zend_register_internal_class(&entry TSRMLS_CC); // store pointer to the class in the unused doc_comment member _entry->info.user.doc_comment = (const char *)this; // initialize the entry initialize(_entry); } /** * End of namespace */ } <|endoftext|>
<commit_before>//===-- DynamicLibrary.cpp - Runtime link/load libraries --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header file implements the operating system DynamicLibrary concept. // // FIXME: This file leaks the ExplicitSymbols and OpenedHandles vector, and is // not thread safe! // //===----------------------------------------------------------------------===// #include "llvm/System/DynamicLibrary.h" #include "llvm/System/Mutex.h" #include "llvm/Config/config.h" #include <cstdio> #include <cstring> #include <map> #include <vector> // Collection of symbol name/value pairs to be searched prior to any libraries. static std::map<std::string, void*> *ExplicitSymbols = 0; namespace { struct ExplicitSymbolsDeleter { ~ExplicitSymbolsDeleter() { if (ExplicitSymbols) delete ExplicitSymbols; } }; } static ExplicitSymbolsDeleter Dummy; void llvm::sys::DynamicLibrary::AddSymbol(const char* symbolName, void *symbolValue) { if (ExplicitSymbols == 0) ExplicitSymbols = new std::map<std::string, void*>(); (*ExplicitSymbols)[symbolName] = symbolValue; } #ifdef LLVM_ON_WIN32 #include "Win32/DynamicLibrary.inc" #else #if HAVE_DLFCN_H #include <dlfcn.h> using namespace llvm; using namespace llvm::sys; //===----------------------------------------------------------------------===// //=== WARNING: Implementation here must contain only TRULY operating system //=== independent code. //===----------------------------------------------------------------------===// static SmartMutex<true> HandlesMutex; static std::vector<void *> *OpenedHandles = 0; bool DynamicLibrary::LoadLibraryPermanently(const char *Filename, std::string *ErrMsg) { void *H = dlopen(Filename, RTLD_LAZY|RTLD_GLOBAL); if (H == 0) { if (ErrMsg) *ErrMsg = dlerror(); return true; } #ifdef __CYGWIN__ // Cygwin searches symbols only in the main // with the handle of dlopen(NULL, RTLD_GLOBAL). if (Filename == NULL) H = RTLD_DEFAULT; #endif SmartScopedLock<true> Lock(HandlesMutex); if (OpenedHandles == 0) OpenedHandles = new std::vector<void *>(); OpenedHandles->push_back(H); return false; } #else using namespace llvm; using namespace llvm::sys; bool DynamicLibrary::LoadLibraryPermanently(const char *Filename, std::string *ErrMsg) { if (ErrMsg) *ErrMsg = "dlopen() not supported on this platform"; return true; } #endif namespace llvm { void *SearchForAddressOfSpecialSymbol(const char* symbolName); } void* DynamicLibrary::SearchForAddressOfSymbol(const char* symbolName) { // First check symbols added via AddSymbol(). if (ExplicitSymbols) { std::map<std::string, void *>::iterator I = ExplicitSymbols->find(symbolName); std::map<std::string, void *>::iterator E = ExplicitSymbols->end(); if (I != E) return I->second; } #if HAVE_DLFCN_H // Now search the libraries. SmartScopedLock<true> Lock(HandlesMutex); if (OpenedHandles) { for (std::vector<void *>::iterator I = OpenedHandles->begin(), E = OpenedHandles->end(); I != E; ++I) { //lt_ptr ptr = lt_dlsym(*I, symbolName); void *ptr = dlsym(*I, symbolName); if (ptr) { return ptr; } } } #endif if (void *Result = llvm::SearchForAddressOfSpecialSymbol(symbolName)) return Result; // This macro returns the address of a well-known, explicit symbol #define EXPLICIT_SYMBOL(SYM) \ if (!strcmp(symbolName, #SYM)) return &SYM // On linux we have a weird situation. The stderr/out/in symbols are both // macros and global variables because of standards requirements. So, we // boldly use the EXPLICIT_SYMBOL macro without checking for a #define first. #if defined(__linux__) { EXPLICIT_SYMBOL(stderr); EXPLICIT_SYMBOL(stdout); EXPLICIT_SYMBOL(stdin); } #else // For everything else, we want to check to make sure the symbol isn't defined // as a macro before using EXPLICIT_SYMBOL. { #ifndef stdin EXPLICIT_SYMBOL(stdin); #endif #ifndef stdout EXPLICIT_SYMBOL(stdout); #endif #ifndef stderr EXPLICIT_SYMBOL(stderr); #endif } #endif #undef EXPLICIT_SYMBOL return 0; } #endif // LLVM_ON_WIN32 <commit_msg>Use thread-safe statics to avoid a static constructor here. This isn't thread-safe on MSVC, but we don't support threaded LLVM there anyways.<commit_after>//===-- DynamicLibrary.cpp - Runtime link/load libraries --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header file implements the operating system DynamicLibrary concept. // // FIXME: This file leaks the ExplicitSymbols and OpenedHandles vector, and is // not thread safe! // //===----------------------------------------------------------------------===// #include "llvm/System/DynamicLibrary.h" #include "llvm/System/Mutex.h" #include "llvm/Config/config.h" #include <cstdio> #include <cstring> #include <map> #include <vector> // Collection of symbol name/value pairs to be searched prior to any libraries. static std::map<std::string, void*> *ExplicitSymbols = 0; namespace { struct ExplicitSymbolsDeleter { ~ExplicitSymbolsDeleter() { if (ExplicitSymbols) delete ExplicitSymbols; } }; } static ExplicitSymbolsDeleter Dummy; void llvm::sys::DynamicLibrary::AddSymbol(const char* symbolName, void *symbolValue) { if (ExplicitSymbols == 0) ExplicitSymbols = new std::map<std::string, void*>(); (*ExplicitSymbols)[symbolName] = symbolValue; } #ifdef LLVM_ON_WIN32 #include "Win32/DynamicLibrary.inc" #else #if HAVE_DLFCN_H #include <dlfcn.h> using namespace llvm; using namespace llvm::sys; //===----------------------------------------------------------------------===// //=== WARNING: Implementation here must contain only TRULY operating system //=== independent code. //===----------------------------------------------------------------------===// static SmartMutex<true>* HandlesMutex; static std::vector<void *> *OpenedHandles = 0; static bool InitializeMutex() { HandlesMutex = new SmartMutex<true>; return HandlesMutex != 0; } static bool EnsureMutexInitialized() { static bool result = InitializeMutex(); return result; } bool DynamicLibrary::LoadLibraryPermanently(const char *Filename, std::string *ErrMsg) { void *H = dlopen(Filename, RTLD_LAZY|RTLD_GLOBAL); if (H == 0) { if (ErrMsg) *ErrMsg = dlerror(); return true; } #ifdef __CYGWIN__ // Cygwin searches symbols only in the main // with the handle of dlopen(NULL, RTLD_GLOBAL). if (Filename == NULL) H = RTLD_DEFAULT; #endif EnsureMutexInitialized(); SmartScopedLock<true> Lock(*HandlesMutex); if (OpenedHandles == 0) OpenedHandles = new std::vector<void *>(); OpenedHandles->push_back(H); return false; } #else using namespace llvm; using namespace llvm::sys; bool DynamicLibrary::LoadLibraryPermanently(const char *Filename, std::string *ErrMsg) { if (ErrMsg) *ErrMsg = "dlopen() not supported on this platform"; return true; } #endif namespace llvm { void *SearchForAddressOfSpecialSymbol(const char* symbolName); } void* DynamicLibrary::SearchForAddressOfSymbol(const char* symbolName) { // First check symbols added via AddSymbol(). if (ExplicitSymbols) { std::map<std::string, void *>::iterator I = ExplicitSymbols->find(symbolName); std::map<std::string, void *>::iterator E = ExplicitSymbols->end(); if (I != E) return I->second; } #if HAVE_DLFCN_H // Now search the libraries. EnsureMutexInitialized(); SmartScopedLock<true> Lock(*HandlesMutex); if (OpenedHandles) { for (std::vector<void *>::iterator I = OpenedHandles->begin(), E = OpenedHandles->end(); I != E; ++I) { //lt_ptr ptr = lt_dlsym(*I, symbolName); void *ptr = dlsym(*I, symbolName); if (ptr) { return ptr; } } } #endif if (void *Result = llvm::SearchForAddressOfSpecialSymbol(symbolName)) return Result; // This macro returns the address of a well-known, explicit symbol #define EXPLICIT_SYMBOL(SYM) \ if (!strcmp(symbolName, #SYM)) return &SYM // On linux we have a weird situation. The stderr/out/in symbols are both // macros and global variables because of standards requirements. So, we // boldly use the EXPLICIT_SYMBOL macro without checking for a #define first. #if defined(__linux__) { EXPLICIT_SYMBOL(stderr); EXPLICIT_SYMBOL(stdout); EXPLICIT_SYMBOL(stdin); } #else // For everything else, we want to check to make sure the symbol isn't defined // as a macro before using EXPLICIT_SYMBOL. { #ifndef stdin EXPLICIT_SYMBOL(stdin); #endif #ifndef stdout EXPLICIT_SYMBOL(stdout); #endif #ifndef stderr EXPLICIT_SYMBOL(stderr); #endif } #endif #undef EXPLICIT_SYMBOL return 0; } #endif // LLVM_ON_WIN32 <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/filerepository.h" #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/random.h" #include "fnord-base/thread/eventloop.h" #include "fnord-base/thread/threadpool.h" #include "fnord-base/wallclock.h" #include "fnord-rpc/ServerGroup.h" #include "fnord-rpc/RPC.h" #include "fnord-rpc/RPCClient.h" #include "fnord-base/cli/flagparser.h" #include "fnord-json/json.h" #include "fnord-json/jsonrpc.h" #include "fnord-http/httprouter.h" #include "fnord-http/httpserver.h" #include "fnord-feeds/FeedService.h" #include "fnord-feeds/RemoteFeedFactory.h" #include "fnord-feeds/RemoteFeedReader.h" #include "fnord-base/stats/statsdagent.h" #include "fnord-http/httpconnectionpool.h" #include "fnord-mdb/MDB.h" #include <fnord-fts/fts.h> #include <fnord-fts/fts_common.h> #include "CustomerNamespace.h" #include "logjoin/LogJoin.h" #include "logjoin/LogJoinTarget.h" #include "logjoin/LogJoinUpload.h" #include "DocStore.h" #include "IndexChangeRequest.h" #include "DocIndex.h" #include "ItemRef.h" #include "common.h" #include "schemas.h" using namespace cm; using namespace fnord; std::atomic<bool> cm_logjoin_shutdown; fnord::thread::EventLoop ev; void quit(int n) { cm_logjoin_shutdown = true; } int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); /* shutdown hook */ cm_logjoin_shutdown = false; struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = quit; sigaction(SIGTERM, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGINT, &sa, NULL); fnord::cli::FlagParser flags; flags.defineFlag( "conf", cli::FlagParser::T_STRING, false, NULL, "./conf", "conf directory", "<path>"); flags.defineFlag( "datadir", cli::FlagParser::T_STRING, true, NULL, NULL, "data dir", "<path>"); flags.defineFlag( "index", cli::FlagParser::T_STRING, false, NULL, NULL, "index directory", "<path>"); flags.defineFlag( "publish_to", fnord::cli::FlagParser::T_STRING, true, NULL, NULL, "upload target url", "<addr>"); flags.defineFlag( "statsd_addr", fnord::cli::FlagParser::T_STRING, false, NULL, "127.0.0.1:8192", "Statsd addr", "<addr>"); flags.defineFlag( "batch_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "2048", "batch_size", "<num>"); flags.defineFlag( "buffer_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "8192", "buffer_size", "<num>"); flags.defineFlag( "flush_interval", fnord::cli::FlagParser::T_INTEGER, false, NULL, "5", "flush_interval", "<num>"); flags.defineFlag( "db_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "128", "max sessiondb size", "<MB>"); flags.defineFlag( "no_dryrun", fnord::cli::FlagParser::T_SWITCH, false, NULL, NULL, "no dryrun", "<bool>"); flags.defineFlag( "shard", fnord::cli::FlagParser::T_STRING, false, NULL, NULL, "shard", "<name>"); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); /* schema... */ auto joined_sessions_schema = joinedSessionsSchema(); /* start event loop */ auto evloop_thread = std::thread([] { ev.run(); }); /* set up rpc client */ HTTPRPCClient rpc_client(&ev); http::HTTPConnectionPool http(&ev); /* start stats reporting */ fnord::stats::StatsdAgent statsd_agent( fnord::net::InetAddr::resolve(flags.getString("statsd_addr")), 10 * fnord::kMicrosPerSecond); statsd_agent.start(); /* get logjoin shard */ cm::LogJoinShardMap shard_map; auto shard = shard_map.getShard(flags.getString("shard")); /* set up logjoin */ auto dry_run = !flags.isSet("no_dryrun"); size_t batch_size = flags.getInt("batch_size"); size_t buffer_size = flags.getInt("buffer_size"); size_t flush_interval = flags.getInt("flush_interval"); fnord::logInfo( "cm.logjoin", "Starting cm-logjoin with:\n dry_run=$0\n batch_size=$1\n" \ " buffer_size=$2\n flush_interval=$9\n" " max_dbsize=$4MB\n" \ " shard=$5\n shard_range=[$6, $7)\n shard_modulo=$8", dry_run, batch_size, buffer_size, 0, flags.getInt("db_size"), shard.shard_name, shard.begin, shard.end, cm::LogJoinShard::modulo, flush_interval); fnord::logInfo( "cm.logjoin", "Using session schema:\n$0", joined_sessions_schema.toString()); /* open session db */ auto sessdb = mdb::MDB::open( flags.getString("datadir"), false, 1000000 * flags.getInt("db_size"), shard.shard_name + ".db", shard.shard_name + ".db.lck", false); /* set up input feed reader */ feeds::RemoteFeedReader feed_reader(&rpc_client); feed_reader.setMaxSpread(10 * kMicrosPerSecond); HashMap<String, URI> input_feeds; input_feeds.emplace( "tracker_log.feedserver01.nue01.production.fnrd.net", URI("http://s01.nue01.production.fnrd.net:7001/rpc")); input_feeds.emplace( "tracker_log.feedserver02.nue01.production.fnrd.net", URI("http://s02.nue01.production.fnrd.net:7001/rpc")); /* setup time backfill */ feed_reader.setTimeBackfill([] (const feeds::FeedEntry& entry) -> DateTime { const auto& log_line = entry.data; auto c_end = log_line.find("|"); if (c_end == std::string::npos) return 0; auto t_end = log_line.find("|", c_end + 1); if (t_end == std::string::npos) return 0; auto timestr = log_line.substr(c_end + 1, t_end - c_end - 1); return std::stoul(timestr) * fnord::kMicrosPerSecond; }); /* open index */ RefPtr<DocIndex> index( new DocIndex( flags.getString("index"), "documents-dawanda", true)); /* set up logjoin target */ fnord::fts::Analyzer analyzer(flags.getString("conf")); cm::LogJoinTarget logjoin_target( joined_sessions_schema, &analyzer, index, dry_run); /* set up logjoin upload */ cm::LogJoinUpload logjoin_upload( sessdb, flags.getString("publish_to"), &http); /* setup logjoin */ cm::LogJoin logjoin(shard, dry_run, &logjoin_target); logjoin.exportStats("/cm-logjoin/global"); logjoin.exportStats(StringUtil::format("/cm-logjoin/$0", shard.shard_name)); fnord::stats::Counter<uint64_t> stat_stream_time_low; fnord::stats::Counter<uint64_t> stat_stream_time_high; fnord::stats::Counter<uint64_t> stat_active_sessions; fnord::stats::Counter<uint64_t> stat_dbsize; exportStat( StringUtil::format("/cm-logjoin/$0/stream_time_low", shard.shard_name), &stat_stream_time_low, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/stream_time_high", shard.shard_name), &stat_stream_time_high, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/active_sessions", shard.shard_name), &stat_active_sessions, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/dbsize", shard.shard_name), &stat_dbsize, fnord::stats::ExportMode::EXPORT_VALUE); /* upload pending q */ if (!dry_run) { logjoin_upload.upload(); } /* resume from last offset */ auto txn = sessdb->startTransaction(true); try { logjoin.importTimeoutList(txn.get()); for (const auto& input_feed : input_feeds) { uint64_t offset = 0; auto last_offset = txn->get( StringUtil::format("__logjoin_offset~$0", input_feed.first)); if (!last_offset.isEmpty()) { offset = std::stoul(last_offset.get().toString()); } fnord::logInfo( "cm.logjoin", "Adding source feed:\n feed=$0\n url=$1\n offset: $2", input_feed.first, input_feed.second.toString(), offset); feed_reader.addSourceFeed( input_feed.second, input_feed.first, offset, batch_size, buffer_size); } txn->abort(); } catch (...) { txn->abort(); throw; } fnord::logInfo("cm.logjoin", "Resuming logjoin..."); DateTime last_flush; uint64_t rate_limit_micros = flush_interval * kMicrosPerSecond; for (;;) { auto begin = WallClock::unixMicros(); feed_reader.fillBuffers(); auto txn = sessdb->startTransaction(); int i = 0; for (; i < batch_size; ++i) { auto entry = feed_reader.fetchNextEntry(); if (entry.isEmpty()) { break; } try { logjoin.insertLogline(entry.get().data, txn.get()); } catch (const std::exception& e) { fnord::logError("cm.logjoin", e, "invalid log line"); } } auto watermarks = feed_reader.watermarks(); auto etime = WallClock::now().unixMicros() - last_flush.unixMicros(); if (etime > rate_limit_micros) { last_flush = WallClock::now(); logjoin.flush(txn.get(), watermarks.first); } auto stream_offsets = feed_reader.streamOffsets(); String stream_offsets_str; for (const auto& soff : stream_offsets) { txn->update( StringUtil::format("__logjoin_offset~$0", soff.first), StringUtil::toString(soff.second)); stream_offsets_str += StringUtil::format("\n offset[$0]=$1", soff.first, soff.second); } fnord::logInfo( "cm.logjoin", "LogJoin comitting...\n stream_time=<$0 ... $1>\n" \ " active_sessions=$2\n flushed_sessions=$3$4", watermarks.first, watermarks.second, logjoin.numSessions(), logjoin_target.num_sessions, stream_offsets_str); if (dry_run) { txn->abort(); } else { txn->commit(); try { logjoin_upload.upload(); } catch (const std::exception& e) { fnord::logError("cm.logjoin", e, "upload failed"); } } if (cm_logjoin_shutdown.load()) { break; } stat_stream_time_low.set(watermarks.first.unixMicros()); stat_stream_time_high.set(watermarks.second.unixMicros()); stat_active_sessions.set(logjoin.numSessions()); //stat_dbsize.set(FileUtil::du_c(flags.getString("datadir")); auto rtime = WallClock::unixMicros() - begin; auto rlimit = kMicrosPerSecond / 10; if (i < 2 && rtime < rlimit) { usleep(rlimit - rtime); } } ev.shutdown(); evloop_thread.join(); sessdb->sync(); fnord::logInfo("cm.logjoin", "LogJoin exiting..."); return 0; } <commit_msg>logjoin rate limit...<commit_after>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/filerepository.h" #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/random.h" #include "fnord-base/thread/eventloop.h" #include "fnord-base/thread/threadpool.h" #include "fnord-base/wallclock.h" #include "fnord-rpc/ServerGroup.h" #include "fnord-rpc/RPC.h" #include "fnord-rpc/RPCClient.h" #include "fnord-base/cli/flagparser.h" #include "fnord-json/json.h" #include "fnord-json/jsonrpc.h" #include "fnord-http/httprouter.h" #include "fnord-http/httpserver.h" #include "fnord-feeds/FeedService.h" #include "fnord-feeds/RemoteFeedFactory.h" #include "fnord-feeds/RemoteFeedReader.h" #include "fnord-base/stats/statsdagent.h" #include "fnord-http/httpconnectionpool.h" #include "fnord-mdb/MDB.h" #include <fnord-fts/fts.h> #include <fnord-fts/fts_common.h> #include "CustomerNamespace.h" #include "logjoin/LogJoin.h" #include "logjoin/LogJoinTarget.h" #include "logjoin/LogJoinUpload.h" #include "DocStore.h" #include "IndexChangeRequest.h" #include "DocIndex.h" #include "ItemRef.h" #include "common.h" #include "schemas.h" using namespace cm; using namespace fnord; std::atomic<bool> cm_logjoin_shutdown; fnord::thread::EventLoop ev; void quit(int n) { cm_logjoin_shutdown = true; } int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); /* shutdown hook */ cm_logjoin_shutdown = false; struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = quit; sigaction(SIGTERM, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGINT, &sa, NULL); fnord::cli::FlagParser flags; flags.defineFlag( "conf", cli::FlagParser::T_STRING, false, NULL, "./conf", "conf directory", "<path>"); flags.defineFlag( "datadir", cli::FlagParser::T_STRING, true, NULL, NULL, "data dir", "<path>"); flags.defineFlag( "index", cli::FlagParser::T_STRING, false, NULL, NULL, "index directory", "<path>"); flags.defineFlag( "publish_to", fnord::cli::FlagParser::T_STRING, true, NULL, NULL, "upload target url", "<addr>"); flags.defineFlag( "statsd_addr", fnord::cli::FlagParser::T_STRING, false, NULL, "127.0.0.1:8192", "Statsd addr", "<addr>"); flags.defineFlag( "batch_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "2048", "batch_size", "<num>"); flags.defineFlag( "buffer_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "8192", "buffer_size", "<num>"); flags.defineFlag( "flush_interval", fnord::cli::FlagParser::T_INTEGER, false, NULL, "5", "flush_interval", "<num>"); flags.defineFlag( "db_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "128", "max sessiondb size", "<MB>"); flags.defineFlag( "no_dryrun", fnord::cli::FlagParser::T_SWITCH, false, NULL, NULL, "no dryrun", "<bool>"); flags.defineFlag( "shard", fnord::cli::FlagParser::T_STRING, false, NULL, NULL, "shard", "<name>"); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); /* schema... */ auto joined_sessions_schema = joinedSessionsSchema(); /* start event loop */ auto evloop_thread = std::thread([] { ev.run(); }); /* set up rpc client */ HTTPRPCClient rpc_client(&ev); http::HTTPConnectionPool http(&ev); /* start stats reporting */ fnord::stats::StatsdAgent statsd_agent( fnord::net::InetAddr::resolve(flags.getString("statsd_addr")), 10 * fnord::kMicrosPerSecond); statsd_agent.start(); /* get logjoin shard */ cm::LogJoinShardMap shard_map; auto shard = shard_map.getShard(flags.getString("shard")); /* set up logjoin */ auto dry_run = !flags.isSet("no_dryrun"); size_t batch_size = flags.getInt("batch_size"); size_t buffer_size = flags.getInt("buffer_size"); size_t flush_interval = flags.getInt("flush_interval"); fnord::logInfo( "cm.logjoin", "Starting cm-logjoin with:\n dry_run=$0\n batch_size=$1\n" \ " buffer_size=$2\n flush_interval=$9\n" " max_dbsize=$4MB\n" \ " shard=$5\n shard_range=[$6, $7)\n shard_modulo=$8", dry_run, batch_size, buffer_size, 0, flags.getInt("db_size"), shard.shard_name, shard.begin, shard.end, cm::LogJoinShard::modulo, flush_interval); fnord::logInfo( "cm.logjoin", "Using session schema:\n$0", joined_sessions_schema.toString()); /* open session db */ auto sessdb = mdb::MDB::open( flags.getString("datadir"), false, 1000000 * flags.getInt("db_size"), shard.shard_name + ".db", shard.shard_name + ".db.lck", false); /* set up input feed reader */ feeds::RemoteFeedReader feed_reader(&rpc_client); feed_reader.setMaxSpread(10 * kMicrosPerSecond); HashMap<String, URI> input_feeds; input_feeds.emplace( "tracker_log.feedserver01.nue01.production.fnrd.net", URI("http://s01.nue01.production.fnrd.net:7001/rpc")); input_feeds.emplace( "tracker_log.feedserver02.nue01.production.fnrd.net", URI("http://s02.nue01.production.fnrd.net:7001/rpc")); /* setup time backfill */ feed_reader.setTimeBackfill([] (const feeds::FeedEntry& entry) -> DateTime { const auto& log_line = entry.data; auto c_end = log_line.find("|"); if (c_end == std::string::npos) return 0; auto t_end = log_line.find("|", c_end + 1); if (t_end == std::string::npos) return 0; auto timestr = log_line.substr(c_end + 1, t_end - c_end - 1); return std::stoul(timestr) * fnord::kMicrosPerSecond; }); /* open index */ RefPtr<DocIndex> index( new DocIndex( flags.getString("index"), "documents-dawanda", true)); /* set up logjoin target */ fnord::fts::Analyzer analyzer(flags.getString("conf")); cm::LogJoinTarget logjoin_target( joined_sessions_schema, &analyzer, index, dry_run); /* set up logjoin upload */ cm::LogJoinUpload logjoin_upload( sessdb, flags.getString("publish_to"), &http); /* setup logjoin */ cm::LogJoin logjoin(shard, dry_run, &logjoin_target); logjoin.exportStats("/cm-logjoin/global"); logjoin.exportStats(StringUtil::format("/cm-logjoin/$0", shard.shard_name)); fnord::stats::Counter<uint64_t> stat_stream_time_low; fnord::stats::Counter<uint64_t> stat_stream_time_high; fnord::stats::Counter<uint64_t> stat_active_sessions; fnord::stats::Counter<uint64_t> stat_dbsize; exportStat( StringUtil::format("/cm-logjoin/$0/stream_time_low", shard.shard_name), &stat_stream_time_low, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/stream_time_high", shard.shard_name), &stat_stream_time_high, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/active_sessions", shard.shard_name), &stat_active_sessions, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/dbsize", shard.shard_name), &stat_dbsize, fnord::stats::ExportMode::EXPORT_VALUE); /* upload pending q */ if (!dry_run) { logjoin_upload.upload(); } /* resume from last offset */ auto txn = sessdb->startTransaction(true); try { logjoin.importTimeoutList(txn.get()); for (const auto& input_feed : input_feeds) { uint64_t offset = 0; auto last_offset = txn->get( StringUtil::format("__logjoin_offset~$0", input_feed.first)); if (!last_offset.isEmpty()) { offset = std::stoul(last_offset.get().toString()); } fnord::logInfo( "cm.logjoin", "Adding source feed:\n feed=$0\n url=$1\n offset: $2", input_feed.first, input_feed.second.toString(), offset); feed_reader.addSourceFeed( input_feed.second, input_feed.first, offset, batch_size, buffer_size); } txn->abort(); } catch (...) { txn->abort(); throw; } fnord::logInfo("cm.logjoin", "Resuming logjoin..."); DateTime last_flush; uint64_t rate_limit_micros = flush_interval * kMicrosPerSecond; for (;;) { auto begin = WallClock::unixMicros(); feed_reader.fillBuffers(); auto txn = sessdb->startTransaction(); int i = 0; for (; i < batch_size; ++i) { auto entry = feed_reader.fetchNextEntry(); if (entry.isEmpty()) { break; } try { logjoin.insertLogline(entry.get().data, txn.get()); } catch (const std::exception& e) { fnord::logError("cm.logjoin", e, "invalid log line"); } } auto watermarks = feed_reader.watermarks(); auto etime = WallClock::now().unixMicros() - last_flush.unixMicros(); if (etime > rate_limit_micros) { last_flush = WallClock::now(); logjoin.flush(txn.get(), watermarks.first); } auto stream_offsets = feed_reader.streamOffsets(); String stream_offsets_str; for (const auto& soff : stream_offsets) { txn->update( StringUtil::format("__logjoin_offset~$0", soff.first), StringUtil::toString(soff.second)); stream_offsets_str += StringUtil::format("\n offset[$0]=$1", soff.first, soff.second); } fnord::logInfo( "cm.logjoin", "LogJoin comitting...\n stream_time=<$0 ... $1>\n" \ " active_sessions=$2\n flushed_sessions=$3$4", watermarks.first, watermarks.second, logjoin.numSessions(), logjoin_target.num_sessions, stream_offsets_str); if (dry_run) { txn->abort(); } else { txn->commit(); try { logjoin_upload.upload(); } catch (const std::exception& e) { fnord::logError("cm.logjoin", e, "upload failed"); } } if (cm_logjoin_shutdown.load()) { break; } stat_stream_time_low.set(watermarks.first.unixMicros()); stat_stream_time_high.set(watermarks.second.unixMicros()); stat_active_sessions.set(logjoin.numSessions()); //stat_dbsize.set(FileUtil::du_c(flags.getString("datadir")); auto rtime = WallClock::unixMicros() - begin; auto rlimit = kMicrosPerSecond; if (i < 2 && rtime < rlimit) { usleep(rlimit - rtime); } } ev.shutdown(); evloop_thread.join(); sessdb->sync(); fnord::logInfo("cm.logjoin", "LogJoin exiting..."); return 0; } <|endoftext|>
<commit_before>/* ** repository: https://github.com/trumanzhao/luabus ** trumanzhao, 2017-06-25, trumanzhao@foxmail.com */ #include "lua_socket_mgr.h" int create_socket_mgr(lua_State* L) { int max_fd = (int)lua_tonumber(L, 1); lua_socket_mgr* mgr = new lua_socket_mgr(); if (!mgr->setup(L, max_fd)) { delete mgr; lua_pushnil(L); return 1; } lua_push_object(L, mgr); return 1; } extern "C" int luaopen_lbus(lua_State* L) { lua_newtable(L); lua_set_table_function(L, -1, "create_socket_mgr", create_socket_mgr); return 1; } <commit_msg>修正VC下的符号导出<commit_after>/* ** repository: https://github.com/trumanzhao/luabus ** trumanzhao, 2017-06-25, trumanzhao@foxmail.com */ #include "lua_socket_mgr.h" int create_socket_mgr(lua_State* L) { int max_fd = (int)lua_tonumber(L, 1); lua_socket_mgr* mgr = new lua_socket_mgr(); if (!mgr->setup(L, max_fd)) { delete mgr; lua_pushnil(L); return 1; } lua_push_object(L, mgr); return 1; } #ifdef _MSC_VER #define LBUS_API _declspec(dllexport) #else #define LBUS_API #endif extern "C" int LBUS_API luaopen_lbus(lua_State* L) { lua_newtable(L); lua_set_table_function(L, -1, "create_socket_mgr", create_socket_mgr); return 1; } <|endoftext|>
<commit_before>#include <node.h> #include <node_buffer.h> #include <string.h> #include <stdlib.h> #include "magic.h" using namespace node; using namespace v8; struct Baton { uv_work_t request; Persistent<Function> callback; char* data; uint32_t dataLen; bool dataIsPath; // libmagic info const char* path; int flags; bool error; char* error_message; const char* result; }; static Persistent<FunctionTemplate> constructor; static const char* fallbackPath; class Magic : public ObjectWrap { public: const char* mpath; int mflags; Magic(const char* path, int flags) { if (path != NULL) { /* Windows blows up trying to look up the path '(null)' returned by magic_getpath() */ if (strncmp(path, "(null)", 6) == 0) path = NULL; } mpath = (path == NULL ? strdup(fallbackPath) : path); mflags = flags; } ~Magic() { if (mpath != NULL) { free((void*)mpath); mpath = NULL; } } static Handle<Value> New(const Arguments& args) { HandleScope scope; #ifndef _WIN32 int mflags = MAGIC_SYMLINK; #else int mflags = MAGIC_NONE; #endif char* path = NULL; bool use_bundled = true; if (!args.IsConstructCall()) { return ThrowException(Exception::TypeError( String::New("Use `new` to create instances of this object.")) ); } if (args.Length() > 1) { if (args[1]->IsInt32()) mflags = args[1]->Int32Value(); else { return ThrowException(Exception::TypeError( String::New("Second argument must be an integer"))); } } if (args.Length() > 0) { if (args[0]->IsString()) { use_bundled = false; String::Utf8Value str(args[0]->ToString()); path = strdup((const char*)(*str)); } else if (args[0]->IsInt32()) mflags = args[0]->Int32Value(); else if (args[0]->IsBoolean() && !args[0]->BooleanValue()) { use_bundled = false; path = strdup(magic_getpath(NULL, 0/*FILE_LOAD*/)); } else { return ThrowException(Exception::TypeError( String::New("First argument must be a string or integer"))); } } Magic* obj = new Magic((use_bundled ? NULL : path), mflags); obj->Wrap(args.This()); obj->Ref(); return args.This(); } static Handle<Value> DetectFile(const Arguments& args) { HandleScope scope; Magic* obj = ObjectWrap::Unwrap<Magic>(args.This()); if (!args[0]->IsString()) { return ThrowException(Exception::TypeError( String::New("First argument must be a string"))); } if (!args[1]->IsFunction()) { return ThrowException(Exception::TypeError( String::New("Second argument must be a callback function"))); } Local<Function> callback = Local<Function>::Cast(args[1]); String::Utf8Value str(args[0]->ToString()); Baton* baton = new Baton(); baton->error = false; baton->error_message = NULL; baton->request.data = baton; baton->callback = Persistent<Function>::New(callback); baton->data = strdup((const char*)*str); baton->dataIsPath = true; baton->path = obj->mpath; baton->flags = obj->mflags; baton->result = NULL; int status = uv_queue_work(uv_default_loop(), &baton->request, Magic::DetectWork, (uv_after_work_cb)Magic::DetectAfter); assert(status == 0); return Undefined(); } static Handle<Value> Detect(const Arguments& args) { HandleScope scope; Magic* obj = ObjectWrap::Unwrap<Magic>(args.This()); if (args.Length() < 2) { return ThrowException(Exception::TypeError( String::New("Expecting 2 arguments"))); } if (!Buffer::HasInstance(args[0])) { return ThrowException(Exception::TypeError( String::New("First argument must be a Buffer"))); } if (!args[1]->IsFunction()) { return ThrowException(Exception::TypeError( String::New("Second argument must be a callback function"))); } Local<Function> callback = Local<Function>::Cast(args[1]); #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 10 Local<Object> buffer_obj = args[0]->ToObject(); #else Local<Value> buffer_obj = args[0]; #endif Baton* baton = new Baton(); baton->error = false; baton->error_message = NULL; baton->request.data = baton; baton->callback = Persistent<Function>::New(callback); baton->data = Buffer::Data(buffer_obj); baton->dataLen = Buffer::Length(buffer_obj); baton->dataIsPath = false; baton->path = obj->mpath; baton->flags = obj->mflags; baton->result = NULL; int status = uv_queue_work(uv_default_loop(), &baton->request, Magic::DetectWork, (uv_after_work_cb)Magic::DetectAfter); assert(status == 0); return Undefined(); } static void DetectWork(uv_work_t* req) { Baton* baton = static_cast<Baton*>(req->data); const char* result; struct magic_set *magic = magic_open(baton->flags | MAGIC_NO_CHECK_COMPRESS | MAGIC_ERROR); if (magic == NULL) { baton->error_message = strdup(uv_strerror( uv_last_error(uv_default_loop()))); } else if (magic_load(magic, baton->path) == -1 && magic_load(magic, fallbackPath) == -1) { baton->error_message = strdup(magic_error(magic)); magic_close(magic); magic = NULL; } if (magic == NULL) { if (baton->error_message) baton->error = true; return; } if (baton->dataIsPath) result = magic_file(magic, baton->data); else result = magic_buffer(magic, (const void*)baton->data, baton->dataLen); if (result == NULL) { const char* error = magic_error(magic); if (error) { baton->error = true; baton->error_message = strdup(error); } } else baton->result = strdup(result); magic_close(magic); } static void DetectAfter(uv_work_t* req) { HandleScope scope; Baton* baton = static_cast<Baton*>(req->data); if (baton->error) { Local<Value> err = Exception::Error(String::New(baton->error_message)); free(baton->error_message); const unsigned argc = 1; Local<Value> argv[argc] = { err }; TryCatch try_catch; baton->callback->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) FatalException(try_catch); } else { const unsigned argc = 2; Local<Value> argv[argc] = { Local<Value>::New(Null()), Local<Value>::New(baton->result ? String::New(baton->result) : String::Empty()) }; if (baton->result) free((void*)baton->result); TryCatch try_catch; baton->callback->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) FatalException(try_catch); } if (baton->dataIsPath) free(baton->data); baton->callback.Dispose(); delete baton; } static Handle<Value> SetFallback(const Arguments& args) { HandleScope scope; if (fallbackPath) free((void*)fallbackPath); if (args.Length() > 0 && args[0]->IsString() && args[0]->ToString()->Length() > 0) { String::Utf8Value str(args[0]->ToString()); fallbackPath = strdup((const char*)(*str)); } else fallbackPath = NULL; return Undefined(); } static void Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> tpl = FunctionTemplate::New(New); Local<String> name = String::NewSymbol("Magic"); constructor = Persistent<FunctionTemplate>::New(tpl); constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(name); NODE_SET_PROTOTYPE_METHOD(constructor, "detectFile", DetectFile); NODE_SET_PROTOTYPE_METHOD(constructor, "detect", Detect); target->Set(String::NewSymbol("setFallback"), FunctionTemplate::New(SetFallback)->GetFunction()); target->Set(name, constructor->GetFunction()); } }; extern "C" { void init(Handle<Object> target) { HandleScope scope; Magic::Initialize(target); } NODE_MODULE(magic, init); } <commit_msg>src: convert filename encoding on Windows<commit_after>#include <node.h> #include <node_buffer.h> #include <string.h> #include <stdlib.h> #include <locale.h> #ifdef _WIN32 # include <wchar.h> #endif #include "magic.h" using namespace node; using namespace v8; struct Baton { uv_work_t request; Persistent<Function> callback; char* data; uint32_t dataLen; bool dataIsPath; // libmagic info const char* path; int flags; bool error; char* error_message; const char* result; }; static Persistent<FunctionTemplate> constructor; static const char* fallbackPath; class Magic : public ObjectWrap { public: const char* mpath; int mflags; Magic(const char* path, int flags) { if (path != NULL) { /* Windows blows up trying to look up the path '(null)' returned by magic_getpath() */ if (strncmp(path, "(null)", 6) == 0) path = NULL; } mpath = (path == NULL ? strdup(fallbackPath) : path); mflags = flags; } ~Magic() { if (mpath != NULL) { free((void*)mpath); mpath = NULL; } } static Handle<Value> New(const Arguments& args) { HandleScope scope; #ifndef _WIN32 int mflags = MAGIC_SYMLINK; #else int mflags = MAGIC_NONE; #endif char* path = NULL; bool use_bundled = true; if (!args.IsConstructCall()) { return ThrowException(Exception::TypeError( String::New("Use `new` to create instances of this object.")) ); } if (args.Length() > 1) { if (args[1]->IsInt32()) mflags = args[1]->Int32Value(); else { return ThrowException(Exception::TypeError( String::New("Second argument must be an integer"))); } } if (args.Length() > 0) { if (args[0]->IsString()) { use_bundled = false; String::Utf8Value str(args[0]->ToString()); path = strdup((const char*)(*str)); } else if (args[0]->IsInt32()) mflags = args[0]->Int32Value(); else if (args[0]->IsBoolean() && !args[0]->BooleanValue()) { use_bundled = false; path = strdup(magic_getpath(NULL, 0/*FILE_LOAD*/)); } else { return ThrowException(Exception::TypeError( String::New("First argument must be a string or integer"))); } } Magic* obj = new Magic((use_bundled ? NULL : path), mflags); obj->Wrap(args.This()); obj->Ref(); return args.This(); } static Handle<Value> DetectFile(const Arguments& args) { HandleScope scope; Magic* obj = ObjectWrap::Unwrap<Magic>(args.This()); if (!args[0]->IsString()) { return ThrowException(Exception::TypeError( String::New("First argument must be a string"))); } if (!args[1]->IsFunction()) { return ThrowException(Exception::TypeError( String::New("Second argument must be a callback function"))); } Local<Function> callback = Local<Function>::Cast(args[1]); String::Utf8Value str(args[0]->ToString()); Baton* baton = new Baton(); baton->error = false; baton->error_message = NULL; baton->request.data = baton; baton->callback = Persistent<Function>::New(callback); #ifdef _WIN32 // convert UTF8 filename string to wide-character string back to C-string const char* ofn = (const char*)*str; char* cfn = NULL; int wLen; wLen = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, ofn, -1, NULL, 0); if (wLen) { wchar_t* wfn = (wchar_t*)malloc(wLen * sizeof(wchar_t)); if (wfn) { if (MultiByteToWideChar(CP_UTF8, 0, ofn, -1, wfn, wLen) != 0) { int cLen = wcstombs(NULL, wfn, 0); if (cLen) { cfn = (char*)malloc(cLen + 1); if (cfn) wcstombs(cfn, wfn, cLen + 1); } } free(wfn); wfn = NULL; } } baton->data = cfn; #else baton->data = strdup((const char*)*str); #endif baton->dataIsPath = true; baton->path = obj->mpath; baton->flags = obj->mflags; baton->result = NULL; int status = uv_queue_work(uv_default_loop(), &baton->request, Magic::DetectWork, (uv_after_work_cb)Magic::DetectAfter); assert(status == 0); return Undefined(); } static Handle<Value> Detect(const Arguments& args) { HandleScope scope; Magic* obj = ObjectWrap::Unwrap<Magic>(args.This()); if (args.Length() < 2) { return ThrowException(Exception::TypeError( String::New("Expecting 2 arguments"))); } if (!Buffer::HasInstance(args[0])) { return ThrowException(Exception::TypeError( String::New("First argument must be a Buffer"))); } if (!args[1]->IsFunction()) { return ThrowException(Exception::TypeError( String::New("Second argument must be a callback function"))); } Local<Function> callback = Local<Function>::Cast(args[1]); #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 10 Local<Object> buffer_obj = args[0]->ToObject(); #else Local<Value> buffer_obj = args[0]; #endif Baton* baton = new Baton(); baton->error = false; baton->error_message = NULL; baton->request.data = baton; baton->callback = Persistent<Function>::New(callback); baton->data = Buffer::Data(buffer_obj); baton->dataLen = Buffer::Length(buffer_obj); baton->dataIsPath = false; baton->path = obj->mpath; baton->flags = obj->mflags; baton->result = NULL; int status = uv_queue_work(uv_default_loop(), &baton->request, Magic::DetectWork, (uv_after_work_cb)Magic::DetectAfter); assert(status == 0); return Undefined(); } static void DetectWork(uv_work_t* req) { Baton* baton = static_cast<Baton*>(req->data); const char* result; struct magic_set *magic = magic_open(baton->flags | MAGIC_NO_CHECK_COMPRESS | MAGIC_ERROR); if (magic == NULL) { baton->error_message = strdup(uv_strerror( uv_last_error(uv_default_loop()))); } else if (magic_load(magic, baton->path) == -1 && magic_load(magic, fallbackPath) == -1) { baton->error_message = strdup(magic_error(magic)); magic_close(magic); magic = NULL; } if (magic == NULL) { if (baton->error_message) baton->error = true; return; } if (baton->dataIsPath) result = magic_file(magic, baton->data); else result = magic_buffer(magic, (const void*)baton->data, baton->dataLen); if (result == NULL) { const char* error = magic_error(magic); if (error) { baton->error = true; baton->error_message = strdup(error); } } else baton->result = strdup(result); magic_close(magic); } static void DetectAfter(uv_work_t* req) { HandleScope scope; Baton* baton = static_cast<Baton*>(req->data); if (baton->error) { Local<Value> err = Exception::Error(String::New(baton->error_message)); free(baton->error_message); const unsigned argc = 1; Local<Value> argv[argc] = { err }; TryCatch try_catch; baton->callback->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) FatalException(try_catch); } else { const unsigned argc = 2; Local<Value> argv[argc] = { Local<Value>::New(Null()), Local<Value>::New(baton->result ? String::New(baton->result) : String::Empty()) }; if (baton->result) free((void*)baton->result); TryCatch try_catch; baton->callback->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) FatalException(try_catch); } if (baton->dataIsPath) free(baton->data); baton->callback.Dispose(); delete baton; } static Handle<Value> SetFallback(const Arguments& args) { HandleScope scope; if (fallbackPath) free((void*)fallbackPath); if (args.Length() > 0 && args[0]->IsString() && args[0]->ToString()->Length() > 0) { String::Utf8Value str(args[0]->ToString()); fallbackPath = strdup((const char*)(*str)); } else fallbackPath = NULL; return Undefined(); } static void Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> tpl = FunctionTemplate::New(New); Local<String> name = String::NewSymbol("Magic"); constructor = Persistent<FunctionTemplate>::New(tpl); constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(name); NODE_SET_PROTOTYPE_METHOD(constructor, "detectFile", DetectFile); NODE_SET_PROTOTYPE_METHOD(constructor, "detect", Detect); target->Set(String::NewSymbol("setFallback"), FunctionTemplate::New(SetFallback)->GetFunction()); target->Set(name, constructor->GetFunction()); } }; extern "C" { void init(Handle<Object> target) { HandleScope scope; (void)setlocale(LC_ALL, ""); Magic::Initialize(target); } NODE_MODULE(magic, init); } <|endoftext|>
<commit_before>// This file was developed by Thomas Müller <thomas94@gmx.net>. // It is published under the BSD 3-Clause License within the LICENSE file. #include "../include/ImageViewer.h" #include "../include/SharedQueue.h" #include "../include/ThreadPool.h" #include <args.hxx> #include <ImfThreading.h> #include <iostream> #include <thread> using namespace args; using namespace std; TEV_NAMESPACE_BEGIN int mainFunc(int argc, char* argv[]) { Imf::setGlobalThreadCount(thread::hardware_concurrency()); ArgumentParser parser{ "Inspection tool for images with a high dynamic range.", "", }; HelpFlag helpFlag{ parser, "help", "Display this help menu", {'h', "help"}, }; ValueFlag<float> exposureFlag{ parser, "exposure", "Exposure scales the brightness of an image prior to tonemapping by 2^Exposure. " "It can be controlled via the GUI, or by pressing E/Shift+E.", {'e', "exposure"}, }; ValueFlag<string> filterFlag{ parser, "filter", "Filters visible images and layers according to a supplied string. " "The string must have the format 'image:layer'. " "Only images whose name contains 'image' and layers whose name contains 'layer' will be visible.", {'f', "filter"}, }; ValueFlag<bool> maximizeFlag{ parser, "maximize", "Whether to maximize the window on startup or not. " "If no images were supplied via the command line, then the default is false. " "Otherwise, the default is true.", {"max", "maximize"}, }; ValueFlag<string> metricFlag{ parser, "metric", "The metric to use when comparing two images. " R"( The available metrics are: E - Error AE - Absolute Error SE - Squared Error RAE - Relative Absolute Error RSE - Relative Squared Error )" "Default is E.", {'m', "metric"}, }; ValueFlag<float> offsetFlag{ parser, "offset", "The offset is added to the image after exposure has been applied. " "It can be controlled via the GUI, or by pressing O/Shift+O.", {'o', "offset"}, }; ValueFlag<string> tonemapFlag{ parser, "tonemap", "The tonemapping algorithm to use. " R"( The available tonemaps are: sRGB - sRGB Gamma - Gamma curve (2.2) FC - False Color PN - Positive=Green, Negative=Red )" "Default is sRGB.", {'t', "tonemap"}, }; PositionalList<string> imageFiles{ parser, "images or channel selectors", "The image files to be opened by the viewer. " "If a filename starting with a ':' is encountered, " "then this filename is not treated as an image file " "but as a comma-separated channel selector. Until the next channel " "selector is encountered only channels containing " "elements from the current selector will be loaded. This is " "especially useful for selectively loading a specific " "part of a multi-part EXR file.", }; // Parse command line arguments and react to parsing // errors using exceptions. try { parser.ParseCLI(argc, argv); } catch (args::Help) { std::cout << parser; return 0; } catch (args::ParseError e) { std::cerr << e.what() << std::endl; std::cerr << parser; return -1; } catch (args::ValidationError e) { std::cerr << e.what() << std::endl; std::cerr << parser; return -2; } // Load images passed via command line prior to initializing nanogui // such that no frozen window is created. shared_ptr<SharedQueue<ImageAddition>> imagesToAdd = make_shared<SharedQueue<ImageAddition>>(); string currentExtra; for (auto imageFile : get(imageFiles)) { if (!imageFile.empty() && imageFile[0] == ':') { currentExtra = imageFile.substr(1); continue; } ThreadPool::singleWorker().enqueueTask([imageFile, currentExtra, &imagesToAdd] { auto image = tryLoadImage(imageFile, currentExtra); if (image) { imagesToAdd->push({false, image}); } }); } // Init nanogui application nanogui::init(); { auto app = make_unique<ImageViewer>(imagesToAdd); app->drawAll(); app->setVisible(true); bool shallMaximize = false; // Load all images which were passed in via the command line. if (imageFiles) { // If all images were loaded from the command line, then there // is a good chance the user won't want to interact with the OS // to drag more images in. Therefore, let's maximize by default. shallMaximize = true; } // Override shallMaximize according to the supplied flag if (maximizeFlag) { cout << get(maximizeFlag) << endl; shallMaximize = get(maximizeFlag); } if (shallMaximize) { app->maximize(); } if (exposureFlag) { app->setExposure(get(exposureFlag)); } if (filterFlag) { app->setFilter(get(filterFlag)); } if (metricFlag) { app->setMetric(toMetric(get(metricFlag))); } if (offsetFlag) { app->setOffset(get(offsetFlag)); } if (tonemapFlag) { app->setTonemap(toTonemap(get(tonemapFlag))); } nanogui::mainloop(250); } // On some linux distributions glfwTerminate() (which is called by // nanogui::shutdown()) causes segfaults. Since we are done with our // program here anyways, let's let the OS clean up after us. //nanogui::shutdown(); // Let all threads gracefully terminate. ThreadPool::shutdown(); return 0; } TEV_NAMESPACE_END int main(int argc, char* argv[]) { try { tev::mainFunc(argc, argv); } catch (const runtime_error& e) { cerr << "Uncaught exception: "s + e.what() << endl; return 1; } } <commit_msg>Significantly shorten main.cpp<commit_after>// This file was developed by Thomas Müller <thomas94@gmx.net>. // It is published under the BSD 3-Clause License within the LICENSE file. #include "../include/ImageViewer.h" #include "../include/SharedQueue.h" #include "../include/ThreadPool.h" #include <args.hxx> #include <ImfThreading.h> #include <iostream> #include <thread> using namespace args; using namespace std; TEV_NAMESPACE_BEGIN int mainFunc(int argc, char* argv[]) { Imf::setGlobalThreadCount(thread::hardware_concurrency()); ArgumentParser parser{ "Inspection tool for images with a high dynamic range.", "", }; HelpFlag helpFlag{ parser, "help", "Display this help menu", {'h', "help"}, }; ValueFlag<float> exposureFlag{ parser, "exposure", "Exposure scales the brightness of an image prior to tonemapping by 2^Exposure. " "It can be controlled via the GUI, or by pressing E/Shift+E.", {'e', "exposure"}, }; ValueFlag<string> filterFlag{ parser, "filter", "Filters visible images and layers according to a supplied string. " "The string must have the format 'image:layer'. " "Only images whose name contains 'image' and layers whose name contains 'layer' will be visible.", {'f', "filter"}, }; ValueFlag<bool> maximizeFlag{ parser, "maximize", "Whether to maximize the window on startup or not. " "If no images were supplied via the command line, then the default is false. " "Otherwise, the default is true.", {"max", "maximize"}, }; ValueFlag<string> metricFlag{ parser, "metric", "The metric to use when comparing two images. " R"( The available metrics are: E - Error AE - Absolute Error SE - Squared Error RAE - Relative Absolute Error RSE - Relative Squared Error )" "Default is E.", {'m', "metric"}, }; ValueFlag<float> offsetFlag{ parser, "offset", "The offset is added to the image after exposure has been applied. " "It can be controlled via the GUI, or by pressing O/Shift+O.", {'o', "offset"}, }; ValueFlag<string> tonemapFlag{ parser, "tonemap", "The tonemapping algorithm to use. " R"( The available tonemaps are: sRGB - sRGB Gamma - Gamma curve (2.2) FC - False Color PN - Positive=Green, Negative=Red )" "Default is sRGB.", {'t', "tonemap"}, }; PositionalList<string> imageFiles{ parser, "images or channel selectors", "The image files to be opened by the viewer. " "If a filename starting with a ':' is encountered, " "then this filename is not treated as an image file " "but as a comma-separated channel selector. Until the next channel " "selector is encountered only channels containing " "elements from the current selector will be loaded. This is " "especially useful for selectively loading a specific " "part of a multi-part EXR file.", }; // Parse command line arguments and react to parsing // errors using exceptions. try { parser.ParseCLI(argc, argv); } catch (args::Help) { std::cout << parser; return 0; } catch (args::ParseError e) { std::cerr << e.what() << std::endl; std::cerr << parser; return -1; } catch (args::ValidationError e) { std::cerr << e.what() << std::endl; std::cerr << parser; return -2; } // Load images passed via command line in the background prior to // creating our main application such that they are not stalled // by the potentially slow initialization of opengl / glfw. shared_ptr<SharedQueue<ImageAddition>> imagesToAdd = make_shared<SharedQueue<ImageAddition>>(); string channelSelector; for (auto imageFile : get(imageFiles)) { if (!imageFile.empty() && imageFile[0] == ':') { channelSelector = imageFile.substr(1); continue; } ThreadPool::singleWorker().enqueueTask([imageFile, channelSelector, &imagesToAdd] { auto image = tryLoadImage(imageFile, channelSelector); if (image) { imagesToAdd->push({false, image}); } }); } // Init nanogui application nanogui::init(); { auto app = make_unique<ImageViewer>(imagesToAdd); app->drawAll(); app->setVisible(true); // Do what the maximize flag tells us---if it exists---and // maximize if we have images otherwise. if (maximizeFlag ? get(maximizeFlag) : imageFiles) { app->maximize(); } // Apply parameter flags if (exposureFlag) { app->setExposure(get(exposureFlag)); } if (filterFlag) { app->setFilter(get(filterFlag)); } if (metricFlag) { app->setMetric(toMetric(get(metricFlag))); } if (offsetFlag) { app->setOffset(get(offsetFlag)); } if (tonemapFlag) { app->setTonemap(toTonemap(get(tonemapFlag))); } // Refresh only every 250ms if there are no user interactions. // This makes an idling tev surprisingly energy-efficient. :) nanogui::mainloop(250); } // On some linux distributions glfwTerminate() (which is called by // nanogui::shutdown()) causes segfaults. Since we are done with our // program here anyways, let's let the OS clean up after us. //nanogui::shutdown(); // Let all threads gracefully terminate. ThreadPool::shutdown(); return 0; } TEV_NAMESPACE_END int main(int argc, char* argv[]) { try { tev::mainFunc(argc, argv); } catch (const runtime_error& e) { cerr << "Uncaught exception: "s + e.what() << endl; return 1; } } <|endoftext|>
<commit_before>#include <cstring> #include <string> #include <iostream> #include <map> #include <set> #include <argp.h> #include <arpa/inet.h> #include <ifaddrs.h> #include <netinet/in.h> #include <pcap.h> #include <signal.h> #include <sqlite3.h> #include <sys/time.h> #include "config.h" #include "log.h" #include "nethdr.h" #include "qnconnection.h" #include "qnflow.h" #include "util.h" const char *argp_program_version = QUANTIFIEDNET_FULL_VERSION; const char *argp_program_bug_address = "<ippatsuman+quantifiednet@gmail.com>"; static char doc[] = "quantifiednet -- a minimal tracer of network connections"; static char args_doc[] = "INTERFACE DB"; static struct argp_option options[] = { {"INTERFACE", 0, 0, OPTION_DOC, "Interface to listen on (e.g., eth0)", 1}, {"DB", 0, 0, OPTION_DOC, "Path to SQLite database", 1}, { 0, 0, 0, 0, 0, 0} }; struct arguments { std::string database; std::string interface; std::map<QNConnection, QNFlow> traffic; int pcap_dl_type; }; static error_t parse_opt (int key, char *arg, struct argp_state *state) { struct arguments *arguments = static_cast<struct arguments*>(state->input); switch (key) { case ARGP_KEY_ARG: if (state->arg_num > 2) { argp_usage(state); } if (state->arg_num == 0) { arguments->interface = arg; } else { arguments->database = arg; } break; case ARGP_KEY_END: if (state->arg_num < 2) { argp_usage(state); } default: return ARGP_ERR_UNKNOWN; } return 0; } static struct argp argp = { options, parse_opt, args_doc, doc, NULL, NULL, NULL}; static void print_usage(void) { argp_help(&argp, stderr, ARGP_HELP_DOC, 0); } static bool InitDbOrDie(const std::string path) { std::string file_uri; std::string create_table = "create table if not exists tcp_connections (id integer primary key, " \ "srcip text not null, srcport integer not null, dstip text not null, " \ "dstport integer not null, sent integer not null, " \ "rcvd integer not null, starttime text not null, " \ "endtime text not null);"; int rc; sqlite3 *pDB; sqlite3_stmt *pStmt; file_uri = "file:" + path; info_log("Using %s as Sqlite3 db", file_uri.c_str()); sqlite3_config(SQLITE_CONFIG_URI, 1); rc = sqlite3_open_v2(file_uri.c_str(), &pDB, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI, NULL); if (rc != SQLITE_OK) { sqlite3_close(pDB); critical_log("%s", sqlite3_errstr(rc)); } rc = sqlite3_prepare_v2(pDB, create_table.c_str(), create_table.length(), &pStmt, NULL); if (rc != SQLITE_OK) { sqlite3_finalize(pStmt); sqlite3_close(pDB); critical_log("%s", sqlite3_errstr(rc)); } rc = sqlite3_step(pStmt); if (rc != SQLITE_DONE) { sqlite3_finalize(pStmt); sqlite3_close(pDB); critical_log("%s", sqlite3_errstr(rc)); } sqlite3_finalize(pStmt); sqlite3_close(pDB); return true; } static void GetLocalAddressesAndIntfOrDie(std::set<in_addr_t>& addresses, std::set<std::string>& interfaces) { struct ifaddrs *ifaddr, *ifa; int family; if (getifaddrs(&ifaddr) == -1) { critical_log("%s", "getifaddrs"); } for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) { continue; } family = ifa->ifa_addr->sa_family; if (family != AF_INET) { continue; } in_addr_t s_addr = (reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr))->sin_addr.s_addr; addresses.insert(s_addr); interfaces.insert(ifa->ifa_name); } freeifaddrs(ifaddr); } static void CheckIntfOrDie(const std::string& ifa, struct arguments& arg) { char errbuf[PCAP_ERRBUF_SIZE]; pcap_t *pcap; int dl_type; pcap = pcap_create(ifa.c_str(), errbuf); if (pcap == NULL) { critical_log("Unable to open interface %s for capture: %s", ifa.c_str(), errbuf); } if (pcap_activate(pcap) != 0) { critical_log("Unable to open interface %s for capture: %s", ifa.c_str(), pcap_geterr(pcap)); } dl_type = pcap_datalink(pcap); if (dl_type != DLT_LINUX_SLL && dl_type != DLT_EN10MB) { pcap_close(pcap); critical_log("Interface %s has datalink type %s (%s), which is not currently supported", ifa.c_str(), pcap_datalink_val_to_name(dl_type), pcap_datalink_val_to_description(dl_type)); } arg.pcap_dl_type = dl_type; pcap_close(pcap); } // evil global goes here: sorry, I need it in the signal handler. static pcap_t *p; static void SigHandler(int sig) { if (p != NULL) { pcap_breakloop(p); } } static void ProcessPkt(unsigned char *user, const struct pcap_pkthdr *h, const u_char *bytes) { struct arguments* arguments; const struct ip_hdr* ip_hdr; const struct tcp_hdr* tcp_hdr; size_t datalink_size; size_t ip_size; arguments = reinterpret_cast<struct arguments*>(user); if (arguments->pcap_dl_type == DLT_LINUX_SLL) { ip_hdr = reinterpret_cast<const struct ip_hdr*>(bytes + sizeof(struct linux_sll_hdr)); datalink_size = sizeof(struct linux_sll_hdr); } else { // arguments->pcap_dl_type == DLT_EN10MB datalink_size = sizeof(struct ether_hdr); } ip_hdr = reinterpret_cast<const struct ip_hdr*>(bytes + datalink_size); // discard non TCP packets if (ip_hdr->proto != IPPROTO_TCP) return; ip_size = IP_HL(ip_hdr)*sizeof(uint32_t); tcp_hdr = reinterpret_cast<const struct tcp_hdr*>(bytes + datalink_size + ip_size); QNConnection conn = QNConnection(ip_hdr->src, tcp_hdr->sport, ip_hdr->dest, tcp_hdr->dport); auto pflow = arguments->traffic.find(conn); if ((tcp_hdr->flags & TCP_SYN) && (tcp_hdr->flags & TCP_ACK)) { // new connection struct timeval now; gettimeofday(&now, NULL); QNFlow flow = QNFlow(conn, now); info_log("New connection %s:%u -> %s:%u", AddrToString(ip_hdr->src).c_str(), ntohs(tcp_hdr->sport), AddrToString(ip_hdr->dest).c_str(), ntohs(tcp_hdr->dport)); arguments->traffic.insert(std::make_pair(conn, flow)); } else if (pflow != arguments->traffic.end()) { // untracked connection if ((tcp_hdr->flags & TCP_FIN) || (tcp_hdr->flags & TCP_RST)) { arguments->traffic.erase(pflow); info_log("Closed connection %s:%u -> %s:%u", AddrToString(ip_hdr->src).c_str(), ntohs(tcp_hdr->sport), AddrToString(ip_hdr->dest).c_str(), ntohs(tcp_hdr->dport)); std::cout << (pflow->second) << std::endl; } else { uint32_t len = ntohs(ip_hdr->len) - IP_HL(ip_hdr)*sizeof(uint32_t) - TCP_DOFF(tcp_hdr)*sizeof(uint32_t); pflow->second.AddSent(ip_hdr->src, len); } } } int main(int argc, char *argv[]) { struct arguments arguments; char errbuf[PCAP_ERRBUF_SIZE]; char filter_expression[] = "ip"; struct bpf_program filter; std::set<in_addr_t> addresses; std::set<std::string> interfaces; argp_parse(&argp, argc, argv, 0, 0, &arguments); if (arguments.interface.empty()) { print_usage(); } if (arguments.database.empty()) { print_usage(); } InitDbOrDie(arguments.database); info_log("Collecting local addresses"); interfaces.insert("any"); GetLocalAddressesAndIntfOrDie(addresses, interfaces); if (interfaces.find(arguments.interface) == interfaces.end()) { critical_log("Interface %s is not a valid AF_INET interface", arguments.interface.c_str()); } info_log("Checking capture interface \"%s\"", arguments.interface.c_str()); CheckIntfOrDie(arguments.interface, arguments); info_log("Control-C to quit"); if (signal(SIGINT, SigHandler) == SIG_ERR) { critical_log("Error while installing signal handler"); } p = pcap_create(arguments.interface.c_str(), errbuf); if (p == NULL) { critical_log("Unable to open interface %s for capture: %s", arguments.interface.c_str(), errbuf); } if (pcap_activate(p) != 0) { critical_log("Unable to open interface %s for capture: %s", arguments.interface.c_str(), pcap_geterr(p)); } arguments.pcap_dl_type = pcap_datalink(p); if (pcap_compile(p, &filter, filter_expression, 0, PCAP_NETMASK_UNKNOWN) != 0) { critical_log("Unable to compile filter expression: %s", pcap_geterr(p)); } if (pcap_setfilter(p, &filter) != 0) { critical_log("Unable to set filter: %s", pcap_geterr(p)); } pcap_loop(p, 0, ProcessPkt, reinterpret_cast<u_char*>(&arguments)); pcap_freecode(&filter); pcap_close(p); return 0; } <commit_msg>Added more signal handling<commit_after>#include <cstring> #include <string> #include <iostream> #include <map> #include <set> #include <argp.h> #include <arpa/inet.h> #include <ifaddrs.h> #include <netinet/in.h> #include <pcap.h> #include <signal.h> #include <sqlite3.h> #include <sys/time.h> #include "config.h" #include "log.h" #include "nethdr.h" #include "qnconnection.h" #include "qnflow.h" #include "util.h" const char *argp_program_version = QUANTIFIEDNET_FULL_VERSION; const char *argp_program_bug_address = "<ippatsuman+quantifiednet@gmail.com>"; static char doc[] = "quantifiednet -- a minimal tracer of network connections"; static char args_doc[] = "INTERFACE DB"; static struct argp_option options[] = { {"INTERFACE", 0, 0, OPTION_DOC, "Interface to listen on (e.g., eth0)", 1}, {"DB", 0, 0, OPTION_DOC, "Path to SQLite database", 1}, { 0, 0, 0, 0, 0, 0} }; struct arguments { std::string database; std::string interface; std::map<QNConnection, QNFlow> traffic; int pcap_dl_type; }; static error_t parse_opt (int key, char *arg, struct argp_state *state) { struct arguments *arguments = static_cast<struct arguments*>(state->input); switch (key) { case ARGP_KEY_ARG: if (state->arg_num > 2) { argp_usage(state); } if (state->arg_num == 0) { arguments->interface = arg; } else { arguments->database = arg; } break; case ARGP_KEY_END: if (state->arg_num < 2) { argp_usage(state); } default: return ARGP_ERR_UNKNOWN; } return 0; } static struct argp argp = { options, parse_opt, args_doc, doc, NULL, NULL, NULL}; static void print_usage(void) { argp_help(&argp, stderr, ARGP_HELP_DOC, 0); } static bool InitDbOrDie(const std::string path) { std::string file_uri; std::string create_table = "create table if not exists tcp_connections (id integer primary key, " \ "srcip text not null, srcport integer not null, dstip text not null, " \ "dstport integer not null, sent integer not null, " \ "rcvd integer not null, starttime text not null, " \ "endtime text not null);"; int rc; sqlite3 *pDB; sqlite3_stmt *pStmt; file_uri = "file:" + path; info_log("Using %s as Sqlite3 db", file_uri.c_str()); sqlite3_config(SQLITE_CONFIG_URI, 1); rc = sqlite3_open_v2(file_uri.c_str(), &pDB, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI, NULL); if (rc != SQLITE_OK) { sqlite3_close(pDB); critical_log("%s", sqlite3_errstr(rc)); } rc = sqlite3_prepare_v2(pDB, create_table.c_str(), create_table.length(), &pStmt, NULL); if (rc != SQLITE_OK) { sqlite3_finalize(pStmt); sqlite3_close(pDB); critical_log("%s", sqlite3_errstr(rc)); } rc = sqlite3_step(pStmt); if (rc != SQLITE_DONE) { sqlite3_finalize(pStmt); sqlite3_close(pDB); critical_log("%s", sqlite3_errstr(rc)); } sqlite3_finalize(pStmt); sqlite3_close(pDB); return true; } static void GetLocalAddressesAndIntfOrDie(std::set<in_addr_t>& addresses, std::set<std::string>& interfaces) { struct ifaddrs *ifaddr, *ifa; int family; if (getifaddrs(&ifaddr) == -1) { critical_log("%s", "getifaddrs"); } for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) { continue; } family = ifa->ifa_addr->sa_family; if (family != AF_INET) { continue; } in_addr_t s_addr = (reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr))->sin_addr.s_addr; addresses.insert(s_addr); interfaces.insert(ifa->ifa_name); } freeifaddrs(ifaddr); } static void CheckIntfOrDie(const std::string& ifa, struct arguments& arg) { char errbuf[PCAP_ERRBUF_SIZE]; pcap_t *pcap; int dl_type; pcap = pcap_create(ifa.c_str(), errbuf); if (pcap == NULL) { critical_log("Unable to open interface %s for capture: %s", ifa.c_str(), errbuf); } if (pcap_activate(pcap) != 0) { critical_log("Unable to open interface %s for capture: %s", ifa.c_str(), pcap_geterr(pcap)); } dl_type = pcap_datalink(pcap); if (dl_type != DLT_LINUX_SLL && dl_type != DLT_EN10MB) { pcap_close(pcap); critical_log("Interface %s has datalink type %s (%s), which is not currently supported", ifa.c_str(), pcap_datalink_val_to_name(dl_type), pcap_datalink_val_to_description(dl_type)); } arg.pcap_dl_type = dl_type; pcap_close(pcap); } // evil global goes here: sorry, I need it in the signal handler. static pcap_t *p; static void SigHandler(int sig) { if (p != NULL) { pcap_breakloop(p); } } static void ProcessPkt(unsigned char *user, const struct pcap_pkthdr *h, const u_char *bytes) { struct arguments* arguments; const struct ip_hdr* ip_hdr; const struct tcp_hdr* tcp_hdr; size_t datalink_size; size_t ip_size; arguments = reinterpret_cast<struct arguments*>(user); if (arguments->pcap_dl_type == DLT_LINUX_SLL) { ip_hdr = reinterpret_cast<const struct ip_hdr*>(bytes + sizeof(struct linux_sll_hdr)); datalink_size = sizeof(struct linux_sll_hdr); } else { // arguments->pcap_dl_type == DLT_EN10MB datalink_size = sizeof(struct ether_hdr); } ip_hdr = reinterpret_cast<const struct ip_hdr*>(bytes + datalink_size); // discard non TCP packets if (ip_hdr->proto != IPPROTO_TCP) return; ip_size = IP_HL(ip_hdr)*sizeof(uint32_t); tcp_hdr = reinterpret_cast<const struct tcp_hdr*>(bytes + datalink_size + ip_size); QNConnection conn = QNConnection(ip_hdr->src, tcp_hdr->sport, ip_hdr->dest, tcp_hdr->dport); auto pflow = arguments->traffic.find(conn); if ((tcp_hdr->flags & TCP_SYN) && (tcp_hdr->flags & TCP_ACK)) { // new connection struct timeval now; gettimeofday(&now, NULL); QNFlow flow = QNFlow(conn, now); info_log("New connection %s:%u -> %s:%u", AddrToString(ip_hdr->src).c_str(), ntohs(tcp_hdr->sport), AddrToString(ip_hdr->dest).c_str(), ntohs(tcp_hdr->dport)); arguments->traffic.insert(std::make_pair(conn, flow)); } else if (pflow != arguments->traffic.end()) { // untracked connection if ((tcp_hdr->flags & TCP_FIN) || (tcp_hdr->flags & TCP_RST)) { arguments->traffic.erase(pflow); info_log("Closed connection %s:%u -> %s:%u", AddrToString(ip_hdr->src).c_str(), ntohs(tcp_hdr->sport), AddrToString(ip_hdr->dest).c_str(), ntohs(tcp_hdr->dport)); std::cout << (pflow->second) << std::endl; } else { uint32_t len = ntohs(ip_hdr->len) - IP_HL(ip_hdr)*sizeof(uint32_t) - TCP_DOFF(tcp_hdr)*sizeof(uint32_t); pflow->second.AddSent(ip_hdr->src, len); } } } int main(int argc, char *argv[]) { struct arguments arguments; char errbuf[PCAP_ERRBUF_SIZE]; char filter_expression[] = "ip"; struct bpf_program filter; std::set<in_addr_t> addresses; std::set<std::string> interfaces; argp_parse(&argp, argc, argv, 0, 0, &arguments); if (arguments.interface.empty()) { print_usage(); } if (arguments.database.empty()) { print_usage(); } InitDbOrDie(arguments.database); info_log("Collecting local addresses"); interfaces.insert("any"); GetLocalAddressesAndIntfOrDie(addresses, interfaces); if (interfaces.find(arguments.interface) == interfaces.end()) { critical_log("Interface %s is not a valid AF_INET interface", arguments.interface.c_str()); } info_log("Checking capture interface \"%s\"", arguments.interface.c_str()); CheckIntfOrDie(arguments.interface, arguments); info_log("Control-C to quit"); if (signal(SIGINT, SigHandler) == SIG_ERR) { critical_log("Error while installing signal handler"); } if (signal(SIGHUP, SigHandler) == SIG_ERR) { critical_log("Error while installing signal handler"); } if (signal(SIGQUIT, SigHandler) == SIG_ERR) { critical_log("Error while installing signal handler"); } if (signal(SIGTERM, SigHandler) == SIG_ERR) { critical_log("Error while installing signal handler"); } p = pcap_create(arguments.interface.c_str(), errbuf); if (p == NULL) { critical_log("Unable to open interface %s for capture: %s", arguments.interface.c_str(), errbuf); } if (pcap_activate(p) != 0) { critical_log("Unable to open interface %s for capture: %s", arguments.interface.c_str(), pcap_geterr(p)); } arguments.pcap_dl_type = pcap_datalink(p); if (pcap_compile(p, &filter, filter_expression, 0, PCAP_NETMASK_UNKNOWN) != 0) { critical_log("Unable to compile filter expression: %s", pcap_geterr(p)); } if (pcap_setfilter(p, &filter) != 0) { critical_log("Unable to set filter: %s", pcap_geterr(p)); } pcap_loop(p, 0, ProcessPkt, reinterpret_cast<u_char*>(&arguments)); pcap_freecode(&filter); pcap_close(p); return 0; } <|endoftext|>
<commit_before>// The MIT License (MIT) // // Copyright (c) 2015 Relja Ljubobratovic, ljubobratovic.relja@gmail.com // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Author: // Relja Ljubobratovic, ljubobratovic.relja@gmail.com #include <io.hpp> #include <gui.hpp> #include <image.hpp> #include <improc.hpp> #include <region.hpp> #include <contour.hpp> #include <draw.hpp> #include <iostream> #include <fstream> #include "calibpattern.hpp" bool write_pattern_results(const std::vector<std::vector<cv::vec2r> > &patterns, const std::string &path) { std::ofstream stream(path, std::fstream::out); if (!stream.is_open()) { return false; } for (unsigned i = 0; i < patterns.size(); ++i) { stream << std::to_string(patterns[i][0][0]) << " " << std::to_string(patterns[i][0][1]); for (unsigned j = 1; j < patterns[i].size(); ++j) { stream << "," << std::to_string(patterns[i][j][0]) << " " << std::to_string(patterns[i][j][1]); } stream << std::endl; } stream.close(); return true; } void pattern_detection() { std::string calib_patterns[] = {"1.png", "2.png", "3.png", "4.png", "5.png", "6.png", "7.png"}; std::vector<std::vector<cv::vec2r> > patterns; for (auto im_path : calib_patterns) { auto image = cv::imread("/home/relja/calibration/ground_truth/" + im_path, cv::REAL, 1); if (image.rows() > 512) { cv::resize( } unsigned p_rows = 6; unsigned p_cols = 9; cv::matrixr im_r = image, im_rb; cv::matrixr gauss_k = cv::gauss({3, 3}); im_rb = cv::conv(im_r, gauss_k); auto pattern = detect_pattern(im_rb, p_rows, p_cols, 15., 0.15, 10); if (pattern.size() == p_rows*p_cols) { pattern = sub_pixel_detect(pattern, im_r, {5, 5}); cv::matrix3r im_draw = im_r.clone(); draw_chessboard(im_draw, pattern, {255., 0., 0.}); cv::imshow("pattern", im_draw); auto r = cv::wait_key(); if (r == 'n') { std::cout << "Pattern " << im_path << " rejected." << std::endl; continue; } else if (r == 'q') { std::cout << "Pattern detection exit" << std::endl; break; } else { std::cout << "Pattern " << im_path << " accepted." << std::endl; patterns.push_back(pattern); } } else { std::cout << "Pattern " << im_path << " not found" << std::endl; continue; } } std::string out_path; std::cout << "Where to write results?" << std::endl; std::cin >> out_path; if (write_pattern_results(patterns, out_path)) { std::cout << "Writing results to " << out_path << " successfull!" << std::endl; } else { std::cout << "Writing results to " << out_path << " failed!" << std::endl; } } int main() { pattern_detection(); return 0; } <commit_msg>added pattern detection write<commit_after>// The MIT License (MIT) // // Copyright (c) 2015 Relja Ljubobratovic, ljubobratovic.relja@gmail.com // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Author: // Relja Ljubobratovic, ljubobratovic.relja@gmail.com #include <io.hpp> #include <gui.hpp> #include <image.hpp> #include <improc.hpp> #include <region.hpp> #include <contour.hpp> #include <draw.hpp> #include <iostream> #include <fstream> #include "calibpattern.hpp" bool write_pattern_results(const std::vector<std::vector<cv::vec2r> > &patterns, const std::string &path) { std::ofstream stream(path); if (!stream.is_open()) { return false; } for (unsigned i = 0; i < patterns.size(); ++i) { stream << patterns[i][0]; for (unsigned j = 1; j < patterns[i].size(); ++j) { stream << "," << patterns[i][j]; } stream << std::endl; } stream.close(); return true; } void pattern_detection() { std::string calib_patterns[] = {"1.png", "2.png", "3.png", "4.png", "5.png", "6.png", "7.png"}; std::vector<std::vector<cv::vec2r> > patterns; for (auto im_path : calib_patterns) { auto image = cv::imread("/home/relja/calibration/ground_truth/" + im_path, cv::REAL, 1); unsigned p_rows = 6; unsigned p_cols = 9; cv::matrixr im_r = image, im_rb; cv::matrixr gauss_k = cv::gauss({5, 5}); im_rb = cv::conv(im_r, gauss_k); auto pattern = detect_pattern(im_rb, p_rows, p_cols, 18., 0.15, 12); if (pattern.size() == p_rows*p_cols) { pattern = sub_pixel_detect(pattern, im_r, {5, 5}); cv::matrix3r im_draw = im_r.clone(); draw_chessboard(im_draw, pattern, {255., 0., 0.}); cv::imshow("pattern", im_draw); auto r = cv::wait_key(); if (r == 'n') { std::cout << "Pattern " << im_path << " rejected." << std::endl; continue; } else if (r == 'q') { std::cout << "Pattern detection exit" << std::endl; break; } else { std::cout << "Pattern " << im_path << " accepted." << std::endl; patterns.push_back(pattern); } } else { std::cout << "Pattern " << im_path << " not found" << std::endl; continue; } } std::string out_path; std::cout << "Where to write results?" << std::endl; std::cin >> out_path; if (write_pattern_results(patterns, out_path)) { std::cout << "Writing results to " << out_path << " successfull!" << std::endl; } else { std::cout << "Writing results to " << out_path << " failed!" << std::endl; } } cv::matrixr calculate_homography() { cv::matrixr H; return H; } int main() { pattern_detection(); return 0; } <|endoftext|>
<commit_before>// main.cpp // Main function for testing Maggie code // // Oliver W. Laslett 2015 // O.Laslett@soton.ac.uk // #include<iostream> using std::cout; using std::endl; #include<cmath> using std::abs; #include<LangevinEquation.hpp> #include<StocLLG.hpp> #include<gtest/gtest.h> #include<boost/multi_array.hpp> typedef boost::multi_array<float,1> array_f; typedef boost::multi_array<float,2> matrix_f; // Test construction of StocLLG TEST(StochasticLLG, ContructAndDim) { StocLLG llg( 1, 2, 3, 4, 5 ); EXPECT_EQ( 3, llg.getDim() ); } // Test deterministic part of StocLLG TEST(StochasticLLG, Drift) { // declare in and out arrays array_f out( boost::extents[3] ); array_f in( boost::extents[3] ); in[0] = 2; in[1] = 3; in[2] = 4; // Set up StocLLG and compute drift StocLLG llg( 2, 3, 1, 2, 3 ); llg.computeDrift( out, in ); // Are the solutions correct? EXPECT_EQ( -34, out[0] ); EXPECT_EQ( -4, out[1] ); EXPECT_EQ( 20, out[2] ); } // Test the stochastic part of the StocLLG TEST(StochasticLLG, Diffusion) { // declare in and out arrays array_f in( boost::extents[3] ); matrix_f out( boost::extents[3][3] ); in[0] = 2; in[1] = 3; in[2] = 4; // set up the StocLLG and compute diffusion StocLLG llg( 2, 3, 1, 2, 3 ); llg.computeDiffusion( out, in ); // are the solutions correct? EXPECT_EQ( 150, out[0][0] ); EXPECT_EQ( -28, out[0][1] ); EXPECT_EQ( -54, out[0][2] ); EXPECT_EQ( -44, out[1][0] ); EXPECT_EQ( 120, out[1][1] ); EXPECT_EQ( -68, out[1][2] ); EXPECT_EQ( -42, out[2][0] ); EXPECT_EQ( -76, out[2][1] ); EXPECT_EQ( 78, out[2][2] ); } int main( int argc, char **argv ) { ::testing::InitGoogleTest( &argc, argv ); return RUN_ALL_TESTS(); } <commit_msg>Wrote tests for RK4 -- all tests pass<commit_after>// main.cpp // Main function for testing Maggie code // // Oliver W. Laslett 2015 // O.Laslett@soton.ac.uk // #include<iostream> using std::cout; using std::endl; #include<cmath> using std::abs; using std::cos; using std::sin; #include<LangevinEquation.hpp> #include<StocLLG.hpp> #include<RK4.hpp> #include<gtest/gtest.h> #include<boost/multi_array.hpp> typedef boost::multi_array<float,1> array_f; typedef boost::multi_array<float,2> matrix_f; // Test construction of StocLLG TEST(StochasticLLG, ContructAndDim) { StocLLG llg( 1, 2, 3, 4, 5 ); EXPECT_EQ( 3, llg.getDim() ); } // Test deterministic part of StocLLG TEST(StochasticLLG, Drift) { // declare in and out arrays array_f out( boost::extents[3] ); array_f in( boost::extents[3] ); in[0] = 2; in[1] = 3; in[2] = 4; // Set up StocLLG and compute drift StocLLG llg( 2, 3, 1, 2, 3 ); llg.computeDrift( out, in ); // Are the solutions correct? EXPECT_EQ( -34, out[0] ); EXPECT_EQ( -4, out[1] ); EXPECT_EQ( 20, out[2] ); } // Test the stochastic part of the StocLLG TEST(StochasticLLG, Diffusion) { // declare in and out arrays array_f in( boost::extents[3] ); matrix_f out( boost::extents[3][3] ); in[0] = 2; in[1] = 3; in[2] = 4; // set up the StocLLG and compute diffusion StocLLG llg( 2, 3, 1, 2, 3 ); llg.computeDiffusion( out, in ); // are the solutions correct? EXPECT_EQ( 150, out[0][0] ); EXPECT_EQ( -28, out[0][1] ); EXPECT_EQ( -54, out[0][2] ); EXPECT_EQ( -44, out[1][0] ); EXPECT_EQ( 120, out[1][1] ); EXPECT_EQ( -68, out[1][2] ); EXPECT_EQ( -42, out[2][0] ); EXPECT_EQ( -76, out[2][1] ); EXPECT_EQ( 78, out[2][2] ); } // Test the RK4 algorithm TEST(RK4, BasicCircle) { // declare array for initial state array_f state( boost::extents[2] ); float t=0; // initial time // fill the array state state[0] = 1; state[1] = 0; // Basic differential equation class ode : public LangevinEquation { public: ode() : LangevinEquation( 2 ) {}; // constructor // Differential equation virtual void computeDrift( array_f& out, array_f& in) { out[0] = in[1]; out[1] = -in[0]; } } testOde; // Create an instance of the RK4 integrator RK4 inte( testOde, state, t, 0.000001 ); // Run the integrator for 2000 steps for( int i=0; i<1000; i++ ) inte.step(); // Get the state and time state = inte.getState(); t = inte.getTime(); // Check the solution EXPECT_LE( abs( cos( t ) - state[0]), 1e-6 ); EXPECT_LE( abs( -sin( t ) - state[1]), 1e-6 ); } int main( int argc, char **argv ) { ::testing::InitGoogleTest( &argc, argv ); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include <cassert> #include <fstream> #include <iostream> #include <set> #include <SFML/Graphics.hpp> template <typename V> unsigned squareLength(const V& vector) { return vector.x * vector.x + vector.y * vector.y; } enum class Asset { Player, Enemy, Grass, Wood, }; struct Cell { sf::Vector2i position; Asset asset; }; struct Character { sf::Vector2i position; Asset asset; }; struct Player: Character { Player() { asset = Asset::Player; } }; struct Enemy: Character { Enemy() { asset = Asset::Enemy; } }; class Level { public: Level(std::string path); ~Level() { for (const Cell* cell: map) delete cell; for (const Enemy* enemy: enemies) delete enemy; } std::set<Cell*> map; sf::Vector2i start; std::set<Enemy*> enemies; }; Level::Level(std::string path) { std::ifstream file; file.open(path.c_str(), std::ifstream::in); assert(file); // Read level size int width, height; file >> width >> height; { // Read player start position int x, y; file >> x >> y; start = sf::Vector2i(x, y); } // Read amount of enemies int enemyCount; file >> enemyCount; // Read enemy position while (enemyCount --> 0) { Enemy* enemy = new Enemy; file >> enemy->position.x >> enemy->position.y; enemies.insert(enemy); } // Read cells for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { // Position is automatic Cell* cell = new Cell; cell->position = sf::Vector2i(x, y); // A character represents a type of cell char type = 0; file >> type; switch (type) { case 'X': cell->asset = Asset::Wood; break; case ',': cell->asset = Asset::Grass; break; // Any unknown character results in empty cell // (except blanks which are skipped) default: delete cell; continue; } map.insert(cell); } } } class Assets { public: static const char* getName(Asset a) { switch (a) { case Asset::Player: return "player"; case Asset::Grass: return "grass"; case Asset::Wood: return "wood"; case Asset::Enemy: return "enemy"; } } static std::string getPath(std::string file) { file.insert(0, "assets/"); return file; } static std::string getPath(Asset a, std::string ext) { ext.insert(0, "."); ext.insert(0, getName(a)); return getPath(ext); } static sf::Texture& getTexture(Asset a) { auto& t = textures[a]; if (t) return *t; t = new sf::Texture; const bool loaded = t->loadFromFile(getPath(a, "png")); assert(loaded); return *t; } private: static std::map<Asset, sf::Texture*> textures; }; decltype(Assets::textures) Assets::textures; int main() { sf::Vector2i viewSize(30, 20); const int cellSize = 32; const int maxRenderRadiusSq = squareLength(viewSize) / 4; Level level(Assets::getPath("level.map")); Player player; player.position = level.start; sf::RenderWindow win(sf::VideoMode(viewSize.x * cellSize, viewSize.y * cellSize), "Tiny World", sf::Style::Default & ~sf::Style::Resize); win.setFramerateLimit(60); while (win.isOpen()) { sf::Event event; while (win.pollEvent(event)) { if (event.type == sf::Event::Closed or (event.type == sf::Event::KeyPressed and event.key.code == sf::Keyboard::Escape)) win.close(); // TODO Menu ? else if (event.type == sf::Event::KeyPressed) { sf::Vector2i oldPos = player.position; switch (event.key.code) { case sf::Keyboard::Up: --player.position.y; break; case sf::Keyboard::Down: ++player.position.y; break; case sf::Keyboard::Left: --player.position.x; break; case sf::Keyboard::Right: ++player.position.x; break; default: continue; } for (Enemy* enemy: level.enemies) { if (player.position == enemy->position) { player.position = oldPos; std::cout << "Touched enemy" << std::endl; // TODO HitPoints } } if (player.position != oldPos) { for (Enemy* enemy: level.enemies) { const sf::Vector2i relPos(enemy->position - player.position); if (std::abs(relPos.x) > std::abs(relPos.y)) enemy->position.x += relPos.x < 0 ? +1 : -1; else if (relPos.x and relPos.y) enemy->position.y += relPos.y < 0 ? +1 : -1; } } } } win.clear(sf::Color(50, 50, 50)); // Draw map for (const Cell* cell: level.map) { const sf::Vector2i relPos(cell->position - player.position); if (squareLength(relPos) < maxRenderRadiusSq) { sf::Sprite sprite(Assets::getTexture(cell->asset)); sprite.move(viewSize.x / 2 * cellSize, viewSize.y / 2 * cellSize); sprite.move(relPos.x * cellSize, relPos.y * cellSize); win.draw(sprite); } } // Draw enemies for (const Enemy* enemy: level.enemies) { const sf::Vector2i relPos(enemy->position - player.position); if (squareLength(relPos) < maxRenderRadiusSq) { sf::Sprite sprite(Assets::getTexture(enemy->asset)); sprite.move(viewSize.x / 2 * cellSize, viewSize.y / 2 * cellSize); sprite.move(relPos.x * cellSize, relPos.y * cellSize); win.draw(sprite); } } { // Draw Player sf::Sprite sprite(Assets::getTexture(Asset::Player)); sprite.move((viewSize.x/2) * cellSize, (viewSize.y/2) * cellSize); win.draw(sprite); } win.display(); } return 0; } <commit_msg>Style fix<commit_after>#include <cassert> #include <fstream> #include <iostream> #include <set> #include <SFML/Graphics.hpp> template <typename V> unsigned squareLength(const V& vector) { return vector.x * vector.x + vector.y * vector.y; } enum class Asset { Player, Enemy, Grass, Wood, }; struct Cell { sf::Vector2i position; Asset asset; }; struct Character { sf::Vector2i position; Asset asset; }; struct Player: Character { Player() { asset = Asset::Player; } }; struct Enemy: Character { Enemy() { asset = Asset::Enemy; } }; class Level { public: Level(std::string path); ~Level() { for (const Cell* cell: map) delete cell; for (const Enemy* enemy: enemies) delete enemy; } std::set<Cell*> map; sf::Vector2i start; std::set<Enemy*> enemies; }; Level::Level(std::string path) { std::ifstream file; file.open(path.c_str(), std::ifstream::in); assert(file); // Read level size int width, height; file >> width >> height; { // Read player start position int x, y; file >> x >> y; start = sf::Vector2i(x, y); } // Read amount of enemies int enemyCount; file >> enemyCount; // Read enemy position while (enemyCount --> 0) { Enemy* enemy = new Enemy; file >> enemy->position.x >> enemy->position.y; enemies.insert(enemy); } // Read cells for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { // Position is automatic Cell* cell = new Cell; cell->position = sf::Vector2i(x, y); // A character represents a type of cell char type = 0; file >> type; switch (type) { case 'X': cell->asset = Asset::Wood; break; case ',': cell->asset = Asset::Grass; break; // Any unknown character results in empty cell // (except blanks which are skipped) default: delete cell; continue; } map.insert(cell); } } } class Assets { public: static const char* getName(Asset a) { switch (a) { case Asset::Player: return "player"; case Asset::Grass: return "grass"; case Asset::Wood: return "wood"; case Asset::Enemy: return "enemy"; } } static std::string getPath(std::string file) { file.insert(0, "assets/"); return file; } static std::string getPath(Asset a, std::string ext) { ext.insert(0, "."); ext.insert(0, getName(a)); return getPath(ext); } static sf::Texture& getTexture(Asset a) { auto& t = textures[a]; if (t) return *t; t = new sf::Texture; const bool loaded = t->loadFromFile(getPath(a, "png")); assert(loaded); return *t; } private: static std::map<Asset, sf::Texture*> textures; }; decltype(Assets::textures) Assets::textures; int main() { sf::Vector2i viewSize(30, 20); const int cellSize = 32; const int maxRenderRadiusSq = squareLength(viewSize) / 4; Level level(Assets::getPath("level.map")); Player player; player.position = level.start; sf::RenderWindow win(sf::VideoMode(viewSize.x * cellSize, viewSize.y * cellSize), "Tiny World", sf::Style::Default & ~sf::Style::Resize); win.setFramerateLimit(60); while (win.isOpen()) { sf::Event event; while (win.pollEvent(event)) { if (event.type == sf::Event::Closed or (event.type == sf::Event::KeyPressed and event.key.code == sf::Keyboard::Escape)) win.close(); // TODO Menu ? else if (event.type == sf::Event::KeyPressed) { sf::Vector2i oldPos = player.position; switch (event.key.code) { case sf::Keyboard::Up: --player.position.y; break; case sf::Keyboard::Down: ++player.position.y; break; case sf::Keyboard::Left: --player.position.x; break; case sf::Keyboard::Right: ++player.position.x; break; default: continue; } for (Enemy* enemy: level.enemies) { if (player.position == enemy->position) { player.position = oldPos; std::cout << "Touched enemy" << std::endl; // TODO HitPoints } } if (player.position != oldPos) { for (Enemy* enemy: level.enemies) { const sf::Vector2i relPos(enemy->position - player.position); if (std::abs(relPos.x) > std::abs(relPos.y)) enemy->position.x += relPos.x < 0 ? +1 : -1; else if (relPos.x and relPos.y) enemy->position.y += relPos.y < 0 ? +1 : -1; } } } } win.clear(sf::Color(50, 50, 50)); // Draw map for (const Cell* cell: level.map) { const sf::Vector2i relPos(cell->position - player.position); if (squareLength(relPos) < maxRenderRadiusSq) { sf::Sprite sprite(Assets::getTexture(cell->asset)); sprite.move(viewSize.x / 2 * cellSize, viewSize.y / 2 * cellSize); sprite.move(relPos.x * cellSize, relPos.y * cellSize); win.draw(sprite); } } // Draw enemies for (const Enemy* enemy: level.enemies) { const sf::Vector2i relPos(enemy->position - player.position); if (squareLength(relPos) < maxRenderRadiusSq) { sf::Sprite sprite(Assets::getTexture(enemy->asset)); sprite.move(viewSize.x / 2 * cellSize, viewSize.y / 2 * cellSize); sprite.move(relPos.x * cellSize, relPos.y * cellSize); win.draw(sprite); } } { // Draw Player sf::Sprite sprite(Assets::getTexture(Asset::Player)); sprite.move((viewSize.x / 2) * cellSize, (viewSize.y / 2) * cellSize); win.draw(sprite); } win.display(); } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include "tcp_server.h" int main(int argc, char** argv) { Akumuli::Logger logger("test", 10); logger.info() << "Info"; for (int i = 0; i < 10; i++) logger.trace() << "Trace msg " << i; logger.error() << "Hello " << "world"; return 0; } <commit_msg>WIP: main executable<commit_after>#include "tcp_server.h" #include <iostream> #include <boost/program_options.hpp> #include <apr_errno.h> namespace po=boost::program_options; using namespace Akumuli; static void static_logger(int tag, const char * msg) { static Logger logger = Logger("Main", 32); logger.error() << msg; } void create_db(const char* name, const char* path, int32_t nvolumes, uint32_t compression_threshold, uint64_t window_size, uint32_t max_cache_size) { auto status = aku_create_database(name, path, path, nvolumes, compression_threshold, window_size, max_cache_size, &static_logger); if (status != AKU_SUCCESS) { std::cout << "Error creating database" << std::endl; char buffer[1024]; apr_strerror(status, buffer, 1024); std::cout << buffer << std::endl; } else { std::cout << "Database created" << std::endl; std::cout << "- path: " << path << std::endl; std::cout << "- name: " << name << std::endl; } } void run_server(std::string path) { auto connection = std::make_shared<AkumuliConnection>(path.c_str(), false, AkumuliConnection::MaxDurability); TcpServer server(connection, 4); server.start(); server.wait(); server.stop(); } int main(int argc, char** argv) { po::options_description desc("Akumuli options"); desc.add_options() ("help", "Produce help message") ("path", po::value<std::string>(), "Path to database files") ("create", "Create database") ("name", po::value<std::string>(), "Database name (create)") ("nvolumes", po::value<int32_t>(), "Number of volumes to create (create)") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; return 0; } if (!vm.count("path")) { std::cout << desc << std::endl; return -1; } std::string path = vm["path"].as<std::string>(); if (vm.count("create") == 0) { run_server(path); } else { if (vm.count("nvolumes") == 0 || vm.count("name") == 0) { std::cout << desc << std::endl; return -1; } std::string name = vm["name"].as<std::string>(); int32_t nvol = vm["nvolumes"].as<int32_t>(); create_db(name.c_str(), path.c_str(), nvol, 10000, 100000, 100000); // TODO: use correct numbers } return 0; } <|endoftext|>
<commit_before> //@HEADER // *************************************************** // // HPCG: High Performance Conjugate Gradient Benchmark // // Contact: // Michael A. Heroux ( maherou@sandia.gov) // Jack Dongarra (dongarra@eecs.utk.edu) // Piotr Luszczek (luszczek@eecs.utk.edu) // // *************************************************** //@HEADER #ifndef HPCG_NO_MPI #include <mpi.h> #endif #ifndef HPCG_NO_OPENMP #include <omp.h> #endif #ifdef _WIN32 const char* NULLDEVICE="nul"; #else const char* NULLDEVICE="/dev/null"; #endif #include <ctime> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include "hpcg.hpp" #include "ReadHpcgDat.hpp" std::ofstream HPCG_fout; //!< output file stream for logging activities during HPCG run static int startswith(const char * s, const char * prefix) { size_t n = strlen( prefix ); if (strncmp( s, prefix, n )) return 0; return 1; } /*! Initializes an HPCG run by obtaining problem parameters (from a file or command line) and then broadcasts them to all nodes. It also initializes login I/O streams that are used throughout the HPCG run. Only MPI rank 0 performs I/O operations. The function assumes that MPI has already been initialized for MPI runs. @param[in] argc_p the pointer to the "argc" parameter passed to the main() function @param[in] argv_p the pointer to the "argv" parameter passed to the main() function @param[out] params the reference to the data structures that is filled the basic parameters of the run @return returns 0 upon success and non-zero otherwise @see HPCG_Finalize */ int HPCG_Init(int * argc_p, char ** *argv_p, HPCG_Params & params) { int argc = *argc_p; char ** argv = *argv_p; char fname[80]; int i, j, *iparams; char cparams[][6] = {"--nx=", "--ny=", "--nz=", "--rt=", "--pz=", "--zl=", "--zu="}; time_t rawtime; tm * ptm; const int nparams = (sizeof cparams) / (sizeof cparams[0]); bool broadcastParams = false; // Make true if parameters read from file. iparams = (int *)malloc(sizeof(int) * nparams); // Initialize iparams for (i = 0; i < nparams; ++i) iparams[i] = 0; /* for sequential and some MPI implementations it's OK to read first three args */ for (i = 0; i < nparams; ++i) if (argc <= i+1 || sscanf(argv[i+1], "%d", iparams+i) != 1 || iparams[i] < 10) iparams[i] = 0; /* for some MPI environments, command line arguments may get complicated so we need a prefix */ for (i = 1; i <= argc && argv[i]; ++i) for (j = 0; j < nparams; ++j) if (startswith(argv[i], cparams[j])) if (sscanf(argv[i]+strlen(cparams[j]), "%d", iparams+j) != 1) iparams[j] = 0; // Check if --rt was specified on the command line int * rt = iparams+3; // Assume runtime was not specified and will be read from the hpcg.dat file if (! iparams[3]) rt = 0; // If --rt was specified, we already have the runtime, so don't read it from file if (! iparams[0] && ! iparams[1] && ! iparams[2]) { /* no geometry arguments on the command line */ ReadHpcgDat(iparams, rt); broadcastParams = true; } // Check for small or unspecified nx, ny, nz values // If any dimension is less than 16, make it the max over the other two dimensions, or 16, whichever is largest for (i = 0; i < 3; ++i) { if (iparams[i] < 16) for (j = 1; j <= 2; ++j) if (iparams[(i+j)%3] > iparams[i]) iparams[i] = iparams[(i+j)%3]; if (iparams[i] < 16) iparams[i] = 16; } // Broadcast values of iparams to all MPI processes #ifndef HPCG_NO_MPI if (broadcastParams) { MPI_Bcast( iparams, nparams, MPI_INT, 0, MPI_COMM_WORLD ); } #endif params.nx = iparams[0]; params.ny = iparams[1]; params.nz = iparams[2]; params.runningTime = iparams[3]; params.pz = iparams[4]; params.zl = iparams[5]; params.zu = iparams[6]; #ifndef HPCG_NO_MPI MPI_Comm_rank( MPI_COMM_WORLD, &params.comm_rank ); MPI_Comm_size( MPI_COMM_WORLD, &params.comm_size ); #else params.comm_rank = 0; params.comm_size = 1; #endif #ifdef HPCG_NO_OPENMP params.numThreads = 1; #else #pragma omp parallel params.numThreads = omp_get_num_threads(); #endif // for (i = 0; i < nparams; ++i) std::cout << "rank = "<< params.comm_rank << " iparam["<<i<<"] = " << iparams[i] << "\n"; time ( &rawtime ); ptm = localtime(&rawtime); sprintf( fname, "hpcg_log_%04d.%02d.%02d.%02d.%02d.%02d.txt", 1900 + ptm->tm_year, ptm->tm_mon+1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec ); if (0 == params.comm_rank) { HPCG_fout.open(fname); } else { #if defined(HPCG_DEBUG) || defined(HPCG_DETAILED_DEBUG) char local[15]; sprintf( local, "%d_", params.comm_rank ); sprintf( fname, "hpcg_log_%s%04.d%02d.%02d.%02d.%02d.%02d.txt", local, 1900 + ptm->tm_year, ptm->tm_mon+1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec ); HPCG_fout.open(fname); #else HPCG_fout.open(NULLDEVICE); #endif } free( iparams ); return 0; } <commit_msg>Increase parameter name size to prepare for new ones<commit_after> //@HEADER // *************************************************** // // HPCG: High Performance Conjugate Gradient Benchmark // // Contact: // Michael A. Heroux ( maherou@sandia.gov) // Jack Dongarra (dongarra@eecs.utk.edu) // Piotr Luszczek (luszczek@eecs.utk.edu) // // *************************************************** //@HEADER #ifndef HPCG_NO_MPI #include <mpi.h> #endif #ifndef HPCG_NO_OPENMP #include <omp.h> #endif #ifdef _WIN32 const char* NULLDEVICE="nul"; #else const char* NULLDEVICE="/dev/null"; #endif #include <ctime> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include "hpcg.hpp" #include "ReadHpcgDat.hpp" std::ofstream HPCG_fout; //!< output file stream for logging activities during HPCG run static int startswith(const char * s, const char * prefix) { size_t n = strlen( prefix ); if (strncmp( s, prefix, n )) return 0; return 1; } /*! Initializes an HPCG run by obtaining problem parameters (from a file or command line) and then broadcasts them to all nodes. It also initializes login I/O streams that are used throughout the HPCG run. Only MPI rank 0 performs I/O operations. The function assumes that MPI has already been initialized for MPI runs. @param[in] argc_p the pointer to the "argc" parameter passed to the main() function @param[in] argv_p the pointer to the "argv" parameter passed to the main() function @param[out] params the reference to the data structures that is filled the basic parameters of the run @return returns 0 upon success and non-zero otherwise @see HPCG_Finalize */ int HPCG_Init(int * argc_p, char ** *argv_p, HPCG_Params & params) { int argc = *argc_p; char ** argv = *argv_p; char fname[80]; int i, j, *iparams; char cparams[][7] = {"--nx=", "--ny=", "--nz=", "--rt=", "--pz=", "--zl=", "--zu="}; time_t rawtime; tm * ptm; const int nparams = (sizeof cparams) / (sizeof cparams[0]); bool broadcastParams = false; // Make true if parameters read from file. iparams = (int *)malloc(sizeof(int) * nparams); // Initialize iparams for (i = 0; i < nparams; ++i) iparams[i] = 0; /* for sequential and some MPI implementations it's OK to read first three args */ for (i = 0; i < nparams; ++i) if (argc <= i+1 || sscanf(argv[i+1], "%d", iparams+i) != 1 || iparams[i] < 10) iparams[i] = 0; /* for some MPI environments, command line arguments may get complicated so we need a prefix */ for (i = 1; i <= argc && argv[i]; ++i) for (j = 0; j < nparams; ++j) if (startswith(argv[i], cparams[j])) if (sscanf(argv[i]+strlen(cparams[j]), "%d", iparams+j) != 1) iparams[j] = 0; // Check if --rt was specified on the command line int * rt = iparams+3; // Assume runtime was not specified and will be read from the hpcg.dat file if (! iparams[3]) rt = 0; // If --rt was specified, we already have the runtime, so don't read it from file if (! iparams[0] && ! iparams[1] && ! iparams[2]) { /* no geometry arguments on the command line */ ReadHpcgDat(iparams, rt); broadcastParams = true; } // Check for small or unspecified nx, ny, nz values // If any dimension is less than 16, make it the max over the other two dimensions, or 16, whichever is largest for (i = 0; i < 3; ++i) { if (iparams[i] < 16) for (j = 1; j <= 2; ++j) if (iparams[(i+j)%3] > iparams[i]) iparams[i] = iparams[(i+j)%3]; if (iparams[i] < 16) iparams[i] = 16; } // Broadcast values of iparams to all MPI processes #ifndef HPCG_NO_MPI if (broadcastParams) { MPI_Bcast( iparams, nparams, MPI_INT, 0, MPI_COMM_WORLD ); } #endif params.nx = iparams[0]; params.ny = iparams[1]; params.nz = iparams[2]; params.runningTime = iparams[3]; params.pz = iparams[4]; params.zl = iparams[5]; params.zu = iparams[6]; #ifndef HPCG_NO_MPI MPI_Comm_rank( MPI_COMM_WORLD, &params.comm_rank ); MPI_Comm_size( MPI_COMM_WORLD, &params.comm_size ); #else params.comm_rank = 0; params.comm_size = 1; #endif #ifdef HPCG_NO_OPENMP params.numThreads = 1; #else #pragma omp parallel params.numThreads = omp_get_num_threads(); #endif // for (i = 0; i < nparams; ++i) std::cout << "rank = "<< params.comm_rank << " iparam["<<i<<"] = " << iparams[i] << "\n"; time ( &rawtime ); ptm = localtime(&rawtime); sprintf( fname, "hpcg_log_%04d.%02d.%02d.%02d.%02d.%02d.txt", 1900 + ptm->tm_year, ptm->tm_mon+1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec ); if (0 == params.comm_rank) { HPCG_fout.open(fname); } else { #if defined(HPCG_DEBUG) || defined(HPCG_DETAILED_DEBUG) char local[15]; sprintf( local, "%d_", params.comm_rank ); sprintf( fname, "hpcg_log_%s%04.d%02d.%02d.%02d.%02d.%02d.txt", local, 1900 + ptm->tm_year, ptm->tm_mon+1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec ); HPCG_fout.open(fname); #else HPCG_fout.open(NULLDEVICE); #endif } free( iparams ); return 0; } <|endoftext|>