コード例 #1
0
ファイル: CDomain.cpp プロジェクト: schdomin/diffusion_pse
void CDomain::saveMeshToPNG( const unsigned int& p_dCurrentTimeStep, const unsigned int& p_uRate )
{
    //ds if the current step matches the rate
    if( 0 == p_dCurrentTimeStep%p_uRate )
    {
        //ds get mesh size
        const unsigned int uMeshSize( 2*m_uNumberOfGridPoints1D );

        //ds get the data
        unsigned char* chMesh( getP2M( uMeshSize ) );

        //ds construct picture name - buffer for snprintf
        char chBuffer[64];

        //ds format: image_number.png
        std::snprintf( chBuffer, 64, "bin/image_%.4u.png", m_uNumberOfImagesSaved );

        //ds create png
        writePNG( chBuffer, uMeshSize, uMeshSize, chMesh );

        //ds free data
        delete chMesh;

        //ds increase counter
        ++m_uNumberOfImagesSaved;
    }
}
コード例 #2
0
ファイル: qrimage.c プロジェクト: wxxweb/w2x
QRimageResultType QRimage_writeImage(
	QRcode *qrcode,
	const char *outfile,
	QRimageType imagetype
	)
{
	if (!qrcode) {
		return QR_IMG_QRCODE_IS_NULL;
	}
	switch(imagetype) {
		case QR_IMG_PNG:
			return writePNG(qrcode, outfile);
		case QR_IMG_EPS:
			return writeEPS(qrcode, outfile);
		case QR_IMG_SVG:
			return writeSVG(qrcode, outfile);
		case QR_IMG_ANSI:
			return writeANSI(qrcode, outfile, 0);
		case QR_IMG_ANSI256:
			return writeANSI(qrcode, outfile, 1);
		case QR_IMG_ASCIIi:
			return writeASCII(qrcode, outfile,  1);
		case QR_IMG_ASCII:
			return writeASCII(qrcode, outfile,  0);
		case QR_IMG_UTF8:
			return writeUTF8(qrcode, outfile, 0);
		case QR_IMG_ANSIUTF8:
			return writeUTF8(qrcode, outfile, 1);
		default:
			return QR_IMG_UNKNOW_IMAGE_TYPE;
	}
	return QR_IMG_SUCCESS;
}
コード例 #3
0
ファイル: image.hpp プロジェクト: Hsaniva/apitrace
 inline bool
 writePNG(const char *filename) const {
     std::ofstream os(filename, std::ofstream::binary);
     if (!os) {
         return false;
     }
     return writePNG(os);
 }
