Example #1
0
void main(int argc, char *argv[]){
	
	char *fileName = argv[1];
	
	/* set mode for output stream */
    int ou_mode = O_CREAT | O_WRONLY;
    mode_t flags = S_IRWXU | S_IRGRP; /* 740 */

    int oFd = open(fileName, ou_mode, flags);

    if ( oFd == -1 )
        exitError("%s %s", "Cannot open file", fileName);

    char buf[BUF_SIZE];
    int numRead, numWrite;
	off_t offset = 100;
    while ( (numRead = read(STDIN_FILENO, buf, BUF_SIZE))>0){

        numWrite=write(oFd, buf, numRead);
		if (numWrite!=numRead)
            exitError("%s %s", "Cannot write the whole buffer", strerror(errno));
		/* put a hole here" */
		off_t next = lseek(oFd, offset, SEEK_END);	
    }

    if (close(oFd)==-1)
        exitError("%s","Cannot close output file");	
}
Example #2
0
/*
 * Ruueads a file of tilt angles whose name is in angleFile, and which must
 * have at least nzz lines.  angleSign should be 1., or -1. to invert the
 * sign of the angles.  Minimum and maximum angles are returned in minAngle
 * and maxAngle.  The return value is the array of tilt angles.
 */
float *readTiltAngles(const char *angleFile, int nzz, float angleSign,
                      float &minAngle, float &maxAngle)
{
  char angleStr[MAX_LINE];
  FILE *fpAngle;
  int k, err;
  float currAngle;
  float *tiltAngles = (float *)malloc(nzz * sizeof(float));
  minAngle = 10000.;
  maxAngle = -10000.;
  if (!tiltAngles)
    exitError("Allocating array for tilt angles");
  if ((fpAngle = fopen(angleFile, "r")) == 0)
    exitError("Opening tilt angle file %s", angleFile);
  for (k = 0; k < nzz; k++) {
    do {
      err = fgetline(fpAngle, angleStr, MAX_LINE);
    } while (err == 0);
    if (err == -1 || err == -2)
      exitError("%seading tilt angle file %s\n",
                err == -1 ? "R" : "End of file while r", angleFile);
    sscanf(angleStr, "%f", &currAngle);
    currAngle *= angleSign;
    minAngle = B3DMIN(minAngle, currAngle);
    maxAngle = B3DMAX(maxAngle, currAngle);
    tiltAngles[k] = currAngle;
  }
  fclose(fpAngle);
  return tiltAngles;
}
Example #3
0
int		check_map(char **map, int* size_column)
{
  int		size_line;
  t_check	test;
  int		i;

  test.testk = 0;
  test.testo = 0;
  test.testi = 0;
  i = -1;
  *size_column = 0;
  size_line = strlen(map[0]);
  while (map[++i] != NULL)
    {
      (*size_column)++;
      if (size_line != strlen(map[i]))
	exitError("[ERROR] : Map syntax error : the map have to be a rectangle\n");
      check_line(map[i], &test, i);
    }
  if (test.testk == 0)
    exitError("[ERROR] : Map syntax error : a key are necessary (k)\n");
  if (test.testo == 0)
    exitError("[ERROR] : Map syntax error : an exit are necessary (o)\n");
  if (test.testi == 0)
    exitError("[ERROR] : Map syntax error : an enter are necessary (i)\n");
  return (size_line);
}
Example #4
0
int main(int argc, char *argv[]) {
	int i, srvSock, cliSock, *tNum;

	if (argc < 3)
		exitError("Usage: pre-threaded <port#> <thread#>\n", 1);

	srvSock = tcpListen(argv[1]);
	nThreads = atoi(argv[2]);
	threads = calloc(nThreads,sizeof(Thread));

	for (i = 0; i < nThreads; i++) {
		tNum = malloc(sizeof(int));
		*tNum = i;
		if (pthread_create(&threads[0].tid, NULL, &thread_start, (void *) tNum))
			exitError("ERROR: pthread_create", 1);
	}

	signal(SIGINT, sig_int);

	cliGet = cliPut = 0;
	while(1){
		cliSock = accept(srvSock, NULL,NULL);
		if(cliSock==-1)
			exitError("ERROR: could not accept new connection on socket",1);
		pthread_mutex_lock(&cliMutex);
		cliSocks[cliPut] = cliSock;
		if (++cliPut == MAX_CLI)
			cliPut = 0;
		if (cliPut == cliGet)
			exitError("ERROR: cliPut = cliGet = %d", cliPut);
		pthread_cond_signal(&cliCond);
		pthread_mutex_unlock(&cliMutex);
	}
}
Example #5
0
void		initImages(t_image* img)
{
  if ((img->screen = SDL_SetVideoMode(SCREEN_X * SIZE_IMAGE,
				      SCREEN_Y * SIZE_IMAGE,
				      32, SDL_RESIZABLE | SDL_DOUBLEBUF)) == NULL)
    exitError("[ERROR] : SDL failure : SDL_SetVideoMode\n");
  SDL_WM_SetCaption("Epikong", "KONG");
  if ((img->bloc = IMG_Load("../image/brique.png")) == NULL)
    exitError("[ERROR] : SDL failure : IMG_Load\n");
  if ((img->scale = IMG_Load("../image/echelle.png")) == NULL)
    exitError("[ERROR] : SDL failure : IMG_Load\n");
  if ((img->door = IMG_Load("../image/porte.png")) == NULL)
    exitError("[ERROR] : SDL failure : IMG_Load\n");
}
Example #6
0
/* reads the math expresion (in values) and its size*/
void readExpression(char **values, int *size)
{
    fprintf(stdout, "[INFO] [READ]\tIntroduce the mathematical expression separated by space in\n");
    fprintf(stdout, "\t\tpostfix form with operands in [a-zA-Z], operations in '+-*/'\n");
    fprintf(stdout, "\t\tand use '#' for unary operations:\n");
    fprintf(stdout, "[INFO] [READ]\t");
    char *buffer = (char*) calloc(1024, sizeof(char));
    fgets(buffer, 1024, stdin);

    *size = 0;
    while (*(buffer+*size) != '\n')
    {
        (*size)++;
    }
    *size = (*size+1)/2;

    char *result = (char*) calloc((*size+1), sizeof(char));
    for (int i=0; i<*size; i++)
    {
        *(result+i) = *(buffer+i*2);
    }

    free(buffer);
    if (checkExpression(result))
    {
        *values = result;
    }
    else
    {
        exitError("[READ]\tThe read expression contains invalid characters.\n");
    }
}
Example #7
0
void		loadAllImages(t_image* m)
{
  SDL_Rect	backPos;
  int		i;
  int		j;

  if (SDL_FillRect(m->screen, NULL,
		   SDL_MapRGB(m->screen->format, 255, 255, 255)) == -1)
    exitError("[ERROR] : SDL failure : SDL_FillRect\n");
  i = -1;
  while (m->map[++i] != NULL)
    {
      j = -1;
      while (m->map[i][++j] != '\0')
	if (m->map[i][j] == 'w' || m->map[i][j] == 's' || m->map[i][j] == 'o')
	  {
	    backPos.x = j * SIZE_IMAGE;
	    backPos.y = i * SIZE_IMAGE;
	    if ((m->map[i][j] == 's')
		&& ((j > 0 && m->map[i][j - 1] == 'w')
		    || m->map[i][j + 1] == 'w'))
	      x_SDL_BlitSurface(retBackImage('w', m), NULL,
				m->screen, &backPos);
	    x_SDL_BlitSurface(retBackImage(m->map[i][j], m), NULL,
			      m->screen, &backPos);
	  }
    }
}
Example #8
0
void CClctrl::readData(CMatrix& X, CMatrix& y, const string fileName)
{
  string m = getMode();
  setMode("file");
  if(verbosity>1)
    cout << "Loading data." << endl;
  switch(fileFormat)
  {
  case 0: /// svmlight file format.
    readSvmlDataFile(X, y, fileName);
    break;
  case 1: /// Matlab file format.
#ifdef _NDLMATLAB
    X.readMatlabFile(fileName, "X");
    y.readMatlabFile(fileName, "y");
#else
    throw ndlexceptions::MatlabInterfaceError("MATLAB not incorporated at compile time");
#endif
    break;
  default:
    exitError("Unrecognised file format number.");
    
  }
  if(verbosity>1)
    cout << "Data set loaded." << endl;
  setMode(m);
}
Example #9
0
void AudioWalkera::setupAlsa(){

	int dir;

	int t = 0, i, c;

	rc = snd_pcm_open(&handle, "default", SND_PCM_STREAM_CAPTURE, 0);

	if(rc < 0)
		exitError("Could not open pcm device");

	snd_pcm_hw_params_alloca(&params);
	//rc = setupHardware(handle, params, &dir);


	snd_pcm_uframes_t frames_inner;
	unsigned int val;

	snd_pcm_hw_params_any(handle, params);

	snd_pcm_hw_params_set_access(handle, params, 
			SND_PCM_ACCESS_RW_INTERLEAVED);

	snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE);

	snd_pcm_hw_params_set_channels(handle, params, 1);


	val = 48000;
	snd_pcm_hw_params_set_rate_near(handle, params, &val, &dir);

	frames_inner = 2304;
	snd_pcm_hw_params_set_period_size_near(handle, params, &frames_inner, &dir);

	rc = snd_pcm_hw_params(handle, params);
 

	if(rc < 0)
		exitError("Could not set hardware parameters");

	snd_pcm_hw_params_get_period_size(params, &frames, &dir);

	buffer = (short*) calloc(frames, sizeof(short));


}
Example #10
0
int main(int argc, char *argv[]) {
	int cliSock;

	if (argc < 2)
		exitError("ERROR: port number not provided\n",1);

	srvSock = tcpListen(argv[1]);

	signal(SIGINT, sig_int);
	while (1) {
		cliSock = accept(srvSock, NULL, NULL);
		if (cliSock == -1)
			exitError("ERROR: could not accept incoming connection\n", 1);

		handleHttpRequest(cliSock);
		closeWriteSock(cliSock);
	}
}
Example #11
0
void AudioWalkera::uinputEvents(){

	memset(&multiEv, 0, sizeof(multiEv));

	multiEv[0].type = EV_ABS;
	multiEv[0].code = ABS_X;
	multiEv[0].value = ailerons;

	multiEv[1].type = EV_ABS;
	multiEv[1].code = ABS_Y;
	multiEv[1].value = elevator;

	multiEv[2].type = EV_ABS;
	multiEv[2].code = ABS_THROTTLE;
	multiEv[2].value = throttle;

	multiEv[3].type = EV_ABS;
	multiEv[3].code = ABS_RUDDER;
	multiEv[3].value = rudder;


	if(write(fd, &multiEv, sizeof(multiEv)) < 0){
		exitError("error: write event");
	}


	memset(&ev, 0, sizeof(struct input_event));
	ev.type = EV_KEY;
	ev.code = BTN_JOYSTICK;
	ev.value = flipSwitch;
	if(write(fd, &ev, sizeof(struct input_event)) < 0){
		exitError("error: write event");
	}


	memset(&ev, 0, sizeof(struct input_event));
	ev.type = EV_SYN;
	ev.code = 0;
	ev.value = 0;
	if(write(fd, &ev, sizeof(struct input_event)) < 0){
		exitError("error: write event");
	}

}
Example #12
0
/* initializes a stack with size >= 1 */
void initStack(int size)
{
    if(size < 1)
    {
        exitError("[INIT]\tFailed to initialize stack. Size is less than 1.\n");
        return;
    }
    stack = (NodeT**) calloc(size, sizeof(NodeT*));
    stackPointer = -1;
}
Example #13
0
void SliceCache::clearAndSetSize(int dim, int hyper, int tSize)
{
  int fftXdim, i, j, rIndex;
  double freqInc;
  numXtiles = mHeader.nx / (tSize / 2) - 1;
  mNumYtiles = mHeader.ny / (tSize / 2) - 1;
  mPsArraySize = numXtiles * mNumYtiles * mPsDim;
  mMaxSliceNum = mMaxCacheSize * 1024 * 1024 / (mPsArraySize * sizeof(float));
  for (i = 0; i < (int)mCachedPS.size(); i++) {
    free(mCachedPS[i]);
    free(mCachedTileDone[i]);
    free(mCachedMeans[i]);
  }
  if (mTile)
    free(mTile);
  mTile = (float *)malloc(tSize * (tSize + 2) * sizeof(float));
  if (mTileToPsInd)
    free(mTileToPsInd);
  mTileToPsInd = (int *)malloc(tSize * (tSize + 2) * sizeof(int));
  if (!mTile || !mTileToPsInd)
    exitError("Allocating memory for mTile or PS index");

  // Compute the index for each component of FFT and the counts in each bin
  mTileSize = tSize;
  mNDim = dim;
  mHyperRes = hyper;
  fftXdim = (mTileSize + 2) / 2;
  freqInc = 1. / ((mNDim - 1) * hyper);
  for (i = 0; i < mPsDim; i++)
    mFreqCount[i] = 0;
  for (i = 0; i < fftXdim - 1; i++) {
    for (j = 0; j < fftXdim; j++) {

      // Here make bins with integer truncation
      rIndex = (int)(sqrt((double)(i * i + j * j)) / (fftXdim - 1) / freqInc);
      rIndex = B3DMIN(rIndex, mPsDim - 1);
      mTileToPsInd[i * fftXdim + j] = rIndex;
      mFreqCount[rIndex] += 2;
    }
  }

  /*for (i = 0; i < mPsDim; i++)
    printf("%d\n", mFreqCount[i]); */

  // Clear cache components
  mCachedPS.clear();
  mCachedMeans.clear();
  mCachedTileDone.clear();
  mSliceAngles.clear();
  mCachedSliceMap.clear();
  mOldestIdx = -1;

  if (debugLevel >= 2)
    printf("cacheSize is set to %d \n", mMaxSliceNum);
}
Example #14
0
/*
 * Reads a defocus file whose name is in fnDefocus and stores the values
 * in an Ilist of SavedDefocus structures, eliminating duplications if any.
 * The return value is the Ilist, which may be empty if the file does not
 * exist.
 */
Ilist *readDefocusFile(const char *fnDefocus, int &defVersion)
{
  FILE *fp;
  SavedDefocus saved;
  char line[MAX_LINE];
  int nchar, versTmp;
  float langtmp, hangtmp, defoctmp;
  Ilist *lstSaved = ilistNew(sizeof(SavedDefocus), 10);
  if (!lstSaved)
    exitError("Allocating list for angles and defocuses");
  fp = fopen(fnDefocus, "r");
  defVersion = 0;
  versTmp = 0;
  if (fp) {
    while (1) {
      nchar = fgetline(fp, line, MAX_LINE);
      if (nchar == -2)
        break;
      if (nchar == -1)
        exitError("Error reading defocus file %s", fnDefocus);
      if (nchar) {
        sscanf(line, "%d %d %f %f %f %d", &saved.startingSlice, &saved.endingSlice
               , &langtmp, &hangtmp, &defoctmp, &versTmp);
        if (!ilistSize(lstSaved))
          defVersion = versTmp;
        saved.lAngle = langtmp;
        saved.hAngle = hangtmp;
        saved.defocus = defoctmp / 1000.;
        saved.startingSlice--;
        saved.endingSlice--;
        addItemToDefocusList(lstSaved, saved);
      }
      if (nchar < 0)
        break;
    }
    fclose(fp);
  }
  return lstSaved;
}
Example #15
0
//init SliceCache and clear its old contents
//It needs to be called whenever the tomogram it manages changes.
void SliceCache::initCache(const char *fnStack, int dim,
                           int hyper, int tSize, int &nx, int &ny, int &nz)
{
  int dsize, csize;
  mDataOffset = 0.;
  if (mFpStack)
    iiFClose(mFpStack);
  if ((mFpStack = iiFOpen(fnStack, "rb")) == 0)
    exitError("could not open input file %s", fnStack);

  /* read mHeader */
  if (mrc_head_read(mFpStack, &mHeader))
    exitError("could not read header of input file %s",  fnStack);
  mSliceMode = sliceModeIfReal(mHeader.mode);
  if (mSliceMode < 0)
    exitError("File mode is %d; only byte, short, integer allowed\n",
              mHeader.mode);
  mrc_getdcsize(mHeader.mode, &dsize, &csize);
  nx = mHeader.nx;
  ny = mHeader.ny;
  nz = mHeader.nz;
  mPsDim = (dim + 1) * hyper + 1;
  if (mFreqCount)
    free(mFreqCount);
  mFreqCount = (int *)malloc(mPsDim * sizeof(int));
  if (mSliceData)
    free(mSliceData);
  mSliceData = (float *)malloc(nx * ny * dsize);
  if (mPsTmp)
    free(mPsTmp);
  mPsTmp = (double *)malloc(mPsDim * sizeof(double));
  if (!mSliceData || !mFreqCount || !mPsTmp)
    exitError("Allocating memory for image slice, frequency counts, or mPsTmp");
  mCurSlice = -1;
  clearAndSetSize(dim, hyper, tSize);
}
Example #16
0
t_monster *add_monster(t_monster *monster, SDL_Rect pos, SDL_Surface *img,
		       int flag)
{
  t_monster	*new_monster;

  new_monster = malloc(sizeof(*new_monster));
  if (new_monster == NULL)
    exitError("Cannot alloc memory\n");
  new_monster->next = monster;
  new_monster->pos.x = pos.x;
  new_monster->pos.y = pos.y;
  new_monster->img = img;
  new_monster->flag = flag;
  monster = new_monster;
  return (monster);
}
Example #17
0
void		waitImage()
{
  int continuer = 1;
  SDL_Event event;
 
  while (continuer)
    {
      if (SDL_WaitEvent(&event) == 0)
	exitError("[ERROR] : SDL failure : SDL_WaitEvent\n");
      if(event.type == SDL_QUIT)
	continuer = 0;
      else if (event.type == SDL_KEYDOWN)
	if (event.key.keysym.sym == SDLK_ESCAPE)
	  continuer = 0;
    }
}
Example #18
0
int		main(int ac, char** av)
{
  SDL_Surface	*screen;
  SDL_Surface	*life_back;
  char		**map;
  char		*life;
  int		i;
  int		size_line;
  int		size_column;

  if (ac == 2)
    {
      map = loadMap(av[1]);
      size_line = check_map(map, &size_column);      
      life = constr_life(size_line, life);
      x_SDL_Init(SDL_INIT_VIDEO);
      screen = SDL_SetVideoMode(size_line*SIZE_IMAGE , size_column*SIZE_IMAGE
+ SIZE_IMAGE, 32, SDL_RESIZABLE | SDL_DOUBLEBUF);

      SDL_WM_SetCaption("Epikong", "KONG");
            
      loadAllImages(map, screen);
      life_back = SDL_CreateRGBSurface(SDL_HWSURFACE, SIZE_IMAGE, SIZE_IMAGE, 32, 0, 0, 0, 0);
      loadImagelife(screen, life, 0);
      
      /* 3 vies */
      loadImagelife(screen, life, 1);
      loadImagelife(screen, life, 1);
      loadImagelife(screen, life, 1);

      x_SDL_Flip(screen);
      x_SDL_Flip(life_back);
      waitImage();
      i = -1;
      while (map[++i] != NULL)
	free(map[i]);
      free(map);
      SDL_Quit();
    }
  else
    {
      printf("Format : %s filemap\n", av[0]);
      exitError("[ERROR] : Bad parameters\n");
    }
  return (EXIT_SUCCESS);
}
Example #19
0
// Used to read in angle from file, now get from array
float  SliceCache::readAngle(int whichSlice)
{
  if (whichSlice < 0 || whichSlice >= mHeader.nz)
    exitError("Slice index is out of range");

  float currAngle;
  float *angles = mApp->getTiltAngles();
  if (angles) {
    currAngle = angles[whichSlice];
    if (debugLevel >= 1)
      printf("Slice %d is included, tilt angle is %f degrees. \n", whichSlice,
             currAngle);
    return currAngle * MY_PI / 180.0;
  } else {
    if (debugLevel >= 1)
      printf("No angle is specified, set to 0.0\n");
    return 0.0;
  }
}
Example #20
0
/*
 * Adds one item to the defocus list, keeping the list in order and
 * and avoiding duplicate starting and ending view numbers
 */