コード例 #4
0
ファイル: image_png.cpp プロジェクト: Dhanasekahar/apitrace
bool
Image::writePNG(const char *filename, bool strip_alpha) const
{
    std::ofstream os(filename, std::ofstream::binary);
    if (!os) {
        return false;
    }
    return writePNG(os, strip_alpha);
}
コード例 #5
0
ファイル: qrenc.c プロジェクト: OldFrank/qrencode
static void qrencode(const char *intext, const char *outfile)
{
	QRcode *qrcode;
	
	qrcode = encode(intext);
	if(qrcode == NULL) {
		perror("Failed to encode the input data:");
		exit(EXIT_FAILURE);
	}
	writePNG(qrcode, outfile);
	QRcode_free(qrcode);
}
コード例 #6
0
ファイル: quricol.cpp プロジェクト: stievie/Martis
void WINAPI GeneratePNGW(LPWSTR fileName, LPWSTR text, int margin, int size)
{
	if (text == NULL)
		return;

	QRcode* qrcode = MakeCode(text);
	if (qrcode == NULL)
		return;

	writePNG(qrcode, fileName, margin, size);

	QRcode_free(qrcode);
}
コード例 #7
0
ファイル: renderpoly.c プロジェクト: MaChao5/pdfviewer-win32
void save_two_bitmaps(intbbox_t*b, unsigned char*data1, unsigned char*data2, char*filename)
{
    int width8 = (b->width+7) >> 3;
    unsigned char*data = malloc_safe(b->width*b->height*4*4);
    unsigned char*p = data;
    int x,y;
    unsigned char*b1 = data1;
    unsigned char*b2 = data2;
    compare_bitmaps(b, data1, data2);
//#   define MARK ((abs(x-badx)<3 && abs(y-bady)<3)*255)
#define MARK 0
    for(y=0;y<b->height;y++) {
        for(x=0;x<b->width;x++) {
            unsigned char c1 = (b1[x>>3]&(0x80>>(x&7)))?255:0;
            unsigned char c2 = (b2[x>>3]&(0x80>>(x&7)))?255:0;
            *p++ = 255;
            *p++ = c1^c2;
            *p++ = c1^c2;
            *p++ = MARK;
        }
        for(x=0;x<b->width;x++) {
            unsigned char c = (b2[x>>3]&(0x80>>(x&7)))?255:0;
            *p++ = 255;
            *p++ = c;
            *p++ = c;
            *p++ = MARK;
        }
        b1 += width8;
        b2 += width8;
    }
    b1 = data1;
    for(y=0;y<b->height;y++) {
        for(x=0;x<b->width;x++) {
            unsigned char c = (b1[x>>3]&(0x80>>(x&7)))?255:0;
            *p++ = 255;
            *p++ = c;
            *p++ = c;
            *p++ = MARK;
        }
        for(x=0;x<b->width;x++) {
            *p++ = 255;
            *p++ = 0;
            *p++ = 0;
            *p++ = 0;
        }
        b1 += width8;
    }
    writePNG(filename, data, b->width*2, b->height*2);
    free(data);
}
コード例 #8
0
ファイル: qrencode.c プロジェクト: flybird119/simplehttp
static int
qrencode(const char *intext)
{
    QRcode *qrcode;
    int ret;

    qrcode = encode(intext);
    if(qrcode == NULL) {
        perror("Failed to encode the input data:");
        exit(EXIT_FAILURE);
    }
    ret = writePNG(qrcode);
    QRcode_free(qrcode);
    return ret;
}
コード例 #9
0
ファイル: qrenc.c プロジェクト: binape/ybb-apitool
static void qrencode(const unsigned char *intext, int length, const char *outfile)
{
	QRcode *qrcode;
	
	qrcode = encode(intext, length);
	if(qrcode == NULL) {
		perror("Failed to encode the input data");
		exit(EXIT_FAILURE);
	}

	if(verbose) {
		fprintf(stderr, "File: %s, Version: %d\n", (outfile!=NULL)?outfile:"(stdout)", qrcode->version);
	}

	switch(image_type) {
		case PNG_TYPE:
			writePNG(qrcode, outfile);
			break;
		case EPS_TYPE:
			writeEPS(qrcode, outfile);
			break;
		case SVG_TYPE:
			writeSVG(qrcode, outfile);
			break;
		case ANSI_TYPE:
		case ANSI256_TYPE:
			writeANSI(qrcode, outfile);
			break;
		case ASCIIi_TYPE:
			writeASCII(qrcode, outfile,  1);
			break;
		case ASCII_TYPE:
			writeASCII(qrcode, outfile,  0);
			break;
		case UTF8_TYPE:
			writeUTF8(qrcode, outfile, 0);
			break;
		case ANSIUTF8_TYPE:
			writeUTF8(qrcode, outfile, 1);
			break;
		default:
			fprintf(stderr, "Unknown image type.\n");
			exit(EXIT_FAILURE);
	}

	QRcode_free(qrcode);
}
コード例 #10
0
ファイル: qrenc.c プロジェクト: OldFrank/qrencode
static void qrencodeStructured(const char *intext, const char *outfile)
{
	QRcode_List *qrlist, *p;
	char filename[FILENAME_MAX];
	char *base, *q, *suffix = NULL;
	int i = 1;

	base = strdup(outfile);
	if(base == NULL) {
		fprintf(stderr, "Failed to allocate memory.\n");
		exit(EXIT_FAILURE);
	}
	if(strlen(base) > 4) {
		q = base + strlen(base) - 4;
		if(strcasecmp(".png", q) == 0) {
			suffix = strdup(q);
			*q = '\0';
		}
	}
	
	qrlist = encodeStructured(intext);
	if(qrlist == NULL) {
		perror("Failed to encode the input data:");
		exit(EXIT_FAILURE);
	}

	for(p = qrlist; p != NULL; p = p->next) {
		if(p->code == NULL) {
			fprintf(stderr, "Failed to encode the input data.\n");
			exit(EXIT_FAILURE);
		}
		if(suffix) {
			snprintf(filename, FILENAME_MAX, "%s-%02d%s", base, i, suffix);
		} else {
			snprintf(filename, FILENAME_MAX, "%s-%02d", base, i);
		}
		writePNG(p->code, filename);
		i++;
	}

	free(base);
	if(suffix) {
		free(suffix);
	}

	QRcode_List_free(qrlist);
}
コード例 #11
0
ファイル: qrenc.c プロジェクト: moshen/libqrencode
static void qrencode(const unsigned char *intext, int length, const char *outfile)
{
	QRcode *qrcode;
	
	qrcode = encode(intext, length);
	if(qrcode == NULL) {
		perror("Failed to encode the input data");
		exit(EXIT_FAILURE);
	}
	switch(image_type) {
		case PNG_TYPE: 
			writePNG(qrcode, outfile);
			break;
		case EPS_TYPE: 
			writeEPS(qrcode, outfile);
			break;
		default:
			fprintf(stderr, "Unknown image type.\n");
			exit(EXIT_FAILURE);
	}
	QRcode_free(qrcode);
}
コード例 #12
0
ファイル: image.cpp プロジェクト: Mikegrann/flood-fill
void Image::write(std::string filepath){
    ASSERT(loaded, "You didn't load the image!");
    ASSERT(path != INVALID_PATH, "You didn't provide a path for the Image");

    INFO("Writing image " << filepath << "...");

    std::string ext = getFileExtension(filepath);

    bool success = false;

    if(ext == BMP_EXT){
        unsigned int rc = writeBMP(filepath);
        if(!rc) success = true;
    }
    else if (ext == PNG_EXT){
        unsigned int rc = writePNG(filepath);
        if(!rc) success = true;
    }

    ASSERT(success, "Failed to write image " << filepath << "!");
    INFO("Image wrote " << filepath << "!");
}
コード例 #13
0
ファイル: NAnim.cpp プロジェクト: Aliandrana/SuperPlay
bool NAnim::save(const std::string& _strPNGFilename, const std::string& _strXMLFilename)
{
	if (false == File::createDirectory(Functions::getDirectoryFromPath(_strPNGFilename)))
	{
		return	false;
	}

	if (false == writePNG(_strPNGFilename))
	{
		return	false;
	}

	if (false == File::createDirectory(Functions::getDirectoryFromPath(_strXMLFilename)))
	{
		return	false;
	}

	if (false == writeXML(_strPNGFilename, _strXMLFilename))
	{
		return	false;
	}

	return	true;
}
コード例 #14
0
ファイル: raytrace.c プロジェクト: wito/raytrace
int main (int argc, const char **argv, const char **env) {
  Light *light = malloc(sizeof(Light));

  light->location = vectorCreate(0.0, 10.0, 10.0);
  light->color = vectorCreate(1.0, 1.0, 1.0);
  light->intensity = 1.0;

  Light **lights = calloc(3, sizeof(Light*));

  lights[0] = light;

  light = malloc(sizeof(Light));

  light->location = vectorCreate(0.0, 3.0, 10.0);
  light->color = vectorCreate(1.0, 0.4, 1.0);
  light->intensity = 1.0;

  lights[1] = light;

  Primitive **primitives = calloc(10,sizeof(Primitive *));

  primitives[0] = createSphere((vector){3.0, 7.0, 2.0}, 2.0);
  primitives[1] = createSphere((vector){0.0, 10.0, 1.9}, 1.9);
  primitives[2] = createPlane(vectorCreate(0.0, 0.0, 1.0), vectorCreate(0.0, 0.0, 0.0));

  primitives[0]->material = malloc(sizeof(Material));
  primitives[1]->material = malloc(sizeof(Material));
  primitives[2]->material = malloc(sizeof(Material));

  primitives[0]->material->color = vectorCreate(1.0, 1.0, 1.0);
  primitives[1]->material->color = vectorCreate(1.0, 1.0, 1.0);
  primitives[2]->material->color = vectorCreate(0.0, 0.7, 0.0);

  primitives[0]->material->specular = 0.7;
  primitives[1]->material->specular = 0.3;
  primitives[2]->material->specular = 0.0;

  primitives[0]->material->diffuse = 1.0;
  primitives[1]->material->diffuse = 0.5;
  primitives[2]->material->diffuse = 1.0;

  primitives[0]->material->reflection = 0.5;
  primitives[1]->material->reflection = 0.5;
  primitives[2]->material->reflection = 0.0;
  
  primitives[0]->material->refraction = 0.0;
  primitives[1]->material->refraction = 1.1;
  primitives[2]->material->refraction = 0.0;
  
  primitives[0]->material->transparency = 0.0;
  primitives[1]->material->transparency = 0.7;
  primitives[2]->material->transparency = 0.0;
  
  primitives[3] = createPlane(vectorCreate(0.0, -1.0, 0.0), vectorCreate(0.0, 15.0, 0.0));
  primitives[3]->material = malloc(sizeof(Material));
  
  primitives[3]->material->color = vectorCreate(0.3, 0.2, 7.0);
  
  primitives[3]->material->specular = 0.0;
  primitives[3]->material->diffuse  = 1.0;
  primitives[3]->material->reflection = 0.0;
  primitives[3]->material->refraction = 0.0;
  primitives[3]->material->transparency = 0.0;

  vector camera = vectorCreate(0.0, -5.0, 5.0);

  png_uint_32 height = HEIGHT, width = WIDTH;

  png_bytepp imageBuffer = malloc(sizeof(png_bytep) * height);
  for (png_uint_32 i = 0; i < height; i++) {
    imageBuffer[i] = malloc(sizeof(png_byte) * 3 * width);
    for (png_uint_32 j = 0; j < width * 3; j++) {
      imageBuffer[i][j] = 0;
    }
  }
  
  int x,y;

  for (y = 0; y < HEIGHT; y++) {
    
    for (x = 0; x < WIDTH; x++) {
      Line *ray = createLine(camera, x, y);

      vector color = rayTrace(ray, primitives, lights, 1.0);
      
      free(ray);
      
      if (color.x >= 1.0) color.x = 1.0;
      if (color.y >= 1.0) color.y = 1.0;
      if (color.z >= 1.0) color.z = 1.0;
      
      imageBuffer[y][x * 3] = color.x * 255;
      imageBuffer[y][x * 3 + 1] = color.y * 255;
      imageBuffer[y][x * 3 + 2] = color.z * 255;
    }
  
  }
  
  writePNG(imageBuffer, width, height, 0);
    
  for (png_uint_32 i = 0; i < height; i++) {
    free(imageBuffer[i]);
  }    
  free(imageBuffer);

  return 0;
}
コード例 #15
0
ファイル: ScreenShooter.cpp プロジェクト: AnsonX10/bitfighter
// Thanks to the good developers of naev for excellent code to base this off of.
// Much was copied directly.
void ScreenShooter::saveScreenshot(UIManager *uiManager, GameSettings *settings, string filename)
{
   string folder = settings->getFolderManager()->getScreenshotDir();

   // Let's find a filename to use
   makeSureFolderExists(folder);

   string fullFilename;
   S32 ctr = 0;

   if(filename == "")
   {
      while(true)    // Settle in for the long haul, boys.  This seems crazy...
      {
         fullFilename = joindir(folder, "screenshot_" + itos(ctr++) + ".png");

         if(!fileExists(fullFilename))
            break;
      }
   }
   else
      fullFilename = joindir(folder, filename + ".png");

   // We default to resizing the opengl viewport to the standard canvas size, unless we're
   // in the editor or our window is smaller than the canvas size
   bool doResize = (!uiManager->isCurrentUI<EditorUserInterface>()) &&
                     DisplayManager::getScreenInfo()->getWindowWidth() > DisplayManager::getScreenInfo()->getGameCanvasWidth();

   // Change opengl viewport temporarily to have consistent screenshot sizes
   if(doResize)
      resizeViewportToCanvas(uiManager);

   // Now let's grab them pixels
   S32 width;
   S32 height;

   // If we're resizing, use the default canvas size
   if(doResize)
   {
      width  = DisplayManager::getScreenInfo()->getGameCanvasWidth();
      height = DisplayManager::getScreenInfo()->getGameCanvasHeight();
   }
   // Otherwise just take the window size
   else
   {
      width  = DisplayManager::getScreenInfo()->getWindowWidth();
      height = DisplayManager::getScreenInfo()->getWindowHeight();
   }

   // Allocate buffer  GLubyte == U8
   U8 *screenBuffer = new U8[BytesPerPixel * width * height];  // Glubyte * 3 = 24 bits
   png_bytep *rows = new png_bytep[height];

   // Set alignment at smallest for compatibility
   mGL->glPixelStore(GLOPT::PackAlignment, 1);

   // Grab the front buffer with the new viewport
#ifndef BF_USE_GLES
   // GLES doesn't need this?
   mGL->glReadBuffer(GLOPT::Back);
#endif

   // Read pixels from buffer - slow operation
   mGL->glReadPixels(0, 0, width, height, GLOPT::Rgb, GLOPT::UnsignedByte, screenBuffer);

   // Change opengl viewport back to what it was
   if(doResize)
      restoreViewportToWindow(settings);

   // Convert Data
   for (S32 i = 0; i < height; i++)
      rows[i] = &screenBuffer[(height - i - 1) * (BytesPerPixel * width)];  // Backwards!

   // Write the PNG!
   if(!writePNG(fullFilename.c_str(), rows, width, height, PNG_COLOR_TYPE_RGB, BitDepth))
      logprintf(LogConsumer::LogError, "Creating screenshot failed!!");

   // Clean up
   delete [] rows;
   delete [] screenBuffer;
}
コード例 #16
0
/**
 * This is the main loop for the program.  It is given a reference image and
 * the size, as well as various parameters used to define polygon type,
 * how many to use, and the target difference percentage.
 */