void addItemToDefocusList(Ilist *lstSaved, SavedDefocus toSave)
{
  SavedDefocus *item;
  int i, matchInd = -1, insertInd = 0;

  // Look for match or place to insert
  for (i = 0; i < ilistSize(lstSaved); i++) {
    item = (SavedDefocus *)ilistItem(lstSaved, i);
    if (item->startingSlice == toSave.startingSlice &&
        item->endingSlice == toSave.endingSlice) {
      matchInd = i;
      *item = toSave;
      break;
    }
    if (item->lAngle + item->hAngle <= toSave.lAngle + toSave.hAngle)
      insertInd = i + 1;
  }

  // If no match, now insert
  if (matchInd < 0 && ilistInsert(lstSaved, &toSave, insertInd))
    exitError("Failed to add item to list of angles and defocuses");
}
Example #21
0
int
background(char* line)
// Check and exec on background all the commands ended with '&' on the command
// line and return the last, foreground command
{
	// Split pipeline in independent commands
	char* array[10];
	int numCommands = gettokens(line, array, 10, "&");

	// run script commands
	int i;
	for(i = 0; i < numCommands-1; ++i)
	{
		switch(fork())
		{
			case -1:
				return -1;

			case 0:	// child
			{
				// redirect stdin to /dev/null
				redirect_stdin("/dev/null");

				// process pipeline
				pipeline_process(array[i]);
				exitError();
			}

			// parent loop to exec in background the next command (if any)
		}
	}

	// collapse line to let only the last (not background) command on it
	int len = strlen(array[numCommands-1]);
	memmove(line, array[numCommands-1], len);
	*(line+len) = '\0';

	return 0;
}
Example #22
0
void		loadFile(t_image* img, char *filemap)
{
  t_removable	remove;

  img->map = loadMap(filemap);
  check_map(img);
  if (img->sizeX != SCREEN_X || img->sizeY != SCREEN_Y)
    {
      fprintf(stderr, "[ERROR] : The map have to have dimension of %d by %d\n",
	      SCREEN_X, SCREEN_Y);
      exitError("");
    }
  loadAllImages(img);
  x_SDL_Flip(img->screen);
  remove.monster = catch_monster(img->map);
  remove.item = catch_item(img->map, &remove);
  put_elem(&remove, img);
  x_SDL_Flip(img->screen);
  key(&remove, *img);
  x_SDL_Flip(img->screen);
  waitImage();
  freeMap(img->map);
}
Example #23
0
void		loadAllImages(char** map, SDL_Surface* screen)
{
  t_image	imgs;
  int		i;

  if (SDL_FillRect(screen, NULL,
		   SDL_MapRGB(screen->format, 255, 255, 255)) == -1)
    exitError("[ERROR] : SDL failure : SDL_FillRect\n");
  if ((imgs.monster = IMG_Load("../image/monstre.png")) == NULL)
    exitError("[ERROR] : SDL failure : IMG_Load\n");
  if ((imgs.bloc = IMG_Load("../image/brique.png")) == NULL)
    exitError("[ERROR] : SDL failure : IMG_Load\n");
  if ((imgs.scale = IMG_Load("../image/echelle.png")) == NULL)
    exitError("[ERROR] : SDL failure : IMG_Load\n");
  if ((imgs.door = IMG_Load("../image/porte.png")) == NULL)
    exitError("[ERROR] : SDL failure : IMG_Load\n");
  if ((imgs.key = IMG_Load("../image/clef.png")) == NULL)
    exitError("[ERROR] : SDL failure : IMG_Load\n");
  i = -1;
  while (map[++i] != NULL)
    loadImage(map[i], &imgs, i, screen);
}
Example #24
0
void CClctrl::confirmCurrentArg(string commandName)
{
  if(getCurrentArgument()!=commandName)
    exitError("Unrecognised argument " + getCurrentArgument() + " for `" + getMode() + "' command.");
}
Example #25
0
void AudioWalkera::setupUinput(){


	struct uinput_user_dev uidev;


	fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
	if(fd < 0)
		exitError("error: open");

	if(ioctl(fd, UI_SET_EVBIT, EV_KEY) < 0)
		exitError("error: ioctl");
	if(ioctl(fd, UI_SET_KEYBIT, BTN_JOYSTICK) < 0)
		exitError("error: ioctl");
	if(ioctl(fd, UI_SET_EVBIT, EV_ABS) < 0)
		exitError("error: ioctl");
	if(ioctl(fd, UI_SET_ABSBIT, ABS_X) < 0)
		exitError("error: ioctl");
	if(ioctl(fd, UI_SET_ABSBIT, ABS_Y) < 0)
		exitError("error: ioctl");
	if(ioctl(fd, UI_SET_ABSBIT, ABS_THROTTLE) < 0)
		exitError("error: ioctl");
	if(ioctl(fd, UI_SET_ABSBIT, ABS_RUDDER) < 0)
		exitError("error: ioctl");


	if(ioctl(fd, UI_SET_EVBIT, EV_MSC) < 0)
		exitError("error: ioctl");

	memset(&uidev, 0, sizeof(uidev));
	snprintf(uidev.name, UINPUT_MAX_NAME_SIZE, "Walkera-PCM-0701");
	uidev.id.bustype = BUS_USB;
	uidev.id.vendor  = 0x1;
	uidev.id.product = 0x1;
	uidev.id.version = 1;

	//Hardcoded calibration values, set these yourself.
	uidev.absmax[ABS_X] = 370;
	uidev.absmin[ABS_X] = -370;

	uidev.absmax[ABS_Y] = 370;
	uidev.absmin[ABS_Y] = -370;

	uidev.absmax[ABS_RUDDER] = 365;
	uidev.absmin[ABS_RUDDER] = -365;

	uidev.absmax[ABS_THROTTLE] = 425;
	uidev.absmin[ABS_THROTTLE] = -420;



	if(write(fd, &uidev, sizeof(uidev)) < 0){
		exitError("Cant setup uinput device, permissions? Udev rule?");
	}
	if(ioctl(fd, UI_DEV_CREATE) < 0){
		exitError("error: ioctl");
	}


}
Example #26
0
int main( int argc, char *argv[] )
{

  int    i = 0;
  FILE   *fin, *fout;
  struct MRCheader hdata, hout;
  struct MRCheader *hptr;
  unsigned char *buf;
  int bsize, csize, dsize;
  int inside = 0;
  int ntaper = DEFAULT_TAPER;
  int taperEntered = 0;
  Islice slice;
  int zmin = -1, zmax = -1;
  int secofs;
  char *progname = imodProgName(argv[0]);
  setStandardExitPrefix(progname);

  if (argc < 2){
    fprintf(stderr, 
            "%s version %s\n", progname, VERSION_NAME);
    imodCopyright();
    mrctaper_help(progname);
    exit(3);
  }

  for (i = 1; i < argc; i++) {
    if (argv[i][0] == '-') {
      switch (argv[i][1]) {
          
      case 'i':
        inside = 1;
        break;

      case 't':
        taperEntered = 1;
        if (argv[i][2] != 0x00)
          sscanf(argv[i], "-t%d", &ntaper);
        else
          sscanf(argv[++i], "%d", &ntaper);
        break;

      case 'z':
        if (argv[i][2] != 0x00)
          sscanf(argv[i], "-z%d%*c%d", &zmin, &zmax);
        else
          sscanf(argv[++i], "%d%*c%d", &zmin, &zmax);
        break;

      default:
        printf("ERROR: %s - illegal option\n", progname);
        mrctaper_help(progname);
        exit(1);
        break;
      }
    } else
      break;
  }

  if (i < (argc - 2) || i == argc){
    mrctaper_help(progname);
    exit(3);      
  }

  if (ntaper < 1 || ntaper > 127)
    exitError("Taper must be between 1 and 127.");

  if (i < argc - 1)
    fin = iiFOpen(argv[i++], "rb");
  else
    fin = iiFOpen(argv[i++], "rb+");

  if (fin == NULL)
    exitError("Opening %s.", argv[i - 1]);
  if (mrc_head_read(fin, &hdata))
    exitError("Can't Read Input File Header.");

  if (sliceModeIfReal(hdata.mode) < 0)
    exitError("Can operate only on byte, integer and real data.");

  if (!taperEntered) {
    ntaper = (hdata.nx + hdata.ny) / 200;
    ntaper = B3DMIN(127, B3DMAX(DEFAULT_TAPER, ntaper));
    printf("Tapering over %d pixels\n", ntaper);
  }
     
  if (zmin == -1 && zmax == -1) {
    zmin = 0;
    zmax = hdata.nz - 1;
  } else {
    if (zmin < 0)
      zmin = 0;
    if (zmax >= hdata.nz)
      zmax = hdata.nz - 1;
  }
     
  if (i < argc) {
    fout = iiFOpen(argv[i], "wb");
    if (fout == NULL)
      exitError("Opening %s.", argv[i]);
    hout = hdata;
    hout.fp = fout;

    /* DNM: eliminate extra header info in the output, and mark it as not swapped  */
    mrcInitOutputHeader(&hout);
    hptr = &hout;
    hout.nz = zmax + 1 - zmin;
    hout.mz = hout.nz;
    hout.zlen = hout.nz;
    secofs = zmin;
  } else {
    if (b3dOutputFileType() == IIFILE_TIFF)
      exitError("Cannot write to an existing TIFF file.");
      
    hptr = &hdata;
    fout = fin;
    secofs = 0;
  }
     
  mrc_getdcsize(hdata.mode, &dsize, &csize);

  bsize = hdata.nx * hdata.ny;
  buf = (unsigned char *)malloc(dsize * csize * bsize);
     
  if (!buf)
    exitError("Couldn't get memory for slice.");
  sliceInit(&slice, hdata.nx, hdata.ny, hdata.mode, buf);

  for (i = zmin; i <= zmax; i++) {
    printf("\rDoing section #%4d", i);
    fflush(stdout);
    if (mrc_read_slice(buf, fin, &hdata, i, 'Z'))
      exitError("Reading section %d.", i);
      
    if (sliceTaperAtFill(&slice, ntaper, inside))
      exitError("Can't get memory for taper operation.");
          
    if (mrc_write_slice(buf, fout, hptr, i - secofs, 'Z'))
      exitError("Writing section %d.", i);
  }
  puts("\nDone!");

  mrc_head_label(hptr, "mrctaper: Image tapered down to fill value at edges");

  mrc_head_write(fout, hptr);
  iiFClose(fout);

  return(0);
}
Example #27
0
int main(int argc, char *argv[])
{
  Imod   model;
  FILE   *fin, *fout;
  char   *filename = NULL;
  int    i;
  int    mode = 0;
  int    useZscale = 0;
  int    doflip = 1;
  int    transopt = 0;
  int    rotScaleopt = 0;
  int    toImage = 0, fromImage = 0;
  int    oneLine = -1;
  int    toggleFlip = 0;
  int    flipModel = 0;
  float  zscale = 1.;
  float transScale = 1.;
  float  rx = 0., ry = 0., rz = 0.;
  float transx = 0., transy = 0., transz = 0.;
  int multiTrans = 0;
  int newNx = 0, newNy = 0, newNz = 0;
  char *progname = imodProgName(argv[0]);
  Ipoint newCen, tmpPt;
  Imat *mat = imodMatNew(3);
  Imat *normMat = imodMatNew(3);
  IrefImage useRef, *modRefp;
  MrcHeader hdata, hdataFirst;
  Ipoint unitPt = {1., 1., 1.};
  char prefix[100];
  sprintf(prefix, "ERROR: %s - ", progname);
  setExitPrefix(prefix);

  if (argc < 3){
    usage(progname);
  }
     
  for (i = 1; i < argc; i++) {
    if (argv[i][0] == '-') {
      switch (argv[i][1]) {

      case '2':
        filename = argv[++i];
        mode += 2;
        break;
            
      case '3':
        filename = argv[++i];
        mode += 3;
        break;

      case 'S':
        sscanf(argv[++i], "%f", &transScale);
        break;

      case 'i':
        toImage = 1;
        if (NULL == (fin = fopen(argv[++i], "rb")))
          exitError("Couldn't open %s", argv[i]);

        if (mrc_head_read(fin, &hdata)) 
          exitError("Reading header from %s", argv[i]);
        fclose(fin);
        break;

      case 'I':
        fromImage = 1;
        if (NULL == (fin = fopen(argv[++i], "rb")))
          exitError("Couldn't open %s", argv[i]);

        if (mrc_head_read(fin, &hdataFirst)) 
          exitError("Reading header from %s", argv[i]);
        fclose(fin);
        break;

      case 'z':
        useZscale = 1;
        break;

      case 'f':
        doflip = 0;
        break;

      case 'Y':
        flipModel = 1;
        break;

      case 'T':
        toggleFlip = 1;
        break;

      case 'n':
        sscanf(argv[++i], "%d%*c%d%*c%d", &newNx, &newNy, &newNz);
        break;
            
      case 'l':
        oneLine = atoi(argv[++i]);
        break;

      case 't':  /* Translations */
        tmpPt.x = tmpPt.y = tmpPt.z = 0.;
        transopt = 1;
        switch (argv[i][2]) {
        case 'x':
          if (argv[i][3] != 0x00)
            sscanf(argv[i], "-tx%f", &tmpPt.x);
          else
            sscanf(argv[++i], "%f", &tmpPt.x);
          if (transx)
            multiTrans = 1;
          transx = tmpPt.x;
          break;
        case 'y':
          if (argv[i][3] != 0x00)
            sscanf(argv[i], "-ty%f", &tmpPt.y);
          else
            sscanf(argv[++i], "%f", &tmpPt.y);
          if (transy)
            multiTrans = 1;
          transy = tmpPt.y;
          break;
        case 'z':
          if (argv[i][3] != 0x00)
            sscanf(argv[i], "-tz%f", &tmpPt.z);
          else
            sscanf(argv[++i], "%f", &tmpPt.z);
          if (transz)
            multiTrans = 1;
          transz = tmpPt.z;
          break;
        default:
          exitError("Invalid option %s", argv[i]);
        }
        imodMatTrans(mat, &tmpPt);
        break;

      case 's':  /* Scaling */
        tmpPt.x = tmpPt.y = tmpPt.z = 1.;
        transopt = 1;
        rotScaleopt = 1;
        switch (argv[i][2]) {
        case 'x':
          if (argv[i][3] != 0x00)
            sscanf(argv[i], "-sx%f", &tmpPt.x);
          else
            sscanf(argv[++i], "%f", &tmpPt.x);
          break;
        case 'y':
          if (argv[i][3] != 0x00)
            sscanf(argv[i], "-sy%f", &tmpPt.y);
          else
            sscanf(argv[++i], "%f", &tmpPt.y);
          break;
        case 'z':
          if (argv[i][3] != 0x00)
            sscanf(argv[i], "-sz%f", &tmpPt.z);
          else
            sscanf(argv[++i], "%f", &tmpPt.z);
          break;
        default:
          exitError("Invalid option %s", argv[i]);
        }
        imodMatScale(mat, &tmpPt);
        tmpPt.x = 1. / tmpPt.x;
        tmpPt.y = 1. / tmpPt.y;
        tmpPt.z = 1. / tmpPt.z;
        imodMatScale(normMat, &tmpPt);
        break;

      case 'r':  /* Rotations */
        transopt = 1;
        rotScaleopt = 1;
        switch (argv[i][2]) {
        case 'x':
          if (argv[i][3] != 0x00)
            sscanf(argv[i], "-rx%f", &rx);
          else
            sscanf(argv[++i], "%f", &rx);
          imodMatRot(mat, (double)rx, b3dX);
          imodMatRot(normMat, (double)rx, b3dX);
          break;
        case 'y':
          if (argv[i][3] != 0x00)
            sscanf(argv[i], "-ry%f", &ry);
          else
            sscanf(argv[++i], "%f", &ry);
          imodMatRot(mat, (double)ry, b3dY);
          imodMatRot(normMat, (double)ry, b3dY);
          break;
        case 'z':
          if (argv[i][3] != 0x00)
            sscanf(argv[i], "-rz%f", &rz);
          else
            sscanf(argv[++i], "%f", &rz);
          imodMatRot(mat, (double)rz, b3dZ);
          imodMatRot(normMat, (double)rz, b3dZ);
          break;
        default:
          exitError("Invalid option %s", argv[i]);
        }
        break;

      default:
        exitError("Invalid option %s",  argv[i]);
      }

    }else{
      break;
    }
  }

  if (mode && mode / 2 != 1) 
    exitError("You cannot enter both -2 and -3");
  
  if (mode && rotScaleopt)  
    exitError("You cannot enter -r or -s options with -2 and -3");
  if (transopt && mode == 2 && oneLine < 1 && transz)
    exitError("You cannot enter -tz option with -2 unless transforming with one line");
  if (mode && multiTrans)
    exitError("You cannot enter -t options more than once with -2 and -3");
  
  if (i != argc - 2) {
    printf("ERROR: %s - Command line should end with two non-option "
            "arguments\n", progname);
    usage(progname);
  }

  fin = fopen(argv[i], "rb");
  if (!fin)
    exitError("Opening input file %s", argv[i]);
      
  imodDefault(&model);
  model.file = fin;
  if (imodReadFile(&model))
    exitError("Reading imod model (%s)", argv[i]);
  fclose(fin);

  if (imodBackupFile(argv[i + 1])) 
    exitError("Couldn't create backup file");

  fout = fopen(argv[i + 1], "wb");
  if (!fout)
    exitError("Opening output file %s", argv[i + 1]);

  /* Change image reference information */
  if (fromImage && imodSetRefImage(&model, &hdataFirst))
    exitError("Allocating a IrefImage structure");

  /* Do flipping operations first */
  if (flipModel)
    imodFlipYZ(&model);
  if (toggleFlip) {
    if (model.flags & IMODF_FLIPYZ)
      model.flags &= ~IMODF_FLIPYZ;
    else
      model.flags |= IMODF_FLIPYZ;
  }

  /* Do scaling to image reference next */
  if (toImage) {

    modRefp = model.refImage;
    if (modRefp && !(model.flags & IMODF_OTRANS_ORIGIN)) 
      exitError("Model has no image origin information; -i option invalid");

    /* get the target transformation */
    useRef.ctrans.x = hdata.xorg;
    useRef.ctrans.y = hdata.yorg;
    useRef.ctrans.z = hdata.zorg;
    useRef.crot.x = hdata.tiltangles[3];
    useRef.crot.y = hdata.tiltangles[4];
    useRef.crot.z = hdata.tiltangles[5];
    useRef.cscale = unitPt;
    if (hdata.xlen && hdata.mx)
      useRef.cscale.x = hdata.xlen/(float)hdata.mx;
    if (hdata.ylen && hdata.my)
      useRef.cscale.y = hdata.ylen/(float)hdata.my;
    if (hdata.zlen && hdata.mz)
      useRef.cscale.z = hdata.zlen/(float)hdata.mz;
    
    if (modRefp) {

      /* If there is a refImage, scale the data as when reading into 3dmod */
      useRef.otrans = modRefp->ctrans;
      useRef.orot = modRefp->crot;
      useRef.oscale = modRefp->cscale;
      imodTransFromRefImage(&model, &useRef, unitPt);
    } else {

      /* If there is no refImage, do not scale data but assign all the information
         just as if reading into 3dmod */
      model.refImage = (IrefImage *)malloc (sizeof(IrefImage));
      modRefp = model.refImage;
      if (!modRefp) 
        exitError("Allocating a IrefImage structure");
      model.flags |= IMODF_OTRANS_ORIGIN;
    }
    *modRefp = useRef;
    modRefp->otrans = useRef.ctrans;

    /* Adjust the maxes for this change */
    model.xmax = hdata.nx;
    model.ymax = hdata.ny;
    model.zmax = hdata.nz;
  }

  /* Use zscale if user indicated it */
  if (useZscale && model.zscale > 0.)
    zscale = model.zscale;

  /* Do flipping if model flipped and user did not turn it off */
  if (!(model.flags & IMODF_FLIPYZ))
    doflip = 0;

  /* Warning every time is too noxious!
  if (!newNx)
    printf("Assuming transformed images have same size as original "
            "images\n (use -n option to specify size of transformed "
            "images)\n");
  */
  newCen.x = (newNx ? newNx : model.xmax) * 0.5f;
  newCen.y = (newNy ? newNy : model.ymax) * 0.5f;
  newCen.z = (newNz ? newNz : model.zmax) * 0.5f;

  if (filename){
    if (filetrans(filename, &model, mode, oneLine, newCen, zscale, doflip, transScale,
                  transx, transy, transz)) 
      exitError("Transforming model.");

  } else if (transopt) {
    imodTransModel3D(&model, mat, normMat, newCen, zscale, doflip);
  }

  model.xmax = newNx ? newNx : model.xmax;
  model.ymax = newNy ? newNy : model.ymax;
  model.zmax = newNz ? newNz : model.zmax;
  imodWrite(&model, fout);
  exit(0);
}
Example #28
0
/*
 * Main entry
 */
int main( int argc, char *argv[])
{
    Imod *imod;
    Iobj *obj;
    Ipoint point;
    Istore store;
    FILE *infp;
    char line[1024];
    int open = 0, zsort = 0, scat = 0, numPerCont = 0, fromZero = 0, zFromZero = 0;
    int err, nvals, nread, ob, co, lineNum, after, needcont, i, numOffset, linelen;
    int numPts = 0, numConts = 0, numObjs = 0;
    int sphere = 0, circle = 0;
    float tst1, tst2, xx, yy, zz, value;
    float zOffset = 0.;
    int numColors = 0;
    int numNames = 0;
    int hasValues = 0;
    int contValues = 0;
    int *red, *green, *blue;
    int directScale = 0;
    float xscale = 1., yscale = 1., zscale = 1., xtrans = 0., ytrans = 0., ztrans = 0.;
    char **names = NULL;

    char *progname = imodProgName(argv[0]);
    char *filename, *imagename;
    MrcHeader hdata;
    IrefImage *ref;
    FILE *fpimage = NULL;
    char *errString;
    int numOptArgs, numNonOptArgs;

    /* Fallbacks from    ../manpages/autodoc2man 2 1 point2model  */
    int numOptions = 16;
    const char *options[] = {
        "input:InputFile:FN:", "output:OutputFile:FN:", "open:OpenContours:B:",
        "scat:ScatteredPoints:B:", "number:PointsPerContour:I:", "planar:PlanarContours:B:",
        "zero:NumberedFromZero:B:", "zcoord:ZCoordinatesFromZero:B:",
        "values:ValuesInLastColumn:I:", "circle:CircleSize:I:", "sphere:SphereRadius:I:",
        "color:ColorOfObject:ITM:", "name:NameOfObject:CHM:",
        "image:ImageForCoordinates:FN:", "pixel:PixelSpacingOfImage:FT:",
        "origin:OriginOfImage:FT:"
    };

    /* Startup with fallback */
    PipReadOrParseOptions(argc, argv, options, numOptions, progname,
                          2, 1, 1, &numOptArgs, &numNonOptArgs, imodUsageHeader);

    /* Get input and output files */
    if (PipGetInOutFile("InputFile", 0, &filename))
        exitError("No input file specified");
    infp = fopen(filename, "r");
    if (!infp)
        exitError("Error opening input file %s", filename);
    free(filename);
    if (PipGetInOutFile("OutputFile", 1, &filename))
        exitError("No output file specified");

    if (!PipGetString("ImageForCoordinates", &imagename)) {
        fpimage = fopen(imagename, "rb");
        if (!fpimage)
            exitError("Could not open image file for coordinates: %s", imagename);
        if (mrc_head_read(fpimage, &hdata))
            exitError("Reading header from %s", imagename);
        free(imagename);
    }

    directScale = 2 - PipGetThreeFloats("PixelSpacingOfImage", &xscale, &yscale, &zscale)
                  - PipGetThreeFloats("OriginOfImage", &xtrans, &ytrans, &ztrans);
    if (directScale && fpimage)
        exitError("You cannot use -image together with -pixel or -origin");

    err = PipGetInteger("PointsPerContour", &numPerCont);
    err = PipGetInteger("SphereRadius", &sphere);
    err = PipGetInteger("CircleSize", &circle);
    err = PipGetBoolean("OpenContours", &open);
    err = PipGetBoolean("ScatteredPoints", &scat);
    err = PipGetBoolean("PlanarContours", &zsort);
    err = PipGetInteger("ValuesInLastColumn", &hasValues);
    err = PipGetBoolean("ZCoordinatesFromZero", &zFromZero);
    if (zFromZero)
        zOffset = 0.5;
    B3DCLAMP(hasValues, -1, 1);
    if (hasValues < 0) {
        hasValues = 1;
        contValues = 1;
    }
    err = PipGetBoolean("NumberedFromZero", &fromZero);
    numOffset = 1 - fromZero;
    if (numPerCont < 0)
        exitError("Number of points per contour must be positive or zero");
    if (open + scat > 1)
        exitError("Only one of -open or -scat may be entered");

    // Get colors
    err = PipNumberOfEntries("ColorOfObject", &numColors);
    if (numColors) {
        red = (int *)malloc(numColors * sizeof(int));
        green = (int *)malloc(numColors * sizeof(int));
        blue = (int *)malloc(numColors * sizeof(int));
        if (!red || !green || !blue)
            exitError("Allocating memory for colors");
        for (co = 0; co < numColors; co++)
            err = PipGetThreeIntegers("ColorOfObject", &red[co], &green[co],
                                      &blue[co]);
    }

    // Get names
    err = PipNumberOfEntries("NameOfObject", &numNames);
    if (numNames) {
        names = (char **)malloc(numNames * sizeof(char *));
        if (!names)
            exitError("Allocating memory for names");
        for (co = 0; co < numNames; co++)
            err = PipGetString("NameOfObject", &names[co]);
    }

    PipDone();

    // Read first line of file, figure out how many values
    if (fgetline(infp, line, 1024) <= 0)
        exitError("Reading beginning of file");

    nvals = sscanf(line, "%f %f %f %f %f %f", &tst1, &tst2, &xx, &yy, &zz, &value);
    nvals -= hasValues;
    if (nvals < 3)
        exitError("There must be at least %d values per line", 3 + hasValues);
    nvals = B3DMIN(nvals, 5);
    if (numPerCont && nvals > 3) {
        exitError("The point file has contour numbers and the -number option "
                  "cannot be used");
    }
    if (zsort && nvals > 3)
        exitError("The point file has contour numbers and the -planar option "
                  "cannot be used");

    rewind(infp);

    imod = imodNew();
    if (!imod)
        exitError("Failed to get model structure");

    // Set the image reference scaling
    if (fpimage) {
        imodSetRefImage(imod, &hdata);
        fclose(fpimage);
    } else if (directScale) {
        imod->refImage = (IrefImage *)malloc(sizeof(IrefImage));
        if (!imod->refImage)
            exitError("Allocating IrefImage structure");
        ref = imod->refImage;
        ref->ctrans.x = xtrans;
        ref->ctrans.y = ytrans;
        ref->ctrans.z = ztrans;
        ref->cscale.x = xscale;
        ref->cscale.y = yscale;
        ref->cscale.z = zscale;
        ref->oscale.x = ref->oscale.y = ref->oscale.z = 1.;
        ref->orot.x = ref->orot.y = ref->orot.z = 0.;
        ref->crot.x = ref->crot.y = ref->crot.z = 0.;
        ref->otrans.x = ref->otrans.y = ref->otrans.z = 0.;
    }

    ob = 0;
    co = 0;
    lineNum = 0;
    imod->xmax = 0.;
    imod->ymax = 0.;
    imod->zmax = 0.;
    store.type = GEN_STORE_VALUE1;
    store.flags = GEN_STORE_FLOAT << 2;

    // To do: error check contour and object #'s, and they are numbered from 1.
    while (1) {

        // get line, done on EOF, skip blank line
        linelen = fgetline(infp, line, 1024);
        if (linelen < 0)
            break;
        if (linelen == 0)
            continue;

        if (nvals == 3) {
            nread = sscanf(line, "%f %f %f %f", &xx, &yy, &zz, &value);
        } else if (nvals == 4) {
            nread = sscanf(line, "%d %f %f %f %f", &co, &xx, &yy, &zz, &value);
            co -= numOffset;
        } else {
            nread = sscanf(line, "%d %d %f %f %f %f", &ob, &co, &xx, &yy, &zz, &value);
            co -= numOffset;
            ob -= numOffset;
        }
        zz -= zOffset;
        lineNum++;

        // Skip line with no values
        if (nread <= 0)
            continue;
        if (B3DMIN(5 + hasValues, nread) != nvals + hasValues &&
                !(contValues && nread == nvals))
            exitError("Every line should have %d entries; line %d has %d",
                      nvals + hasValues, lineNum, nread);

        if (ob < 0 || co < 0)
            exitError("Illegal object or contour number (object %d, contour %d at line %d",
                      ob + numOffset, co + numOffset, lineNum);

        // Add objects if needed to get to the current object
        if (ob >= imod->objsize) {
            for (i = imod->objsize; i <= ob; i++) {
                if (imodNewObject(imod))
                    exitError("Failed to add object to model");
                if (open)
                    imod->obj[i].flags |= IMOD_OBJFLAG_OPEN;
                if (scat)
                    imod->obj[i].flags |= IMOD_OBJFLAG_SCAT | IMOD_OBJFLAG_OPEN;
                numObjs++;
                imod->obj[i].pdrawsize = B3DMAX(0, sphere);
                if (circle > 0) {
                    imod->obj[i].symsize = circle;
                    imod->obj[i].symbol = IOBJ_SYM_CIRCLE;
                }
                if (i < numColors) {
                    imod->obj[i].red = red[i] / 255.;
                    imod->obj[i].green = green[i] / 255.;
                    imod->obj[i].blue = blue[i] / 255.;
                }
                if (i < numNames) {
                    strncpy(imod->obj[i].name, names[i], IOBJ_STRSIZE - 1);
                    imod->obj[i].name[IOBJ_STRSIZE - 1] = 0x00;
                }
            }
        }

        // Determine if a contour is needed: either the contour number is too high
        // or the number limit is reached or there is a change in Z
        needcont = 0;
        obj = &imod->obj[ob];
        if (co >= obj->contsize)
            needcont = 1;
        else if ((numPerCont && obj->cont[co].psize >= numPerCont) ||
                 (zsort && B3DNINT(obj->cont[co].pts[0].z) != B3DNINT(zz))) {
            co++;
            needcont = 1;
        }

        if (needcont) {
            imodSetIndex(imod, ob, -1, -1);
            for (i = obj->contsize; i<= co; i++) {
                if (imodNewContour(imod))
                    exitError("Failed to add contour to model");
                numConts++;
            }
        }

        point.x = xx;
        point.y = yy;
        point.z = zz;
        imod->xmax = B3DMAX(imod->xmax, B3DNINT(xx + 10.));
        imod->ymax = B3DMAX(imod->ymax, B3DNINT(yy + 10.));
        imod->zmax = B3DMAX(imod->zmax, B3DNINT(zz + 1.));
        if (!imodPointAppend(&obj->cont[co], &point))
            exitError("Failed to add point to contour");
        numPts++;

        // take care of value for contour or point, only add one per contour
        if (hasValues) {
            store.value.f = value;
            err = 0;
            if (contValues && istoreLookup(obj->store, co, &after) < 0) {
                if (nread < nvals + 1)
                    exitError("The first point for a contour must have a value entry; line %d "
                              "has only %d entries", lineNum, nread);
                store.index.i = co;
                err = istoreInsert(&obj->store, &store);
            } else {
                store.index.i = obj->cont[co].psize - 1;
                err = istoreInsert(&obj->cont[co].store, &store);
            }
            if (err)
                exitError("Failed to add general value");
        }
    }

    // Get the object min/max values set up
    if (hasValues) {
        for (ob = 0; ob < imod->objsize; ob++) {
            if (imod->obj[ob].contsize && istoreFindAddMinMax1(&imod->obj[ob]))
                exitError("Adding min/max values to object");
        }
    }

    // Attach image file's size as the max values
    if (fpimage) {
        imod->xmax = hdata.nx;
        imod->ymax = hdata.ny;
        imod->zmax = hdata.nz;
    }

    fclose(infp);
    if (imodBackupFile(filename))
        printf("Warning: %s - Failed to make old version of %s be a backup file\n",
               progname, filename);

    imod->file = fopen(filename, "wb");
    if (!imod->file)
        exitError("Opening new model file %s", filename);
    if (imodWriteFile(imod))
        exitError("Writing model file %s", filename);
    free(filename);
    printf("Model created with %d objects, %d contours, %d points\n", numObjs,
           numConts, numPts);
    exit(0);
}
Example #29
0
void CClctrl::unrecognisedFlag()
{
  exitError("Unrecognised flag: " + getCurrentArgument() + " under " + getMode() +  " command.");
}
Example #30
0
float *SliceCache::getHyperPS(int tileX, int tileY, int whichSlice,
                              double &mean)
{
  if (whichSlice < 0 || whichSlice >= mHeader.nz)
    exitError("slice Num is out of range");
  int sliceIdx = cacheIndex(whichSlice);
  int currCacheSize = mCachedPS.size();
  int tileIdx = tileX + tileY * numXtiles;
  float *retPS;
  int halfSize = mTileSize / 2;
  int tileXdim = mTileSize + 2;
  int fftXdim = tileXdim / 2;
  int idir = 0; //FFT direction;
  int ii, jj, ind, ind2, ix0, iy0;

  if (sliceIdx > -1) { // already in cache
    //if (debugLevel >= 2)
    //  printf("Slice %d is in cache and is included\n", whichSlice);

  } else if (currCacheSize < mMaxSliceNum) { //not in cache and cache not full
    float *newPS = (float *)malloc(mPsArraySize * sizeof(float));
    int *newDone = (int *)malloc(numXtiles * mNumYtiles * sizeof(int));
    float *newMeans = (float *)malloc(numXtiles * mNumYtiles * sizeof(double));
    if (!newPS || !newDone || !newMeans)
      exitError("Allocating memory for power spectra");

    if (debugLevel >= 2)
      printf("Slice %d is NOT in cache and is included \n", whichSlice);

    for (ii = 0; ii < numXtiles * mNumYtiles; ii++)
      newDone[ii] = 0;

    mCachedPS.push_back(newPS);
    mCachedMeans.push_back(newMeans);
    mCachedTileDone.push_back(newDone);
    mCachedSliceMap.push_back(whichSlice);
    mSliceAngles.push_back(readAngle(whichSlice));

    if (mOldestIdx == -1)
      mOldestIdx = currCacheSize;
    sliceIdx = currCacheSize;

  } else { // not in cache and cache is full
    if (debugLevel >= 2)
      printf("Slice %d is NOT in cache and replaces slice %d \n", whichSlice,
             mCachedSliceMap[mOldestIdx]);

    mCachedSliceMap[mOldestIdx] = whichSlice;
    mSliceAngles[mOldestIdx] = readAngle(whichSlice);
    sliceIdx = mOldestIdx;
    mOldestIdx = (mOldestIdx + 1) % mMaxSliceNum;
  }

  fflush(stdout);
  retPS = mCachedPS[sliceIdx] + tileIdx * mPsDim;
  if (mCachedTileDone[sliceIdx][tileIdx]) {
    mean = mCachedMeans[sliceIdx][tileIdx];
    return retPS;
  }

  // Have to compute the power spectrum
  // Read in slice if needed
  if (mCurSlice != whichSlice) {
    // Reallocate as floating point when necessary
    if (mDataOffset && mSliceMode != MRC_MODE_FLOAT) {
      free(mSliceData);
      mSliceData = (float *)malloc(mHeader.nx * mHeader.ny * 4);
      if (!mSliceData)
	exitError("Allocating memory for floating point image slice");
      mSliceMode = MRC_MODE_FLOAT;
    }

    if (mrc_read_slice(mSliceData, mFpStack, &mHeader, whichSlice, 'Z'))
      exitError("Reading slice %d", whichSlice);

    // Apply any offset needed. Done as float to avoid over/underflow.
    if (mDataOffset) {
      unsigned char *bdata = (unsigned char *)mSliceData;
      b3dUInt16 *usdata = (b3dUInt16 *)mSliceData;
      b3dInt16 *sdata = (b3dInt16 *)mSliceData;

      switch (mHeader.mode) {
      case MRC_MODE_BYTE:
	for (ii = mHeader.nx * mHeader.ny - 1; ii >= 0; ii--)
	  mSliceData[ii] = bdata[ii] + mDataOffset;
	break;
      case MRC_MODE_USHORT:
	for (ii = mHeader.nx * mHeader.ny - 1; ii >= 0; ii--)
	  mSliceData[ii] = usdata[ii] + mDataOffset;
	break;
      case MRC_MODE_SHORT:
	for (ii = mHeader.nx * mHeader.ny - 1; ii >= 0; ii--)
	  mSliceData[ii] = sdata[ii] + mDataOffset;
	break;
      case MRC_MODE_FLOAT:
	for (ii = 0; ii < mHeader.nx * mHeader.ny; ii++)
	  mSliceData[ii] += mDataOffset;
	break;
      }
    }
    mCurSlice = whichSlice;
  }

  // get the mTile
  ix0 = tileX * halfSize;
  iy0 = tileY * halfSize;
  sliceTaperInPad(mSliceData, mSliceMode, mHeader.nx, ix0, ix0 + mTileSize - 1,
                  iy0, iy0 + mTileSize - 1, mTile, tileXdim, mTileSize, mTileSize,
                  9, 9);

  // Get its mean and save it
  mean = 0.0;
  for (ii = 0; ii < mTileSize; ii++)
    for (jj = 0; jj < mTileSize; jj++)
      mean += mTile[ii * tileXdim + jj];
  mean /= (mTileSize * mTileSize);
  mCachedMeans[sliceIdx][tileIdx] = mean;

  // FFT and sum into the PS curve
  todfft(mTile, &mTileSize, &mTileSize, &idir);

  for (ii = 0; ii < mPsDim; ii++)
    mPsTmp[ii] = 0.;
  for (ii = 0; ii < mTileSize / 2; ii++) {
    for (jj = 0; jj < fftXdim; jj++) {
      ix0 = ii * fftXdim + jj;
      ind = ii * tileXdim + 2 * jj;
      ind2 = (mTileSize - 1 - ii) * tileXdim + 2 * jj;
      mPsTmp[mTileToPsInd[ix0]] +=
        mTile[ind] * mTile[ind] + mTile[ind + 1] * mTile[ind + 1] +
        mTile[ind2] * mTile[ind2] + mTile[ind2 + 1] * mTile[ind2 + 1];
    }
  }

  // Store into floats and return
  for (ii = 0; ii < mPsDim; ii++) {
    retPS[ii] = mPsTmp[ii];
    //printf("%d  %f\n", mFreqCount[ii], retPS[ii]);
  }
  mCachedTileDone[sliceIdx][tileIdx] = 1;
  return retPS;
}