static void main_loop(Color_t *original, int width, int height,
        int n_points, int n_polygons, double target_percentage)
{
    int old_diff = -1;
    unsigned int new_diff;
    unsigned int n_used, n_tried;
    unsigned int max_diff;
    double current_percent = 0.0f;
    char output[64];
    Color_t *temporary;
    Color_t *canvas;

    n_used = n_tried = 0;

    /* The most different a test image can be. */
    max_diff = MAX_COLOR_VALUE * (unsigned int)width * (unsigned int)height * 3;

    /* Allocate the buffers used--one for a temporary buffer, and one for
     * holding our work-in-progress. */
    temporary = malloc(width * height * sizeof(Color_t));
    if (!temporary)
        abort_("Unable to allocate temporary buffer.\n");

    canvas = malloc(width * height * sizeof(Color_t));
    if (!canvas)
        abort_("Unable to allocate canvas buffer.\n");

    /* Start with a blank canvas. */
    clearCanvas(canvas, width, height);

    do {
        n_tried++;

        /* Generate a randomly-colored polygon. */
        Color_t color = getRandomColor();
        Polygon_t polygon = getRandomPolygon(width, height, n_points);

        /* Create the temporary canvas by starting with the current work in
         * progress. */
        memcpy(temporary, canvas, width*height*sizeof(Color_t));

        /* Generate a random weighting to use for merging in the new polygon. */
        double weight = drandrange(0.25, 0.75);

        /* Add a polygon. */
        drawPolygon(temporary, width, height, polygon, n_points, color, weight);

        /* Compare to the original. */
        new_diff = isSecondOneBetter(original, temporary, width, height, old_diff);
        if (new_diff < 0)
            continue;

        /* If we've improved, keep the new version */
        if (old_diff < 0 || new_diff < old_diff) {
            n_used++;
            current_percent =
                100.0f - ((100.0f * (double)new_diff) / (double)max_diff);

            printf("%d / %d (tested %d) -- %.02f%% (Weight %2.2f)\n",
                    n_used, n_polygons, n_tried, current_percent, weight);

            memcpy(canvas, temporary, width*height*sizeof(Color_t));
            old_diff = new_diff;
            sprintf(output, "./out/img_%d.png", n_used);
            writePNG(output, canvas, width, height);

            if (current_percent > target_percentage && target_percentage > 0.0f)
                break;
        }
    } while (n_used < n_polygons);

    free(temporary);
    free(canvas);
}
コード例 #17
0
ファイル: pngread.c プロジェクト: thananon/class_project
int main(int argc,char **argv){
	int width,height;
	int **pixel;
	int **out;
	float **tmp;
	pixel = readPNG(argv[1],&width,&height);
	
	writePNG("res_original.png",pixel,width,height);

	out = histEQ(pixel,width,height);
	writePNG("res_Equalized.png",out,width,height);
	FREE_PIXEL(out);

	out = getNegative(pixel,width,height);
	writePNG("res_Negative.png",out,width,height);
	FREE_PIXEL(out);

	out = halfIntensity(pixel,width,height);
	writePNG("res_HalfI.png",out,width,height);
	FREE_PIXEL(out);
	
	out = IRescale(pixel,width,height,min,max,0,100);
	writePNG("res_scaleto0100.png",out,width,height);
	FREE_PIXEL(out);

	out = IRescale(pixel,width,height,min,max,200,255);
	writePNG("res_scaleto200255.png",out,width,height);
	FREE_PIXEL(out);

	tmp = getExp(pixel,width,height,20,1.01);
	out = Normalize(tmp,width,height);
	writePNG("res_exp.png",out,width,height);
	FREE_PIXEL(out);

	tmp = getLog(pixel,width,height,20.2);
	out = Normalize(tmp,width,height);
	writePNG("res_log.png",out,width,height);
	FREE_PIXEL(out);
	
	tmp = getPower(pixel,width,height,1,0.5);
	out = Normalize(tmp,width,height);
	writePNG("res_powerg05.png",out,width,height);
	FREE_PIXEL(out);
	
	tmp = getPower(pixel,width,height,1,2);
	out = Normalize(tmp,width,height);
	writePNG("res_powerg2.png",out,width,height);
	FREE_PIXEL(out);

	tmp = getPower(pixel,width,height,1,2.5);
	out = Normalize(tmp,width,height);
	writePNG("res_powerg25.png",out,width,height);
	FREE_PIXEL(out);
	//printHist(out,width,height);

	free(pixel);
return 0;
}
コード例 #18
0
ファイル: qrenc.c プロジェクト: moshen/libqrencode
static void qrencodeStructured(const unsigned char *intext, int length, const char *outfile)
{
	QRcode_List *qrlist, *p;
	char filename[FILENAME_MAX];
	char *base, *q, *suffix = NULL;
	const char *type_suffix;
	int i = 1;
	int suffix_size;

	switch(image_type) {
		case PNG_TYPE: 
			type_suffix = ".png";
			break;
		case EPS_TYPE: 
			type_suffix = ".eps";
			break;
		default:
			fprintf(stderr, "Unknown image type.\n");
			exit(EXIT_FAILURE);
	}

	base = strdup(outfile);
	if(base == NULL) {
		fprintf(stderr, "Failed to allocate memory.\n");
		exit(EXIT_FAILURE);
	}
	suffix_size = strlen(type_suffix);
	if(strlen(base) > suffix_size) {
		q = base + strlen(base) - suffix_size;
		if(strcasecmp(type_suffix, q) == 0) {
			suffix = strdup(q);
			*q = '\0';
		}
	}
	
	qrlist = encodeStructured(intext, length);
	if(qrlist == NULL) {
		perror("Failed to encode the input data");
		exit(EXIT_FAILURE);
	}

	for(p = qrlist; p != NULL; p = p->next) {
		if(p->code == NULL) {
			fprintf(stderr, "Failed to encode the input data.\n");
			exit(EXIT_FAILURE);
		}
		if(suffix) {
			snprintf(filename, FILENAME_MAX, "%s-%02d%s", base, i, suffix);
		} else {
			snprintf(filename, FILENAME_MAX, "%s-%02d", base, i);
		}
		switch(image_type) {
			case PNG_TYPE: 
				writePNG(p->code, filename);
				break;
			case EPS_TYPE: 
				writeEPS(p->code, filename);
				break;
			default:
				fprintf(stderr, "Unknown image type.\n");
				exit(EXIT_FAILURE);
		}
		i++;
	}

	free(base);
	if(suffix) {
		free(suffix);
	}

	QRcode_List_free(qrlist);
}
コード例 #19
0
ファイル: img.cpp プロジェクト: JonnyH/ktftd
int main(int argc, char **argv)
{
	if (argc <= 2)
	{
		printUsage();
		return EXIT_SUCCESS;
	}
	std::string fileName(argv[2]);
	std::string outputFileName = fileName.substr(0, fileName.length()-4);
	outputFileName.append(".png");
	if (argv[1][0] == 'f')
	{
		if (argc <= 5)
		{
			printUsage();
			return EXIT_SUCCESS;
		}
		std::ifstream inFile(fileName);
		ktftd::img::FontSize size;
		switch (argv[3][0])
		{
			case 's':
				size = ktftd::img::FONTSIZE_SMALL;
				break;
			case 'b':
				size = ktftd::img::FONTSIZE_BIG;
				break;
			default:
				printUsage();
				return EXIT_FAILURE;
		}
		auto font = ktftd::img::LoadFont(inFile, size);
		std::string paletteName(argv[4]);
		int paletteOffset = atoi(argv[5]);
		std::ifstream paletteFile(paletteName);
		auto palette = ktftd::img::LoadPalette(paletteFile, paletteOffset);

		for (unsigned int c = font.startASCII; c < font.endASCII; c++)
		{
			std::stringstream ss;
			ss << "char" << std::setw(3) << std::setfill('0') << c << ".png";
			auto outputImage = font.characterImages[c-font.startASCII].getImage(palette);
			outputImage.writePNG(ss.str().c_str());
		}
	}
	else if (argv[1][0] == 'i')
	{
		if (argc <= 2)
		{
			printUsage();
			return EXIT_SUCCESS;
		}


		auto spk = fileName.rfind(".SPK");
		auto bdy = fileName.rfind(".BDY");
		auto scr = fileName.rfind(".SCR");
		auto dat = fileName.rfind(".DAT");
		auto lbm = fileName.rfind(".LBM");

		bool requiresPalette;

		ktftd::img::Palette palette;
		ktftd::img::PaletteImage palettedImage;
		ktftd::img::Image outputImage;

		std::ifstream inFile(fileName);

		if (spk == fileName.length()-4)
		{
			std::cout << "Is SPK File\n";
			requiresPalette = true;
			palettedImage = ktftd::img::LoadSPKImage(inFile);
		}
		else if (bdy == fileName.length()-4)
		{
			std::cout << "Is BDY file\n";
			requiresPalette = true;
			palettedImage = ktftd::img::LoadBDYImage(inFile);
		}
		else if(scr == fileName.length()-4)
		{
			std::cout << "Is SCR file\n";
			requiresPalette = true;
			palettedImage = ktftd::img::LoadSCRImage(inFile);
		}
		else if(dat == fileName.length()-4)
		{
			std::cout << "Is DAT file\n";
			requiresPalette = true;
			//DAT files are the same as SCR
			palettedImage = ktftd::img::LoadSCRImage(inFile);
		}
		else if(lbm == fileName.length() - 4)
		{
			std::cout << "Is LBM file\n";
			requiresPalette = false;
			auto lbmFile = ktftd::img::LoadLBMImage(inFile);
			assert(lbmFile.palette);
			assert(lbmFile.image);
			outputImage = lbmFile.image->getImage(*lbmFile.palette);
		}
		else
		{
			std::cerr << "Unknown file type: \"" << fileName << "\"\n";
			printUsage();
			return EXIT_FAILURE;
		}

		if (requiresPalette)
		{
			if (argc <= 3)
			{
				printUsage();
				return EXIT_FAILURE;
			}
			std::string paletteName (argv[3]);
			auto dat = paletteName.rfind(".DAT");
			auto lbm = paletteName.rfind(".LBM");
			if (dat == paletteName.length() - 4)
			{
				std::cout << "Is dat palette\n";
				if (argc != 5)
				{
					printUsage();
					return EXIT_FAILURE;
				}
				else
				{
					int paletteOffset = atoi(argv[4]);
					std::ifstream paletteFile(paletteName);
					palette = ktftd::img::LoadPalette(paletteFile, paletteOffset);
				}
			}
			else if(lbm == paletteName.length()-4)
			{
				std::cout << "Is lbm palette\n";
				std::ifstream paletteFile(paletteName);
				auto lbmImage = ktftd::img::LoadLBMImage(paletteFile);
				palette = *lbmImage.palette;
			}
			else
			{
				std::cerr << "Unknown palette type: \"" << paletteName << "\"\n";
				printUsage();
				return EXIT_FAILURE;
			}
			outputImage = palettedImage.getImage(palette);
		}
		outputImage.writePNG(outputFileName.c_str());

	}
	else if (argv[1][0] == 'p')
	{
		if (argc < 3)
		{
			printUsage();
			return EXIT_FAILURE;
		}

		std::string paletteName(argv[2]);
		ktftd::img::Palette palette;

		if (paletteName.rfind(".LBM") == paletteName.length()-4)
		{
			std::ifstream paletteFile(paletteName);
			auto lbmImage = ktftd::img::LoadLBMImage(paletteFile);
			palette = *lbmImage.palette;
		}
		else if (paletteName.rfind(".DAT") == paletteName.length()-4)
		{
	
			if (argc != 4)
			{
				printUsage();
				return EXIT_FAILURE;
			}
			std::ifstream inFile(argv[2]);
			int paletteOffset = atoi(argv[3]);
			palette = ktftd::img::LoadPalette(inFile, paletteOffset);
		}
		else
		{
			std::cerr << "Unknown palette file type\n";
			printUsage();
			return EXIT_FAILURE;
		}
		
		auto image = palette.toImage();
		image.writePNG(outputFileName.c_str());
	}
	else
	{
		printUsage();
		return EXIT_FAILURE;
	}
}
コード例 #20
0
ファイル: tpos.c プロジェクト: michaelwille/js9
int main(int argc, char **argv)
{
  int c, i, j, got, args, jsonlen, istart;
  int odim1, odim2, blen, pad;
  int idim1=0, idim2=0, bitpix=0, ncard=0;
  int verbose=0;
  size_t totbytes, dlen;
  char tbuf[SZ_LINE];
  char *buf=NULL;
  char *jsonheader=NULL;
  char *iname=NULL, *oname=NULL;
  FILE *ofp=NULL;
  Optinfo optinfo;
#if HAVE_CFITSIO
  int status = 0;
  int n;
  int hdutype;
  int maxcard, morekeys;
  int dims[2] = {0, 0};
  int block = 1;
  void *dbuf;
  double d1, d2, d3, d4;
  double cens[2] = {0.0, 0.0};
  char *s;
  char *filter=NULL;
  char *evtlist = DEF_EVTLIST;
  char card[81];
  char s1[BUFLEN], s2[BUFLEN], s3[BUFLEN], s4[BUFLEN];
  fitsfile *fptr=NULL, *ofptr=NULL;
#elif HAVE_FUNTOOLS
  char *s=NULL;
  int dtype;
  Fun ifun=NULL, tfun=NULL;
#endif

  /* we want the args in the same order in which they arrived, and
     gnu getopt sometimes changes things without this */
  putenv("POSIXLY_CORRECT=true");

  /* process switch arguments */
  while ((c = getopt(argc, argv, "b:e:f:s:v")) != -1){
    switch(c){
    case 'b':
#if HAVE_CFITSIO
      block = atoi(optarg);
#else
      fprintf(stderr, "warning: -b switch only for cfitsio (ignoring)\n");
#endif
      break;
    case 'e':
#if HAVE_CFITSIO
      evtlist = optarg;
#else
      fprintf(stderr, "warning: -e switch only for cfitsio (ignoring)\n");
#endif
      break;
    case 'f':
#if HAVE_CFITSIO
      filter = optarg;
#else
      fprintf(stderr, "warning: -f switch only for cfitsio (ignoring)\n");
#endif
      break;
    case 's':
#if HAVE_CFITSIO
      s = strdup(optarg);
      if( strlen(s) > BUFLEN ) s[BUFLEN-1] = '\0';
      if( sscanf(s, "%[0-9.*] @ %[-0-9.*] , %[0-9.*] @ %[-0-9.*]%n",
		 s1, s2, s3, s4, &n) == 4){
	dims[0] = atof(s1);
	cens[0] = atof(s2);
	dims[1] = atof(s3);
	cens[1] = atof(s4);
      }  else if(sscanf(s, "%[-0-9.*] : %[-0-9.*] , %[-0-9.*] : %[-0-9.*]%n",
			s1, s2, s3, s4, &n) == 4){
	d1 = atof(s1);
	d2 = atof(s2);
	d3 = atof(s3);
	d4 = atof(s4);
	dims[0] = d2 - d1 + 1;
	cens[0] = dims[0] / 2;
	dims[1] = d4 - d3 + 1;
	cens[1] = dims[1] / 2;
      } else {
	fprintf(stderr, "warning: unknown arg for -s switch (ignoring)\n");
      }
      if( s ) free(s);
#else
      fprintf(stderr, "warning: -s switch only for cfitsio (ignoring)\n");
#endif
     break;
    case 'v':
      verbose++;
      break;
    }
  }

  /* check for required arguments */
  args = argc - optind;
  if( args < 2 ){
    fprintf(stderr, "usage: %s iname oname\n", argv[0]);
    exit(1);
  }
  iname = argv[optind++];
  oname = argv[optind++];

  /* optional info */
  if( !(optinfo = (Optinfo)calloc(sizeof(OptinfoRec), 1)) ){
    fprintf(stderr, "ERROR: can't allocate optional info rec\n");
    exit(1);
  }

  /* open the input FITS file */
#if HAVE_CFITSIO
  fptr = openFITSFile(iname, evtlist, &hdutype, &status);
  errchk(status);
#elif HAVE_FUNTOOLS
  if( !(ifun = FunOpen(iname, "r", NULL)) ){
    fprintf(stderr, "ERROR could not open input FITS file: %s (%s)\n", 
	    iname, strerror(errno));
    exit(1);
  }
#endif

  /* save the input filename in the png file */
  optinfo->fitsname = iname;

  /* open the output PGN file */
  if( !strcmp(oname, "-") || !strcmp(oname, "stdout") ){
    ofp = stdout;
  } else if( !(ofp = fopen(oname, "w")) ){
    fprintf(stderr, "ERROR: could not create output PNG file: %s (%s)\n", 
	    oname, strerror(errno));
    exit(1);
  }

#if HAVE_CFITSIO
  switch(hdutype){
  case IMAGE_HDU:
    // get image array
    dbuf = getImageToArray(fptr, NULL, NULL, &idim1, &idim2, &bitpix, &status);
    errchk(status);
    fits_get_hdrspace(fptr, &maxcard, &morekeys, &status);
    errchk(status);
    ofptr = fptr;
    break;
  default:
    ofptr = filterTableToImage(fptr, filter, NULL, dims, cens, block, &status);
    errchk(status);
    // get image array
    dbuf = getImageToArray(ofptr, NULL, NULL, &idim1, &idim2, &bitpix, &status);
    errchk(status);
    // get number of keys
    fits_get_hdrspace(ofptr, &maxcard, &morekeys, &status);
    errchk(status);
    break;
  }

#elif HAVE_FUNTOOLS
  /* copy the input fits header into a FITS image header */
  if( !(tfun = (Fun)calloc(1, sizeof(FunRec))) ){
      fprintf(stderr, "ERROR: could not create tfun struct\n");
      exit(1);
  }
  _FunCopy2ImageHeader(ifun, tfun);
  /* and save for storage in the png file */
  optinfo->fitsheader = (char *)tfun->header->cards;

  /* get image parameters. its safe to do this before calling image get
     so long as we don't change bitpix before that call */
  FunInfoGet(ifun,
	     FUN_SECT_BITPIX,  &bitpix,
	     FUN_SECT_DIM1,    &idim1,
	     FUN_SECT_DIM2,    &idim2,
	     0);
#endif

  /* convert FITS header into a json string */
  snprintf(tbuf, SZ_LINE-1, "{\"js9Protocol\": %s, ", JS9_PROTOCOL);
  scat(tbuf, &jsonheader);
  snprintf(tbuf, SZ_LINE-1, "\"js9Endian\": \"%s\", ", JS9_ENDIAN);
  scat(tbuf, &jsonheader);
  snprintf(tbuf, SZ_LINE-1, "\"cardstr\": \"");
  scat(tbuf, &jsonheader);
  // concat header cards into a single string
#if HAVE_CFITSIO
  while( ++ncard <= maxcard ){
    fits_read_record(ofptr, ncard, card, &status);
    errchk(status);
    // change " to '
    for(i=0; i<80; i++){
      if( card[i] == '"' ){
	card[i] = '\'';
      }
    }
    snprintf(tbuf, SZ_LINE-1, "%-80s", card);
    scat(tbuf, &jsonheader);
  }
#elif HAVE_FUNTOOLS
  while( (s = FunParamGets(tfun, NULL, ++ncard, NULL, &dtype)) ){
    for(i=0; i<80; i++){
      if( s[i] == '"' ){
	s[i] = '\'';
      }
    }
    scat(s, &jsonheader);
    if( s ) free(s);
  }
#endif
  // end with the number of cards
  snprintf(tbuf, SZ_LINE-1, "\", \"ncard\": %d}", ncard);
  scat(tbuf, &jsonheader);

  /* we want the image buffer to start on an 8-byte boundary, 
     so make jsonheader + null byte end on one */
  pad = 8 - (strlen(jsonheader) % 8) - 1;
  for(i=0; i<pad; i++){
    strcat(jsonheader, " ");
  }
  /* get final length of json header */
  jsonlen = strlen(jsonheader);

  /* total length of the header + null + image we are storing */
  blen = ABS(bitpix/8);
  dlen = (size_t)idim1 * (size_t)idim2 * blen;
  totbytes = jsonlen + 1 + dlen;

  /* all of this should now fit into the png image */
  /* somewhat arbitrarily, we use idim1 for odim1, and adjust odim2 to fit */
  odim1 = idim1;
  odim2 = (int)(((totbytes + odim1 - 1) / odim1) + (COLOR_CHANNELS-1)) / COLOR_CHANNELS;

  /* allocate buf to hold json header + null byte + RGB image */
  if( !(buf=calloc(COLOR_CHANNELS, odim1 * odim2)) ){
    fprintf(stderr, "ERROR: can't allocate image buf\n");
    exit(1);
  }

  /* move the json header into the output buffer */
  memmove(buf, jsonheader, jsonlen);
  /* add a null byte to signify end of json header */
  buf[jsonlen] = '\0';

  /* offset into image buffer where image starts, past header and null byte */
  istart = jsonlen + 1;

  /* debug output */
  if( verbose ){
    fprintf(stderr, 
    "idim=%d,%d (bitpix=%d jsonlen=%d istart=%d endian=%s) [%ld] -> odim=%d,%d [%d]\n", 
	    idim1, idim2, bitpix, jsonlen, istart, JS9_ENDIAN, totbytes, 
	    odim1, odim2, odim1 * odim2 * COLOR_CHANNELS);
  }

#if HAVE_CFITSIO
  /* move the json header into the output buffer */
  memmove(&buf[istart], dbuf, dlen);
#elif HAVE_FUNTOOLS
  /* extract and bin the data section into an image buffer */
  if( !FunImageGet(ifun, &buf[istart], NULL) ){
    fprintf(stderr, "ERROR: could not FunImageGet: %s\n", iname);
    exit(1);
  }
#endif

  /* debugging output to check against javascript input */
  if( verbose > 1 ){
    fprintf(stderr, "jsonheader: %s\n", jsonheader);
    for(j=0; j<idim2; j++){
      fprintf(stderr, "data #%d: ", j);
      for(i=0; i<idim1; i++){
	switch(bitpix){
	case 8:
	  fprintf(stderr, "%d ", 
		  *(unsigned char *)(buf + istart + ((j * idim1) + i) * blen));
	  break;
	case 16:
	  fprintf(stderr, "%d ", 
		  *(short *)(buf + istart + ((j * idim1) + i) * blen));
	  break;
	case -16:
	  fprintf(stderr, "%d ", 
		  *(unsigned short *)(buf + istart + ((j * idim1) + i) * blen));
	  break;
	case 32:
	  fprintf(stderr, "%d ",
		  *(int *)(buf + istart + ((j * idim1) + i) * blen));
	  break;
	case -32:
	  fprintf(stderr, "%.3f ",
		  *(float *)(buf + istart + ((j * idim1) + i) * blen));
	  break;
	case -64:
	  fprintf(stderr, "%.3f ", 
		  *(double *)(buf + istart + ((j * idim1) + i) * blen));
	  break;
	}
      }
      fprintf(stderr, "\n");
    }
    fprintf(stderr, "\n");
  }

  /* might have to swap to preferred endian for png creation */
  if( (!strncmp(JS9_ENDIAN, "l", 1) &&  is_bigendian()) ||
      (!strncmp(JS9_ENDIAN, "b", 1) && !is_bigendian()) ){
    swap_data(&buf[istart], idim1 * idim2, bitpix/8);
  }

  /* write the PNG file */
  got = writePNG(ofp, buf, odim1, odim2, optinfo);

  /* free up space */
  if( buf ) free(buf);
  if( optinfo ) free(optinfo);
  if( jsonheader ) free(jsonheader);

  /* close files */
#if HAVE_CFITSIO
  status = 0;
  if( ofptr && (ofptr != fptr) ) closeFITSFile(ofptr, &status);
  if( fptr ) closeFITSFile(fptr, &status);
  if( dbuf ) free(dbuf);
#elif HAVE_FUNTOOLS
  if( ifun ) FunClose(ifun);
  if( tfun ){
    FunClose(tfun);
    free(tfun);
  }
#endif
  if( ofp) fclose(ofp);

  /* return the news */
  return got;
}
コード例 #21
0
ファイル: qrenc.c プロジェクト: binape/ybb-apitool
static void qrencodeStructured(const unsigned char *intext, int length, const char *outfile)
{
	QRcode_List *qrlist, *p;
	char filename[FILENAME_MAX];
	char *base, *q, *suffix = NULL;
	const char *type_suffix;
	int i = 1;
	size_t suffix_size;

	switch(image_type) {
		case PNG_TYPE:
			type_suffix = ".png";
			break;
		case EPS_TYPE:
			type_suffix = ".eps";
			break;
		case SVG_TYPE:
			type_suffix = ".svg";
			break;
		case ANSI_TYPE:
		case ANSI256_TYPE:
		case ASCII_TYPE:
		case UTF8_TYPE:
		case ANSIUTF8_TYPE:
			type_suffix = ".txt";
			break;
		default:
			fprintf(stderr, "Unknown image type.\n");
			exit(EXIT_FAILURE);
	}

	if(outfile == NULL) {
		fprintf(stderr, "An output filename must be specified to store the structured images.\n");
		exit(EXIT_FAILURE);
	}
	base = strdup(outfile);
	if(base == NULL) {
		fprintf(stderr, "Failed to allocate memory.\n");
		exit(EXIT_FAILURE);
	}
	suffix_size = strlen(type_suffix);
	if(strlen(base) > suffix_size) {
		q = base + strlen(base) - suffix_size;
		if(strcasecmp(type_suffix, q) == 0) {
			suffix = strdup(q);
			*q = '\0';
		}
	}
	
	qrlist = encodeStructured(intext, length);
	if(qrlist == NULL) {
		perror("Failed to encode the input data");
		exit(EXIT_FAILURE);
	}

	for(p = qrlist; p != NULL; p = p->next) {
		if(p->code == NULL) {
			fprintf(stderr, "Failed to encode the input data.\n");
			exit(EXIT_FAILURE);
		}
		if(suffix) {
			snprintf(filename, FILENAME_MAX, "%s-%02d%s", base, i, suffix);
		} else {
			snprintf(filename, FILENAME_MAX, "%s-%02d", base, i);
		}

		if(verbose) {
			fprintf(stderr, "File: %s, Version: %d\n", filename, p->code->version);
		}

		switch(image_type) {
			case PNG_TYPE: 
				writePNG(p->code, filename);
				break;
			case EPS_TYPE: 
				writeEPS(p->code, filename);
				break;
			case SVG_TYPE: 
				writeSVG(p->code, filename);
				break;
			case ANSI_TYPE:
			case ANSI256_TYPE:
				writeANSI(p->code, filename);
				break;
			case ASCIIi_TYPE:
				writeASCII(p->code, filename, 1);
				break;
			case ASCII_TYPE:
				writeASCII(p->code, filename, 0);
				break;
			case UTF8_TYPE:
				writeUTF8(p->code, filename, 0);
				break;
			case ANSIUTF8_TYPE:
				writeUTF8(p->code, filename, 0);
				break;

			default:
				fprintf(stderr, "Unknown image type.\n");
				exit(EXIT_FAILURE);
		}
		i++;
	}

	free(base);
	if(suffix) {
		free(suffix);
	}

	QRcode_List_free(qrlist);
}
コード例 #22
0
ファイル: sandpile.c プロジェクト: dargouder/SandpileSim
int main(int argc, char** argv) {

    const int x = 0, y = 1;

    /* MPI Message tag */
    const int tag = 1;

    /* Sandpile criticality parameter (must be > 1) */
    const int Ncrit = 2;

    /* Number of steps to run for */
    int Nsteps = 30000;

    /* Probability of adding a new grain in at top squares */
    const double newProb = 0.002;

    /* Interval at which to print images */
    const int Nimage = 500;

    /* Interval at which to print counters */
    const int Ncount = 100;

    /* loop counters */
    int istep, isnap = 0, ic = 0;

    /* local variables */
    double xi;

    /* filename for output images */
    char filename[25];

    /* Seed random number generator */
    unsigned long seed = 20340293;
    init_genrand(seed);

    /* Initial and final times */
    /* Time and initialisation and shutdown */
    double t1 = 0, t2 = 0;

    /* This reads one of the provided input files to define */
    /* a simulation grid, including its dimensions. Either: */

    /* blank.dat     : empty grid - standard sandpiles      */
    /* funnel.dat    : sand pouring through a simple funnel */
    /* largegrid.dat : the grid you should use for timings  */
    FILE *inp = fopen("largegrid.dat", "r");
    if (inp == NULL) {
        printf("Could not open input file!\n");
        exit(EXIT_FAILURE);
    }
    fread(&Nx, 1, sizeof (int), inp); /* Read Nx */
    fread(&Ny, 1, sizeof (int), inp); /* Read Ny */

    /* Allocate memory for a grid this size */
    state_mem = (int *) calloc(Ny*Nx, sizeof (int));
    state = (int **) malloc(Ny * sizeof (int *));
    for (iy = 0; iy < Ny; iy++) {
        state[iy] = &state_mem[iy * Nx];
    }

    /* Read the initial grid from the file */
    for (iy = 0; iy < Ny; iy++) {
        for (ix = 0; ix < Nx; ix++) {
            fread(&state[iy][ix], 1, sizeof (int), inp);
        }
    }

    /* We're done with the input file now */
    fclose(inp);

    int ierr; /* error flag */

    /* Initialise MPI and to retreive rank and p, the number of processors  */
    ierr = MPI_Init(&argc, &argv);
    if (ierr != MPI_SUCCESS) {
        printf("MPI_Init was not successful, program aborting!\n");
    }


    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &p);
    
    /* If running on only 1 process, abort. */
    if (p == 1) {
		if (rank==0) {
			printf("Number of processors must be more than 1!\n");
			exit(EXIT_FAILURE);
		}
	}

	/* Columns assigned to each processor */
    int columns_per_processor = Nx / (p);
    /* Remainder of columns if p is not a perfect divisor*/
    int remainder = Nx % p;

	/* Indices of starting and ending column for this process */
    start = rank * columns_per_processor;
    end = start + columns_per_processor - 1;
    
    /* Increase the workload of process p-1 if there are remaining unassigned columns.*/
    if (remainder == 0) {
        columns_per_processor = Nx / (p);
    } else {
        if (rank == p - 1) {

            columns_per_processor = Nx / (p) + remainder;

            start = rank * Nx / p;
            end = start + columns_per_processor - 1;
        }
    }

    /* Information for setting up a Cartesian communicator */
    int ndims = 2;
    int reorder = 0;
    int pbc [2] = {0, 0};
    int dims[2];

    /* Dimensions of Cartesian communicator */
    dims[x] = p;
    dims[y] = 1;

    /* Creating Cartesian Communicator */
    MPI_Cart_create(MPI_COMM_WORLD, ndims, dims, pbc, reorder, &cart_comm);
    MPI_Comm_rank(cart_comm, &cart_rank);
    MPI_Cart_coords(cart_comm, cart_rank, 2, my_rank_coords);


    MPI_Cart_shift(cart_comm, 0, 1, &(my_rank_neighbours[left]), &(my_rank_neighbours[right]));
    my_rank_neighbours[up] = my_rank_neighbours[down] = rank;

    /*-------------/
    / Start Timer  /
    /-------------*/

    t1 = MPI_Wtime();


    /*----------------/
    / BEGIN MAIN LOOP /
    /----------------*/

    int procs;

    for (istep = 0; istep <= Nsteps; istep++) {

        /*-------------------------------------------/
        /  Move existing grains down due to gravity  /
        /-------------------------------------------*/

        for (iy = 1; iy < Ny; iy++) {
            for (ix = start; ix <= end; ix++) {

                /* Is this pixel occupied by a falling grain ? */
                if (state[iy][ix] == falling) {

                    /* Check if there is an empty square to fall into */
                    if (state[iy - 1][ix] == empty) {

                        /* Fall down one square */
                        state[iy - 1][ix] = falling;
                        state[iy ][ix] = empty;

                    } else {

                        /* Flag pixel as stationary if blocked */
                        if (state[iy - 1][ix] != falling) {
                            state[iy][ix] = stationary;
                        }
                    }

                } /* if falling pixel */

            } /* ix */

        } /* iy */

        /* All grains now in the bottom row are stationary */
        for (ix = start; ix <= end; ix++) {
            if (state[0][ix] == falling) state[0][ix] = stationary;
        }



        /*----------------/
        / Sandpile model  /
        /----------------*/
        halo_swaps();

        /* For each row in the current column (other than top and bottom Ncrit-1 layers) */
        for (iy = Ncrit; iy < Ny - 1; iy++) {
            /* Loop over columns */
            for (ix = start; ix <= end; ix++) {

                /* Is this pixel the uppermost sand grain in a column ? */
                if (state[iy][ix] == stationary && state[iy + 1][ix] != stationary) {

                    /* Determine if this pixel/grain will topple to the left or the right */
                    /* by checking if it is Ncrit grains heigher than its neighbours.     */
                    int count_left = (ix == 0) ? 1 : 0; /* Initialise to zero unless in leftmost column  */
                    int count_right = (ix == Nx - 1) ? 1 : 0; /* Initialise to zero unless in rightmost column */
                    for (ic = 0; ic < Ncrit + 1; ic++) {
                        if (ix > 0)
                            if (state[iy - ic][ix - 1] == stationary || state[iy - ic][ix - 1] == fixed) count_left++;
                        if (ix < Nx - 1)
                            if (state[iy - ic][ix + 1] == stationary || state[iy - ic][ix + 1] == fixed) count_right++;
                    } /* ic */

                    /* Can this grain topple ? */
                    if (count_left == 0 || count_right == 0) {

                        /* In what direction does it topple ? */
                        int dir = 0;

                        if (count_left == 0 && count_right > 0) dir = -1;
                        if (count_left > 0 && count_right == 0) dir = +1;
                        if (count_left == 0 && count_right == 0) {
                            xi = genrand();
                            dir = xi < 0.5 ? 1 : -1;
                        }

                        /* Is the cell we might topple into empty? */
                        if (state[iy - Ncrit][ix + dir] == empty) {
                            /* Topple */
                            state[iy][ix] = empty;
                            state[iy - Ncrit][ix + dir] = falling;


                        }

                    } /* end if can topple */

                } /* end if uppermost */



            } /* iy */

        } /* ix */

        /* Merge neighbour columns with toppled grains*/
        updateBoundaryAfterTopple();
        /*----------------/
        / Input new sand  /
        /----------------*/

        /* Loop over each site in the top row, adding a new sand pixel */
        /* with probability newProb. Will overwrite existing sand if   */
        /* any piles reach the top of the grid.                        */
        for (ix = start; ix <= end; ix++) {
            xi = genrand();
            if (xi < newProb) {
                state[Ny - 1][ix] = falling; /* Sand pixel */
            }
        }

        if (rank != 0 && istep % Ncount == 0) {
            /* Send only relevant columns*/
            int send_state_mem[Ny][columns_per_processor];
            int temp_ix;
            for (iy = 0; iy < Ny; iy++) {
                for (ix = start, temp_ix = 0; ix <= end; ix++, temp_ix++) {
                    /* Fill send_state_mem with relevant columns from state_mem*/
                    send_state_mem[iy][temp_ix] = state[iy][ix];
                }
            }
            MPI_Send(&send_state_mem, Ny * columns_per_processor, MPI_INT, 0, tag, MPI_COMM_WORLD);
        }

        /* Receive grid from all to rank 0 */
        if (rank == 0) {

            if (istep % Ncount == 0) {

                for (procs = 1; procs < p; procs++) {
                    int cpp = columns_per_processor;
					/* Calculate number of received columns depending on the processor rank*/
                    if (remainder != 0 && procs == p - 1) {
                        cpp = columns_per_processor + remainder;
                    }

                    int start = procs * columns_per_processor;
                    int end = start + cpp - 1;

                    int recv_state_mem[Ny][cpp];

                    MPI_Recv(&recv_state_mem, Ny * cpp, MPI_INT, procs, tag, MPI_COMM_WORLD, &stat);

                    int iy, ix, temp_ix;
                    for (iy = 0; iy < Ny; iy++) {
                        for (ix = start, temp_ix = 0; ix <= end; ix++, temp_ix++) {
                            state[iy][ix] = recv_state_mem[iy][temp_ix];
                        }
                    }
                }
            }



            /*---------------------------------/
            /  Print images every Nimage steps /
            /---------------------------------*/
            if (istep % Nimage == 0) {
                sprintf(filename, "snapshot%08d.png", isnap);
                writePNG(filename, state, Ny, Nx);
                isnap++;
            }

            /*-------------------------------------/
            /  Print counters every Ncount steps   /
            /-------------------------------------*/
            if (istep % Ncount == 0) {
                int nfall = 0;
                int nstat = 0;
                for (iy = 0; iy < Ny; iy++) {
                    for (ix = 0; ix < Nx; ix++) {
                        if (state[iy][ix] == falling) nfall++;
                        if (state[iy][ix] == stationary) nstat++;
                    }
                }
                printf("Step : %d, Falling : %d, Stationary %d, Total %d\n", istep, nfall, nstat, nfall + nstat);
            }
        }
    } /* istep */


    /*------------/
    / Stop Timer  /
    /------------*/

    if (p > 1) {
        t2 = MPI_Wtime();
        if (rank == 0) {
            printf("Total time elapsed since MPI initialised :  %12.6f s\n", t2 - t1);
        }
    }

    /* Shutdown MPI - insert appropriate call here */
    ierr = MPI_Finalize();

    /* Release memory */
    free(state);
    free(state_mem);

    exit(EXIT_SUCCESS);


}
コード例 #23
0
 void composeImage(const QImage& src, const QPoint& offset)
 {
     writeMOVE(offset);
     //writeFRAM(src.size());
     writePNG(src);
 }
コード例 #24
0
void
orcqrencode(char *ctx)
{
	int version;
	int level;
	int hint;
	int size;
	int margin;
	int i;
	int doEncodeStructured;
	char buf[MAX_DATA_SIZE];
	char buf2[MAX_DATA_SIZE];
	char qrfile[SIZE_QRFILE];
	char qrfile_suffix[SIZE_QRFILE + 10];
	char *p;
	QRcode *code;
	QRcode_List *head, *entry;

OPENLOG;
	if((p = strchr(CTX(ctx, OFFSET_INFILE), ' ')) != NULL) *p = '\0';
	if((p = strchr(CTX(ctx, OFFSET_QRFILE), ' ')) != NULL) *p = '\0';

	memset(CTX(ctx, OFFSET_RET_CODE), QRENCODE_OK, SIZE_RET_CODE);

	if(euc2sjis(CTX(ctx, OFFSET_INFILE), buf) != 0){
		memset(CTX(ctx, OFFSET_RET_CODE), CHAR_CONV_ERROR, SIZE_RET_CODE);
		return;
	}

	hint = ctx_string2int(ctx, OFFSET_HINT, SIZE_HINT);

	if (hint < 2) {
		if(parse_csv(buf, buf2) !=0){
			memset(CTX(ctx, OFFSET_RET_CODE), KANA_CONV_ERROR, SIZE_RET_CODE);
			return;
		}
	} else {
		lf2crlf(buf,buf2);
	}

	snprintf(qrfile, SIZE_QRFILE, "%s", CTX(ctx, OFFSET_QRFILE));
	version = ctx_string2int(ctx, OFFSET_VERSION, SIZE_VERSION);
	if(version <= 0 || version > 40){
		memset(CTX(ctx, OFFSET_RET_CODE), PARAM_ERROR, SIZE_RET_CODE);
		return;	
	}
	switch(*CTX(ctx, OFFSET_LEVEL)){
		case 'L':
			level = QR_ECLEVEL_L;
			break;
		case 'M':
			level = QR_ECLEVEL_M;
			break;
		case 'Q':
			level = QR_ECLEVEL_Q;
			break;
		case 'H':
			level = QR_ECLEVEL_H;
			break;
		default:
			level = QR_ECLEVEL_L;
	}

	p = strrchr(qrfile, '.');
	if(p != NULL)*p = '\0';
	doEncodeStructured = ctx_string2int(ctx, OFFSET_STRUCTURED, SIZE_STRUCTURED);
	hint = (hint % 2) == 0 ? QR_MODE_KANJI : QR_MODE_8;
	size = ctx_string2int(ctx, OFFSET_PIXEL, SIZE_PIXEL);
	margin = ctx_string2int(ctx, OFFSET_MARGIN, SIZE_MARGIN);

	code = QRcode_encodeString(buf2, version, level, hint, 1);
	if (code != NULL) {
		if (code->version <= version) {
			snprintf(qrfile_suffix, sizeof(qrfile_suffix), 
				"%s_%02d.png", qrfile, 1);
			if(writePNG(code, qrfile_suffix, size, margin) != 0){
				memset(CTX(ctx, OFFSET_RET_CODE), WRITE_PNG_ERROR, SIZE_RET_CODE);
				QRcode_free(code);
				return;
			}
		SYSLOG("write single image");
			sprintf(buf, "%02d" , code->version);
			memcpy(CTX(ctx, OFFSET_RET_VERSION), buf, SIZE_RET_VERSION);
			sprintf(buf, "%02d" , 1);
			memcpy(CTX(ctx, OFFSET_RET_SYMBOLS), "01", SIZE_RET_SYMBOLS);
			QRcode_free(code);
			return;
		}
		QRcode_free(code);
	}
	if (doEncodeStructured) {
		head = QRcode_encodeStringStructured(buf2, version, level, hint ,1);
		if(head) {
			entry = head;
			i = 0;
			while(entry != NULL) {
				code = entry->code;
				snprintf(qrfile_suffix, 
					sizeof(qrfile_suffix), "%s_%02d.png", qrfile, i + 1);
				if(writePNG(code, qrfile_suffix, size, margin) != 0){
					memset(CTX(ctx, OFFSET_RET_CODE), WRITE_PNG_ERROR, SIZE_RET_CODE);
					break;
				}
				entry = entry->next;	
				i++;
			}
		SYSLOG("write multi images");
			QRcode_List_free(entry);
		}
		else {
			memset(CTX(ctx, OFFSET_RET_CODE), QRENCODE_ERROR, SIZE_RET_CODE);
		 	return;
		}
		sprintf(buf, "%02d" , head->code->version);
		memcpy(CTX(ctx, OFFSET_RET_VERSION), buf, SIZE_RET_VERSION);
		sprintf(buf, "%02d" , i);
		memcpy(CTX(ctx, OFFSET_RET_SYMBOLS), buf, SIZE_RET_SYMBOLS);
		QRcode_List_free(head);
	}
#if 1
	print_ctx(ctx);
#endif
SYSLOG("end");
	return;
}